log4j2动态修改⽇志级别及拓展性使⽤⼀、供参考的完整⽇志配置
<?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}-%">
<Policies>
<!-- interval单位为filePattern最后⼀个单位,此处为6⼩时,modulate若为true,
则⽇志时间将以0点为边界进⾏偏移计算,由于加了.gz策略,所以此处意思为每隔6⼩时,便会新⽣成⼀个
log4j2的压缩⽂件,当每个⽂件超过250M时,也会新⽣成⼀个log4j2的压缩⽂件 -->
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
log4j2不打印日志</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="ioty" level="warn"/>
<logger name="org.apache.http" level="warn"/>
<logger name="db.driver" level="INFO"/>
<logger name="org.jbossty" level="warn"/>
<logger name="org.dis" level="INFO"/>
</Loggers>
</Configuration>
⼆、动态修改⽇志级别
Collection<org.apache.Logger> current = Context(false).getLoggers();
Collection<org.apache.Logger> notcurrent = Context().getLoggers();
Collection<org.apache.Logger> allConfig = current;
allConfig.addAll(notcurrent);
for (org.apache.Logger log:allConfig){
log.setLevel(Level.DEBUG);
}
三、⾃定义appender
以上介绍,均依赖于log4j2提供的官⽅配置,当对⽇志的业务逻辑复杂时,光靠配置也许满⾜不了需要,此时我们会想⾃⼰能操控打印的⽇志,做⽇志的路由,或保存等操作,这个时候就需要有⾃定义的appender,可以配置的就靠配置完成,不能的就⾃⼰写代码⼲预,⽽log4j2刚好提供了这样的拓展性。
如下代码即是⾃定义的Appender,通过实现AbstractAppender接⼝,配置@Plugin注解对应的信息并在eppend⽅法中写⾃⼰的业务逻辑,从⽽实现了对⽇志更⼤⾃由度的控制,如下展⽰的log4j配置⽂件中的配置节点名称要和注解中配置的name属性⼀致,并在Configuration节点配置好⾃定义Appender所在的包路径即可。
package com.jyk.log4j2.log4j2_test;
import java.io.Serializable;
import urrent.locks.Lock;
import urrent.locks.ReadWriteLock;
import urrent.locks.ReentrantReadWriteLock;
import org.apache.Filter;
import org.apache.Layout;
import org.apache.LogEvent;
import org.apache.appender.AbstractAppender;
import org.apache.appender.AppenderLoggingException;
import org.apache.onfig.plugins.Plugin;
import org.apache.onfig.plugins.PluginAttribute;
import org.apache.onfig.plugins.PluginElement;
import org.apache.onfig.plugins.PluginFactory;
import org.apache.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 = adLock();
//需要实现的构造⽅法,直接使⽤⽗类就⾏
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 ");
} 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) {
<("No name provided for MyCustomAppenderImpl");
return null;
}
if (layout == null) {
layout = ateDefaultLayout();
}
return new MyAppender(name, filter, layout, ignoreExceptions);
}
}
<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>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论