java相关:log4j2动态修改日志级别及拓展性使用详解
发布于 2021-1-28|
复制链接
摘记: 一、供参考的完整日志配置
```xml
..
一、供参考的完整日志配置
```xml
${sys:vmparam}
${basePath}/app.log
-->
```
二、动态修改日志级别
```java
Collection current = LoggerContext.getContext(false).getLoggers();
Collection notcurrent = LoggerContext.getContext().getLoggers();
Collection 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所在的包路径即可。
```java
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 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 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);
}
}
```
```xml
```