Log4j2 插件的简单使用

发布于:2024-12-23 ⋅ 阅读:(45) ⋅ 点赞:(0)

代码: TestPlugin.java

package com.chenjiacheng.webapp.plugins;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;

/**
 * Created by chenjiacheng on 2024/12/22 21:08
 *
 * @author chenjiacheng
 * @since 1.0.0
 */
@Plugin(name = "test", category = StrLookup.CATEGORY)
public class TestPlugin implements StrLookup {

    public TestPlugin(){
        System.out.println("TestPlugin.TestPlugin");
    }

    @Override
    public String lookup(String key) {
        return "test";
    }

    @Override
    public String lookup(LogEvent event, String key) {
        return "test";
    }
}

配置: log4j2-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="TRACE" monitorInterval="30">

    <LookupPlugin name="spring">
        <Plugin class="org.apache.logging.log4j.spring.boot.SpringLookup"/>
    </LookupPlugin>

    <Properties>
        <Property name="PROJECT_NAME">${spring:spring.application.name}</Property>
        <Property name="LOG_PATH">./data/logs</Property>
        <Property name="TEST">${test:test.key}</Property>
        <Property name="pattern">[%d{yyyy-MM-dd HH:mm:ss,SSS}] [%c{1.}::%M] [%t] [%p]: %m%n</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="${pattern}"/>
        </Console>
        <RollingFile name="RollingFile" fileName="${LOG_PATH}/${PROJECT_NAME}/${TEST}.log"
                     filePattern="${LOG_PATH}/${date:yyyy-MM-dd}/${PROJECT_NAME}-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${pattern}"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="1024 MB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFile"/>
        </Root>
    </Loggers>
</Configuration>

作用: 对指定环境变量进行解析