Use the log management -log4j and slf4j

Excerpt: https://www.cnblogs.com/zhh19981104/p/12133730.html

I. Overview

1, Log4j:

Apache Log4j is an open source project, through the use of Log4j, we can control the destination log information delivery is the console, files, GUI components, or even socket servers, NT event logger, UNIX Syslog daemon etc; we also you can control the output format of each log; each defined by a level of log information, we were able to more carefully control the log generation process. The most interesting is that these can be flexibly configured via a configuration file, without modifying the application code.

 

2, slf4j:

SLF4J, namely simple log facade (Simple Logging Facade for Java), not specific logging solution, which only serve a wide variety of system logs. Officially, SLF4J is a Facade for simple logging system that allows end users to use their desired log system when deploying their applications. In fact, SLF4J provided some core API interface and a factory class of LoggerFactory. To some extent, JDBC SLF4J somewhat similar, but simpler than JDBC, the JDBC, you need to specify the driver, and when using SLF4J does not require or specify the configuration file you plan to use in the code that specific log system. As with JDBC substantially the same regardless of the particular database, the SLF4J provides a uniform interface to log, as long as it provides a recording method according to the format of the final logging, logging level, and the like output by configuring the specific logging system, flexible logging system can be switched in the application.

 

Second, practice

1, import the corresponding jar package, recommended maven project import.

 

  Introducing a, manner using conventional jar

                                                                    

   

  b, using maven project into

Copy the code
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.turtle</groupId>
  <artifactId>log</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>log</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>

  </dependencies>

</project>
Copy the code

 

 

 2, write test code:

Copy the code
com.turtle.log Package; 

Import com.turtle.OutputStreamUtil; 
Import org.slf4j.Logger; 
Import org.slf4j.LoggerFactory; 
Import the java.text.SimpleDateFormat; 
Import java.util.Date; 

public {class TestLog_01 

    Private Final static Logger = LoggerFactory.getLogger Logger (TestLog_01.class); 

    public static void main (String [] args) { 
        logger.info ( "programer Processing ......"); 
        the try { 
            // the abnormality information generated division by 0 
            System.out.println (1/0); 
        } the catch (exception E) { 
            // the abnormality information is printed to the log file 
            String = exception new new OutputStreamUtil () util (E);. 
            // output log file
            logger.error("Programer error:"+ exception+"\t"+"【"+new SimpleDateFormat("yyyy-MM-dd/HH.mm.ss").format(new Date())+"】");
        }
        logger.debug("start Debug detail......");
    }
}
Copy the code

 

3, the configuration file

Levels log ### SET ### 
Log4j.rootLogger = the DEBUG, stdout, D, E

# log information output destination
log4j.appender.stdout = org.apache.log4j.ConsoleAppender tells that
# the Target is the target output destination
log4j. = the System.out appender.stdout.Target
# log information specified minimum level of output
log4j.appender.stdout.Threshold the INFO =
# define named stdout output of layout types
log4j.appender.stdout.layout = org.apache.log4j. the PatternLayout
# If a specific pattern layout will print format specification information ConversionPattern
log4j.appender.stdout.layout.ConversionPattern = [% -5p]% {D the mM-dd-YYYY HH: mm: SS} m%%% L the n-



# handle name corresponding log D of
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
filename # file is the output destination
log4j.appender.D.File = lOG // app_debug.log
#false: defaults is true, will be designated to file, false refers to the contents of the file specified by the news coverage
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.TTCCLayout



# 名字为E的对应日志处理
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = LOG//app_error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

 

 

Third, the detailed explanation

1, og4j defines eight levels of log (removal and OFF ALL, can be said to be divided into six levels)

Descending order of priority: OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL.

  •     ALL LEVEL lowest level, to open all logging.
  •     TRACE log level is very low, generally do not use.
  •     DEBUG pointed out that fine-grained information events for debugging applications are very helpful, mainly for the development process of the print run of some information.
  •     INFO messages on a coarse-grained level to highlight the process of running the application. Print some of your interesting or important information, this information may be used in some important production environments running output, but not abuse, avoid printing too many logs.
  •     WARN 表明会出现潜在错误的情形,有些信息不是错误信息,但是也要给程序员的一些提示。
  •     ERROR 指出虽然发生错误事件,但仍然不影响系统的继续运行。打印错误和异常信息,如果不想输出太多的日志,可以使用这个级别。
  •     FATAL 指出每个严重的错误事件将会导致应用程序的退出。这个级别比较高了。重大错误,这种级别你可以直接停止程序了。
  •     OFF LEVEL 最高等级的,用于关闭所有日志记录。

  如果将log level设置在某一个级别上,那么比此级别优先级高的log都能打印出来。例如,如果设置优先级为WARN,那么OFF、FATAL、ERROR、WARN 4个级别的log能正常输出,而INFO、DEBUG、TRACE、 ALL级别的log则会被忽略。Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG。

 

2、rootLogger = DEBUG,stdout,D,E   #配置根logger,

基本格式为 log4j.rootLogger = LEVEL, appenderName1 ,  appenderName2  ,只能有一个等级的哦,不能存在多个等级,否则会报错

 

3、log4j.appender.stdout=org.apache.log4j.ConsoleAppender  #配置日志信息输出目的地Appender

  •   org.apache.log4j.ConsoleAppender(控制台)
  •   org.apache.log4j.FileAppender(文件)
  •   org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
  •   org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
  •   org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)

 

4、Target , File 分别就是输出目的地的目标、文件名啦。此处可将相应的内容写到相应的目的地及文件中.

 

5、Append=false:默认值是true,即将消息增加到指定文件中,false指将消息覆盖指定的文件内容。

 

6、Threshold=DEBUG:指定日志消息的输出最低层次。

  应当注意每个appender的级别应该是不同的,比如error类的单独放到一个文件中,更方便我们排除错误,所以推荐对不同级别的日志输出到不同的日志文件中。

 

7、当选择RollingFileAppender时,MaxFileSize=100KB

  后缀可以是KB, MB 或者是 GB. 在日志文件到达该大小时,将会自动滚动,即将原来的内容移到mylog.log.1文件。MaxBackupIndex=2:指定可以产生的滚动文件的最大数。

 

8、log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  # 定义名为stdout的输出端的layout类型

  •   org.apache.log4j.HTMLLayout(以HTML表格形式布局)
  •   org.apache.log4j.PatternLayout(可以灵活地指定布局模式)
  •   org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
  •   org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)

 

9、log4j.appender.stdout.layout.ConversionPattern= [%-5p] %d{yyyy-MM-dd HH:mm:ss} %l%m%n 

如果使用pattern布局就要指定的打印信息的具体格式ConversionPattern,打印参数如下:

  •   %p: 输出日志信息优先级,即DEBUG,INFO,WARN,ERROR,FATAL,
  •   %r: 输出自应用启动到输出该log信息耗费的毫秒数
  •   %c: 输出日志信息所属的类目,通常就是所在类的全名
  •   %t: 输出产生该日志事件的线程名
  •   %l: 输出日志事件的发生位置,相当于%C.%M(%F:%L)的组合,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main (TestLog4.Java:10)
  •   %x: 输出和当前线程相关联的NDC(嵌套诊断环境),尤其用到像Java servlets这样的多客户多线程的应用中。
  •   %%: 输出一个"%"字符
  •   %F: 输出日志消息产生时所在的文件名称
  •   %L: 输出代码中的行号
  •   %m: 输出代码中指定的消息,产生的日志具体信息 (注意下文log的使用时传入的参数)
  •   %n: 输出一个回车换行符,Windows平台为"/r/n",Unix平台为"/n"输出日志信息换行
  •   %d: 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式

  可以在%与模式字符之间加上修饰符来控制其最小宽度、最大宽度、和文本的对齐方式。如:

  •   %20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,默认的情况下右对齐。
  •   %-20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,"-"号指定左对齐。
  •   %.30c:指定输出category的名称,最大的宽度是30,如果category的名称大于30的话,就会将左边多出的字符截掉,但小于30的话也不会有空格。
  •   %20.30c:如果category的名称小于20就补空格,并且右对齐,如果其名称长于30字符,就从左边较远输出的字符截掉。

四、案例:

运行对应的代码,就可以得到对应的日志,这是log4j与slf4j日志系统的使用         

                                                               

 

代码:

  com.turtle.log.LogTest
  com.turtle.log1.LogTest
  com.turtle.log2.LogTest
  com.turtle.utils.ExceptionOutputStreamUtil
  log4j.properties
  pom.xml

 

五、总结:

日志的关键配置包括输出目标,信息等级,文件形式和格式控制,各个配置灵活调整,可在不同的文件中找到不同的有用的信息,格式控制中%c/%t/%l在一个庞大的项目中十分有用。有些配置文件自己老是会忘记,所以花点时间,把log4j与slf4j的使用进行一个汇总,总结一下,理出属于自己的思路,方便后面的复习。

 
标签:  Java

一、概述

1、log4j:

Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

 

2、slf4j:

SLF4J,即简单日志门面(Simple Logging Facade for Java),不是具体的日志解决方案,它只服务于各种各样的日志系统。按照官方的说法,SLF4J是一个用于日志系统的简单Facade,允许最终用户在部署其应用时使用其所希望的日志系统。实际上,SLF4J所提供的核心API是一些接口以及一个LoggerFactory的工厂类。从某种程度上,SLF4J有点类似JDBC,不过比JDBC更简单,在JDBC中,你需要指定驱动程序,而在使用SLF4J的时候,不需要在代码中或配置文件中指定你打算使用那个具体的日志系统。如同使用JDBC基本不用考虑具体数据库一样,SLF4J提供了统一的记录日志的接口,只要按照其提供的方法记录即可,最终日志的格式、记录级别、输出方式等通过具体日志系统的配置来实现,因此可以在应用中灵活切换日志系统。

 

二、实践

1、导入对应的jar包,推荐使用maven工程导入。

 

  a、使用传统jar的方式引入

                                                                    

   

  b、使用maven工程导入

Copy the code
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.turtle</groupId>
  <artifactId>log</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>log</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>

  </dependencies>

</project>
Copy the code

 

 

 2、编写测试代码:

Copy the code
package com.turtle.log;

import com.turtle.OutputStreamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestLog_01 {

    private final static Logger logger = LoggerFactory.getLogger(TestLog_01.class);

    public static void main(String[] args) {
        logger.info("programer processing......");
        try{
            // 会产生除以0的异常信息
            System.out.println(1/0);
        }catch (Exception e){
            // 将异常信息打印到日志文件中去
            String exception = new OutputStreamUtil().util(e);
            // 输出日志文件
            logger.error("Programer error:"+ exception+"\t"+"【"+new SimpleDateFormat("yyyy-MM-dd/HH.mm.ss").format(new Date())+"】");
        }
        logger.debug("start Debug detail......");
    }
}
Copy the code

 

3、配置文件

### set log levels ###
log4j.rootLogger = DEBUG,stdout,D,E

# 配置日志信息输出目的地
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
# Target是输出目的地的目标
log4j.appender.stdout.Target = System.out
# 指定日志消息的输出最低层次
log4j.appender.stdout.Threshold = INFO
# 定义名为stdout的输出端的layout类型
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
# 如果使用pattern布局就要指定的打印信息的具体格式ConversionPattern
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss} %l%m%n



# 名字为D的对应日志处理
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
# File是输出目的地的文件名
log4j.appender.D.File = LOG//app_debug.log
#false:默认值是true,即将消息增加到指定文件中,false指将消息覆盖指定的文件内容
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.TTCCLayout



# 名字为E的对应日志处理
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = LOG//app_error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

 

 

三、详细解释

1、og4j定义了8个级别的log(除去OFF和ALL,可以说分为6个级别)

优先级从高到低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL。

  •     ALL LEVEL 最低等级的,用于打开所有日志记录。
  •     TRACE 很低的日志级别,一般不会使用。
  •     DEBUG 指出细粒度信息事件对调试应用程序是非常有帮助的,主要用于开发过程中打印一些运行信息。
  •     INFO 消息在粗粒度级别上突出强调应用程序的运行过程。打印一些你感兴趣的或者重要的信息,这个可以用于生产环境中输出程序运行的一些重要信息,但是不能滥用,避免打印过多的日志。
  •     WARN 表明会出现潜在错误的情形,有些信息不是错误信息,但是也要给程序员的一些提示。
  •     ERROR 指出虽然发生错误事件,但仍然不影响系统的继续运行。打印错误和异常信息,如果不想输出太多的日志,可以使用这个级别。
  •     FATAL 指出每个严重的错误事件将会导致应用程序的退出。这个级别比较高了。重大错误,这种级别你可以直接停止程序了。
  •     OFF LEVEL 最高等级的,用于关闭所有日志记录。

  如果将log level设置在某一个级别上,那么比此级别优先级高的log都能打印出来。例如,如果设置优先级为WARN,那么OFF、FATAL、ERROR、WARN 4个级别的log能正常输出,而INFO、DEBUG、TRACE、 ALL级别的log则会被忽略。Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG。

 

2、rootLogger = DEBUG,stdout,D,E   #配置根logger,

基本格式为 log4j.rootLogger = LEVEL, appenderName1 ,  appenderName2  ,只能有一个等级的哦,不能存在多个等级,否则会报错

 

3、log4j.appender.stdout=org.apache.log4j.ConsoleAppender  #配置日志信息输出目的地Appender

  •   org.apache.log4j.ConsoleAppender(控制台)
  •   org.apache.log4j.FileAppender(文件)
  •   org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
  •   org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
  •   org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)

 

4、Target , File 分别就是输出目的地的目标、文件名啦。此处可将相应的内容写到相应的目的地及文件中.

 

5、Append=false:默认值是true,即将消息增加到指定文件中,false指将消息覆盖指定的文件内容。

 

6、Threshold=DEBUG:指定日志消息的输出最低层次。

  应当注意每个appender的级别应该是不同的,比如error类的单独放到一个文件中,更方便我们排除错误,所以推荐对不同级别的日志输出到不同的日志文件中。

 

7、当选择RollingFileAppender时,MaxFileSize=100KB

  后缀可以是KB, MB 或者是 GB. 在日志文件到达该大小时,将会自动滚动,即将原来的内容移到mylog.log.1文件。MaxBackupIndex=2:指定可以产生的滚动文件的最大数。

 

8、log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  # 定义名为stdout的输出端的layout类型

  •   org.apache.log4j.HTMLLayout(以HTML表格形式布局)
  •   org.apache.log4j.PatternLayout(可以灵活地指定布局模式)
  •   org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
  •   org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)

 

9、log4j.appender.stdout.layout.ConversionPattern= [%-5p] %d{yyyy-MM-dd HH:mm:ss} %l%m%n 

如果使用pattern布局就要指定的打印信息的具体格式ConversionPattern,打印参数如下:

  •   %p: 输出日志信息优先级,即DEBUG,INFO,WARN,ERROR,FATAL,
  •   %r: 输出自应用启动到输出该log信息耗费的毫秒数
  •   %c: 输出日志信息所属的类目,通常就是所在类的全名
  •   %t: 输出产生该日志事件的线程名
  •   %l: 输出日志事件的发生位置,相当于%C.%M(%F:%L)的组合,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main (TestLog4.Java:10)
  •   %x: 输出和当前线程相关联的NDC(嵌套诊断环境),尤其用到像Java servlets这样的多客户多线程的应用中。
  •   %%: 输出一个"%"字符
  •   %F: 输出日志消息产生时所在的文件名称
  •   %L: 输出代码中的行号
  •   %m: 输出代码中指定的消息,产生的日志具体信息 (注意下文log的使用时传入的参数)
  •   %n: 输出一个回车换行符,Windows平台为"/r/n",Unix平台为"/n"输出日志信息换行
  •   %d: 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式

  可以在%与模式字符之间加上修饰符来控制其最小宽度、最大宽度、和文本的对齐方式。如:

  •   %20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,默认的情况下右对齐。
  •   %-20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,"-"号指定左对齐。
  •   %.30c:指定输出category的名称,最大的宽度是30,如果category的名称大于30的话,就会将左边多出的字符截掉,但小于30的话也不会有空格。
  •   %20.30c:如果category的名称小于20就补空格,并且右对齐,如果其名称长于30字符,就从左边较远输出的字符截掉。

四、案例:

运行对应的代码,就可以得到对应的日志,这是log4j与slf4j日志系统的使用         

                                                               

 

代码:

  com.turtle.log.LogTest
  com.turtle.log1.LogTest
  com.turtle.log2.LogTest
  com.turtle.utils.ExceptionOutputStreamUtil
  log4j.properties
  pom.xml

 

V. Summary:

Key configuration log includes an output target, the level of information, file format, and format control, each flexible configuration adjustments can find different useful information in different files, the format of Control% c /% t /% l in a large the project is very useful. Some configuration files themselves always forget, so take the time and use the log4j slf4j be a summary, to sum up, sort out their own ideas, to facilitate later review.

Guess you like

Origin www.cnblogs.com/xichji/p/12143121.html