<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="false" debug="false">
<springProperty scop="context" name="spring.application.name" source="spring.application.name" defaultValue="app"/>
<property name="log.home" value="logs"/>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ---> [%thread] ---> %-5level %logger{50} - %msg%n</pattern>
</layout>
</appender>
<appender name="appLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.home}/${spring.application.name}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.home}/${appName}-%d{yyyy-MM-dd}-%i.log</fileNamePattern>
<MaxHistory>365</MaxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern>
</layout>
</appender>
<!--采集业务日志写入组件-->
<appender name="crawlerUserAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${log.home}/crawler.log</File>
<append>true</append>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<!-- <onMatch>ACCEPT</onMatch>-->
<!-- <onMismatch>DENY</onMismatch>-->
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.home}/crawler.log.%d</fileNamePattern>
<maxHistory>12</maxHistory>
</rollingPolicy>
<encoder charset="UTF-8">
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] %level [%thread] %file:%line - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!--采集业务日志名称及组件配置-->
<logger name="crawlerUser" additivity="false">
<appender-ref ref="crawlerUserAppender"/>
</logger>
<root level="info">
<appender-ref ref="stdout"/>
<appender-ref ref="appLogAppender"/>
</root>
</configuration>
整体实现上,通过配置一个appender、logger,然后在类文件中通过logger名称可以实现一类业务日志。
上述的logback-spring.xml文件中appender为crawlerUserAppender;logger为crawlerUser,在类中调用方式如下:
private static Logger crawlerLogger = LoggerFactory.getLogger("crawlerUser");
通过日志名称来获取Logger对象,写入文件中,写入的数据示例如下,
[2021-06-02 14:33:52.963] INFO [http-nio-18002-exec-1] TestController.java:55 - 请求getUserList()方法,请求参数:18, 参数名称:xxx
[2021-06-02 14:34:03.084] INFO [http-nio-18002-exec-2] TestController.java:32 - 请求test()方法
[2021-06-02 14:35:17.924] INFO [http-nio-18002-exec-5] TestController.java:43 - 请求getUserListByPage()方法