log4j2动态修改日志级别及拓展性使用详解

时间:2022-06-09 03:28:01

一、供参考的完整日志配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?xml version="1.0" encoding="utf-8"?>
 
<!-- 配置loggerconfig,即appenders的日志级别为warn -->
<configuration status="warn">
 
  <!-- 定义下面的引用名 -->
  <properties>
    <property name="basepath">${sys:vmparam}</property>
    <property name="filepath">${basepath}/app.log</property>
  </properties>
 
  <!-- appenders支持配置多个appender,支持向不同的目标输送日志,本例为配置向控制台输出 -->
  <appenders>
    <console name="console" target="system_out">
      <patternlayout pattern="%d{hh:mm:ss.sss} [%t] %-5level %logger{36} - %msg%n" />
    </console>
 
    <!-- 将日志输出到指定位置的文件中 -->
    <rollingfile name="rollingfile" filename="${filepath}"
      filepattern="logs/$${date:yyyy-mm}/app-%d{yyyy-mm-dd-hh}-%i.log.gz">
      <policies>
        <!-- interval单位为filepattern最后一个单位,此处为6小时,modulate若为true
        则日志时间将以0点为边界进行偏移计算,由于加了.gz策略,所以此处意思为每隔6小时,便会新生成一个
        log4j2的压缩文件,当每个文件超过250m时,也会新生成一个log4j2的压缩文件 -->
        <timebasedtriggeringpolicy interval="6" modulate="true"/>
        <sizebasedtriggeringpolicy size="250 mb"/>
      </policies>
      <!-- 滚动策略,日志文件最多保留20个 -->
      <defaultrolloverstrategy max="20"/>
 
      <!-- 最多备份30天以内||日志文件大小达到100gb的日志||文件数量超过十个
      此处为策略限制,delete中可以按自己需要用正则表达式编写 -->
      <defaultrolloverstrategy>
        <delete basepath="${filepath}" maxdepth="1">
          <iffilename glob="logs_*.log" />
          <iflastmodified age="30d" />
          <ifaccumulatedfilesize exceeds="100 gb" />
          <ifaccumulatedfilecount exceeds="10" />
        </delete>
      </defaultrolloverstrategy>
    </rollingfile>
  </appenders>
 
  <!-- loggers支持配置多个logger,可引用不同的目标appender,也可根据业务需求定制特定要求的appender -->
  <loggers>
    
    <asynclogger name="asynclogger" level="trace">
      <appender-ref ref="console" />
      <appender-ref ref="rollingfile" />
    </asynclogger>
 
    <asyncroot level="trace">
      <appender-ref ref="console" />
    </asyncroot>
    
    <root level="info">
      <!-- <appenderref ref="console" /> -->
      <appenderref ref="rollingfile" />
    </root>
    
    <!-- 第三方日志系统 -->
    <logger name="org.springframework" level="info" additivity="false">
      <appender-ref ref="console" />
    </logger>
    <logger name="io.netty" level="warn"/>
    <logger name="org.apache.http" level="warn"/>
    <logger name="org.mongodb.driver" level="info"/>
    <logger name="org.jboss.netty" level="warn"/>
    <logger name="org.springframework.data.redis" level="info"/>
  </loggers>
</configuration>

二、动态修改日志级别

?
1
2
3
4
5
6
7
collection<org.apache.logging.log4j.core.logger> current = loggercontext.getcontext(false).getloggers();
collection<org.apache.logging.log4j.core.logger> notcurrent = loggercontext.getcontext().getloggers();
collection<org.apache.logging.log4j.core.logger> allconfig = current;
allconfig.addall(notcurrent);
for (org.apache.logging.log4j.core.logger log:allconfig){
  log.setlevel(level.debug);
} 

三、自定义appender

以上介绍,均依赖于log4j2提供的官方配置,当对日志的业务逻辑复杂时,光靠配置也许满足不了需要,此时我们会想自己能操控打印的日志,做日志的路由,或保存等操作,这个时候就需要有自定义的appender,可以配置的就靠配置完成,不能的就自己写代码干预,而log4j2刚好提供了这样的拓展性。

如下代码即是自定义的appender,通过实现abstractappender接口,配置@plugin注解对应的信息并在eppend方法中写自己的业务逻辑,从而实现了对日志更大*度的控制,如下展示的log4j配置文件中的配置节点名称要和注解中配置的name属性一致,并在configuration节点配置好自定义appender所在的包路径即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.jyk.log4j2.log4j2_test;
 
import java.io.serializable;
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.readwritelock;
import java.util.concurrent.locks.reentrantreadwritelock;
import org.apache.logging.log4j.core.filter;
import org.apache.logging.log4j.core.layout;
import org.apache.logging.log4j.core.logevent;
import org.apache.logging.log4j.core.appender.abstractappender;
import org.apache.logging.log4j.core.appender.appenderloggingexception;
import org.apache.logging.log4j.core.config.plugins.plugin;
import org.apache.logging.log4j.core.config.plugins.pluginattribute;
import org.apache.logging.log4j.core.config.plugins.pluginelement;
import org.apache.logging.log4j.core.config.plugins.pluginfactory;
import org.apache.logging.log4j.core.layout.patternlayout;
 
@plugin(name = "myappender", category = "core", elementtype = "appender", printobject = true)
public class myappender extends abstractappender {
 
  /**
   * @fields serialversionuid
   */
  private static final long serialversionuid = -830237775522429777l;
  private final readwritelock rwlock = new reentrantreadwritelock();
  private final lock readlock = rwlock.readlock();
 
  //需要实现的构造方法,直接使用父类就行
  protected myappender(final string name, final filter filter, final layout<? extends serializable> layout,
      final boolean ignoreexceptions) {
    super(name, filter, layout, ignoreexceptions);
  }
 
  @override
  public void append(logevent event) {
    readlock.lock();
    try {
      final byte[] bytes = getlayout().tobytearray(event);//日志二进制文件,输出到指定位置就行
      
      //拿到每次打印的日志,写自己的业务逻辑
      system.out.println("enter my append...");
    } catch (exception ex) {
      if (!ignoreexceptions()) {
        throw new appenderloggingexception(ex);
      }
    } finally {
      readlock.unlock();
    }
  }
 
  // 下面这个方法可以接收配置文件中的参数信息
  @pluginfactory
  public static myappender createappender(@pluginattribute("name") string name,
      @pluginelement("filter") final filter filter,
      @pluginelement("layout") layout<? extends serializable> layout,
      @pluginattribute("ignoreexceptions") boolean ignoreexceptions) {
    if (name == null) {
      logger.error("no name provided for mycustomappenderimpl");
      return null;
    }
    if (layout == null) {
      layout = patternlayout.createdefaultlayout();
    }
    return new myappender(name, filter, layout, ignoreexceptions);
  }
}
?
1
2
3
4
5
<configuration status="warn" packages="com.jyk.log4j2.log4j2_test">
 
<myappender name="textarea">
      <patternlayout pattern="%d{hh:mm:ss.sss} [%t] %-5level %logger{36} - %msg%n" />
</myappender>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/jiyukai/p/9420833.html