当前位置: 首页 > 工具软件 > mom4j > 使用案例 >

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

王长卿
2023-12-01

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

<?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>

二、动态修改日志级别

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所在的包路径即可。
  Appender的自定义,可以参考log4j-core源码中org.apache.logging.log4j.core.appender.mom包中其它的扩展appender的实现。主要是实现AbstractAppender和AbstractManager。

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);
    }
}

自定义appender配置

<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>
 类似资料: