The use of log4j in the project

Article pre-introduction

 This article will not introduce some concepts of log4j in detail, please check the
previous one: log4j from entry to understanding

  1. The concept of log level, logger, appender, and layout, as well as their corresponding inheritance relationship and the meaning of formatted symbols for detailed layout, this article will not introduce in detail
  2. This article explains in detail the target, Threshold, Append, and additivity tags in the configuration file.

The address of the problem frequently mentioned by log4j

http://logging.apache.org/log4j/1.2/faq.html#noconfig

Use of log4j in maven project

Create a maven project

Insert picture description here

Add dependencies in the pom.xml of the project.

        <!--log4j依赖-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

Add the log4j.properties file to the resources file

Insert picture description here

The following is the content of the file

# 定义一个根记录器,定义其日志级别,console,file,rollfile是自定义的追加器(名称自定义即可,会在后面指定追加器的具体类型)
log4j.rootLogger=INFO,console,file,rollfile,dailyfile,hourfile

## 定义一个追加器的类型为输出到控制台的追加器
log4j.appender.console=org.apache.log4j.ConsoleAppender
#指定当前的追加器打印日志的最低输出级别,默认为debug
log4j.appender.console.Threshold=error
# 输出日志到控制台的方式,其他参数有System.err(当做错误输出,显示为红色)
log4j.appender.console.Target=System.out
# 设置记录器的布局的类型
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# 上面选的布局为自定义的输出格式的类型,所以下面指定输出格式
#  %-5p表示显示日志级别,字符不足五个,在右侧用空格补齐,%d指定日期格式,%c列出记录器的名字空间的全称
#  %L输出日志发生的位置(在代码中的行数)%m你在代码中定义的消息,%n换行
log4j.appender.console.layout.ConversionPattern=[%-5p][%d{
    
    yyyy-MM-dd HH:mm:ss}] %c %L %m%n

##  输出到文件
log4j.appender.file=org.apache.log4j.FileAppender
# 指定输出的位置和文件名
log4j.appender.file.File=d:/logfile.txt
# 指定输出的日志是追加(ture)还是覆盖(false)到指定文件中,默认为ture;
log4j.appender.file.Append=true
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p][%d{
    
    yyyy-MM-dd HH:mm:ss}] %c %L %m%n


##  继承自FileAppender,输出到文件,并且控制文件到达指定大小后生成新的文件
log4j.appender.rollfile=org.apache.log4j.RollingFileAppender
log4j.appender.rollfile.File=d:/logrollfile.txt
#  当达到指定大小时,自动创建另一个文件,
log4j.appender.rollfile.MaxFileSize=2KB
log4j.appender.rollfile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollfile.layout.ConversionPattern=[%-5p][%d{
    
    yyyy-MM-dd HH:mm:ss}] %c %L %m%n

## 单独指定某个包或类打印的日志级别
## log4j.logger.com.emptycloud=debug

##  每天生成一个日志文件
log4j.appender.dailyfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyfile.Threshold=error
log4j.appender.dailyfile.Append=true
log4j.appender.dailyfile.File=D:/logfordailyfile.log
#指定产生新的日志文件后新的日志文件的名称,使用单引号,双引号会在生成新的文件时报错(命名报错)
log4j.appender.dailyfile.DatePattern='.'YYYY-MM-dd
log4j.appender.dailyfile.layout=org.apache.log4j.PatternLayout
# 项目名称-时间-日志级别 - 类名-行号-消息-换行
log4j.appender.dailyfile.layout.ConversionPattern=[log4j-demo] %-d{
    
    yyyy-MM-dd HH:mm:ss:SSS} [%-5p] %c:%l - %m%n

# 每小时生成一个日志文件
log4j.appender.hourfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.hourfile.Threshold=error
log4j.appender.hourfile.Append=true
log4j.appender.hourfile.File=D:/logforhourfile.log
# 每月YYYY-MM 每天YYYY-MM-dd  以此类推
log4j.appender.hourfile.DatePattern='.'YYYY-MM-dd-HH
log4j.appender.hourfile.layout=org.apache.log4j.PatternLayout
log4j.appender.hourfile.layout.ConversionPattern=[log4j-demo] %-d{
    
    yyyy-MM-dd HH:mm:ss:SSS} [%-5p] %c:%l - %m%n

Add logging in the code

In actual use, the logger object is usually configured as a private static final constant in the class, which is commonly used in all methods of the class

public class Log4jDemo {
    
    
    public static void main(String[] args) {
    
    
        //创建记录器
        Logger logger = LogManager.getLogger(Log4jDemo.class);
        //打印不同级别的日志
        logger.trace("这是trace级别的日志");
        logger.debug("这是debug级别的日志222222222222222222222222222222222");
        logger.info("这是info级别的日志");
        logger.warn("这是warn级别的日志");
        logger.fatal("这是fatal日志");
        logger.error("这是error级别日志");
    }
}

You can add a loop to view the file structure generated by its configuration file (modify the time of the system)

Output result

[INFO ][2019-01-31 11:05:05] com.emptycloud.blog.log4jDemo 21 这是info级别的日志
[WARN ][2019-01-31 11:05:05] com.emptycloud.blog.log4jDemo 22 这是warn级别的日志

Insert picture description here

The embodiment of log4j inheritance relationship in the configuration file (introduction of the additivity flag)

  1. Create a java project and add the log4j jar package, and add the configuration file in the root directory
    https://blog.csdn.net/qq_40182873/article/details/86615490
    Insert picture description here 2. According to log4j's inheritance rules, the appenders in the configuration file are all Belongs to the root logger, and the logger created in a separate class will inherit upwards to the appender of the root logger.
    Now we need this inheritance relationship
    in the middle section . 1. Use the setAdditivity method in the code and set it to false, but this It may cause you to configure the corresponding appender and layout separately in the configuration file or class
    2. Configure in the configuration file
log4j.rootLogger=debug,console

log4j.logger.com.emptyCloud.blog=error,sonlogger
# 打断logger的继承关系
# log4j.additivity.com.emptyCloud.blog=false

log4j.appender.sonlogger=org.apache.log4j.ConsoleAppender
log4j.appender.sonlogger.Target=System.out
log4j.appender.sonlogger.layout=org.apache.log4j.PatternLayout
log4j.appender.sonlogger.layout.ConversionPattern=[sonlogger][%-5p][%d{
    
    yyyy-MM-dd HH:mm:ss}] %c %L %m%n

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[rootlogger][%-5p][%d{
    
    yyyy-MM-dd HH:mm:ss}] %c %L %m%n

3. The corresponding code is the same as above

  1. Explanation
     Then there are three loggers named rootloogger, com.emptyCloud.blog (the two are configured in the configuration file) and com.emptyCloud.blog.log4jDemo (created in the code).
      log4j judges its inheritance relationship according to its name. This is introduced in [log4j from entry to understanding][ https://blog.csdn.net/qq_40182873/article/details/86525547#_44 ]
    The following is the corresponding output
[sonlogger][FATAL][2019-02-13 16:03:49] com.emptyCloud.blog.log4jDemo 26 这是fatal日志
[rootlogger][FATAL][2019-02-13 16:03:49] com.emptyCloud.blog.log4jDemo 26 这是fatal日志
[sonlogger][ERROR][2019-02-13 16:03:49] com.emptyCloud.blog.log4jDemo 27 这是error级别日志
[rootlogger][ERROR][2019-02-13 16:03:49] com.emptyCloud.blog.log4jDemo 27 这是error级别日志

After removing the comment of the configuration file

[sonlogger][FATAL][2019-02-13 16:04:52] com.emptyCloud.blog.log4jDemo 26 这是fatal日志
[sonlogger][ERROR][2019-02-13 16:04:52] com.emptyCloud.blog.log4jDemo 27 这是error级别日志

It can be seen from this that the level of the bottom logger print log is inherited from the nearest parent logger, and then if the inheritance relationship of the logger is not interrupted, it will print the log once, and its parent logger will also print it again. Log

  1. Note that
    log4j.additivity and log4j.logger are followed by the name of the logger. When configuring, pay attention to the inheritance relationship as needed
    . This is mainly用于项目中个别包打印和根记录器不同的日志级别

Introduction to log4j's xml type configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration>
    <!--输出到控制台-->
    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="DEBUG"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </layout>
    </appender>

    <!--输出到文件(info)-->
    <!--将生成“info.log.2014-06-11”这样的日志文件-->
    <appender name="fileAppenderInfo" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${user.home}/logs/website/info.log" />
        <param name="DatePattern" value=".yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="INFO" />
            <param name="LevelMax" value="INFO" />
        </filter>
    </appender>

    <!--输出到文件(warn)-->
    <appender name="fileAppenderWarn" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${user.home}/logs/website/warn.log" />
        <param name="DatePattern" value=".yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </layout>

        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="WARN" />
            <param name="LevelMax" value="WARN" />
        </filter>
    </appender>

    <!--输出到文件(error)-->
    <appender name="fileAppenderError" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${user.home}/logs/website/error.log" />
        <param name="DatePattern" value=".yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="ERROR" />
            <param name="LevelMax" value="ERROR" />
        </filter>
    </appender>

    <!--屏蔽所有org.springframework.*输出的Debug(及以下)信息-->
    <logger name="org.springframework">
        <level value="INFO"></level>
    </logger>

    <root>
        <level value="ALL"/>
        <appender-ref ref="consoleAppender" />
        <appender-ref ref="fileAppenderInfo" />
        <appender-ref ref="fileAppenderWarn" />
        <appender-ref ref="fileAppenderError" />
    </root>
</log4j:configuration>

Transfer from Jiang Guogang’s technical blog
& emsp; I feel that the xml format configuration file structure is clearer, but I still like the properties type configuration file

Here controls the output log level of a single appender in properties as follows:

log4j.appender.console.filter.infoFilter = org.apache.log4j.varia.LevelRangeFilter
log4j.appender.console.filter.infoFilter.LevelMin=INFO
log4j.appender.console.filter.infoFilter.LevelMax=INFO

The role of isDebugEnabled in log4j

isDebugEnabled role

Other links

  1. The message is logged to the database jabcAppender
  2. Configuration of log4j in web.xml
  3. Dynamic path configuration of log4j
  4. Dynamic configuration of log4j in the program

Guess you like

Origin blog.csdn.net/qq_40182873/article/details/86706355