1.日志不仅用于排查问题,查看应用运行情况
2.更可以用于统计,虽然统计可以通过数据库进行统计,但存在风险,如果用日志,并且建议一个日志系统用于分析
为了日后产品大数据分析以及运营人员分析数据
3.写日志,可以加缓存buffer,也可以进行异步
下面这段xml文件放在resources目录下
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!--日志布局 时间格式 日记级别 方法 线程-->
<appender name="consoleApp" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</layout>
</appender>
<!--用于统计-->
<appender name="dataApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>
`%date{yyyy-MM-dd HH:mm:ss.SSS}`%msg`%n
</pattern>
</encoder>
<!-- 滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路径 保存一个月-->
<fileNamePattern>app_log/log/app.data.%d.log</fileNamePattern>
<MaxHistory>1</MaxHistory>
</rollingPolicy>
</appender>
<appender name="fileInfoApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路径 -->
<fileNamePattern>app_log/log/app.info.%d.log</fileNamePattern>
<MaxHistory>1</MaxHistory>
</rollingPolicy>
</appender>
<appender name="fileErrorApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
</pattern>
</encoder>
<!-- 设置滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路径 -->
<fileNamePattern>app_log/log/app.err.%d.log</fileNamePattern>
<!-- 控制保留的归档文件的最大数量,超出数量就删除旧文件,假设设置每个月滚动,
且<maxHistory> 是1,则只保存最近1个月的文件,删除之前的旧文件 -->
<MaxHistory>1</MaxHistory>
</rollingPolicy>
</appender>
<!--用于统计数据-->
<logger name="dataLogger">
<level value="INFO" />
<appender-ref ref="dataApp" />
</logger>
<root level="INFO">
<appender-ref ref="consoleApp"/>
<appender-ref ref="fileInfoApp"/>
<appender-ref ref="fileErrorApp"/>
</root>
</configuration>
Step1
需要记录日志的类添加
private Logger logger = LoggerFactory.getLogger(this.getClass());
private Logger dataLogger = LoggerFactory.getLogger("dataLogger");
Step2
日志打印
dataLogger.info("module=video_order`api=saveVideoOrder`user_id={}`video_id={}",videoOrderDto.getUserId(),videoOrderDto.getVideoId());
项目启动后会生成app_log目录