将指定日志输出到指定文件

需求就是要将某个类中的日志输出到某个文件中,配置和代码如下:

 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

    
<Appenders>
    <!-- 用于客户端日志上报 -->
    <RollingRandomAccessFile name="CLIENT_LOG"
                                 fileName="${LOG_HOME}/${APP_NAME}_${INFO_LOG_FILE_NAME}_Client_Log.log"
                                 filePattern="${LOG_HOME}/${APP_NAME}_${INFO_LOG_FILE_NAME}_Client_Log.log.%d{yyyy-MM-dd}.gz">
        <PatternLayout pattern="${LOG_PATTERN}"/>
        <Filters>
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
        </Filters>
        <Policies>
            <TimeBasedTriggeringPolicy/>
            <SizeBasedTriggeringPolicy size="128MB"/>
        </Policies>
        <DefaultRolloverStrategy max="30"/>
    </RollingRandomAccessFile>
    
    <!-- 用于硬件信息上报 -->
    <RollingRandomAccessFile name="CLIENT_CALIBRATION_REPORT"
                                 fileName="${LOG_HOME}/${APP_NAME}_${INFO_LOG_FILE_NAME}_Client_Calibration_Report.log"
                                 filePattern="${LOG_HOME}/${APP_NAME}_${INFO_LOG_FILE_NAME}_Client_Calibration_Report.log.%d{yyyy-MM-dd}.gz">
        <PatternLayout pattern="${LOG_PATTERN}"/>
        <Filters>
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
        </Filters>
        <Policies>
            <TimeBasedTriggeringPolicy/>
            <SizeBasedTriggeringPolicy size="128MB"/>
        </Policies>
        <DefaultRolloverStrategy max="30"/>
    </RollingRandomAccessFile>
</Appenders>

    
<Loggers>
    <AsyncLogger name="com.sdstc.message.service.impl.ClientLogServiceImpl" level="debug" includeLocation="true">
        <appender-ref ref="CLIENT_LOG"/>
    </AsyncLogger>
    <AsyncLogger name="com.sdstc.message.service.impl.ClientCalibrationReportServiceImpl" level="debug"
                     includeLocation="true">
        <appender-ref ref="CLIENT_CALIBRATION_REPORT"/>
    </AsyncLogger>
</Loggers>

代码中就是普通的获取Logger,然后进行日志输出。

参考资料

  1. 【log4j2打印日志】指定日志打印到指定文件