文章参考:
- https://www.cnblogs.com/caoleiCoding/p/9416473.html
- https://blog.csdn.net/alice_qixin/article/details/81483984
- https://blog.csdn.net/x631617479/article/details/82184303
一.默认实现的日志配置
1.1Spring boot
默认已经集成了logging
,同时也是默认开启的,如果想根据自己的需求对日志进行配置,方法很简单——只需要在配置文件中进行相应设置,这里提供我自己的配置如下(配置文件采用了application-dev.yml
):
server:
port: 8080
logging:
config: classpath:logback.xml
1.2 配置logback.xml
文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="false" scanPeriod="10 seconds">
<logger name="org.springframework" level="INFO" />
<logger name="com.data.spider.dao" level="INFO" />
<!--<logger name="com.autohome.datacenter.spider.web.dao" level="DEBUG" />-->
<!--文件输出的格式设置 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 文件输出的日志 的格式 -->
<encoder>
<pattern>
%5p [%t] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集,防止中文乱码 -->
</encoder>
<!-- 配置日志所生成的目录以及生成文件名的规则 在logs/mylog-2016-10-31.0.log -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--<fileNamePattern>${user.dir}/logs/log-%d{yyyy-MM-dd}.%i.log</fileNamePattern>-->
<fileNamePattern>${spider_web_log_path}/log-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- 最大64MB 超过最大值,会重新建一个文件-->
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>7</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<!-- Safely log to the same file from multiple JVMs. Degrades performance! -->
<prudent>true</prudent>
</appender>
<!--控制台输出的格式设置 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- 控制台输出的日志 的格式 -->
<encoder>
<pattern>
%5p [%t] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n </pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 只是DEBUG级别以上的日志才显示 -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
</appender>
<!-- Enable FILE and STDOUT appenders for all log messages. By default,
only log at level INFO and above. -->
<root level="INFO">
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
1.3 调用测试
package com.data.spider.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Test {
private static final Logger LOGGER = LoggerFactory.getLogger( Test.class );
public static void main(String[] args) {
LOGGER.info("==========print log==========");
LOGGER.error("==========error log==========");
LOGGER.warn("==========warn log==========");
LOGGER.debug("==========warn log==========");
}
}
二、自定义日志配置
使用默认的日志在实际开发中会存在很多问题,比如备份文件名称无法自动重命名、各个等级的日志被放在一个文件中等,所以实际开发中为了更好满足我们的需求,我们一般都会自定义采用配置的方式,日志自定配置步骤如下
2.1剔除springboot自带logging包并添加log4j2
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
----------
<!--log4j2 日志框架-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.2 自定义配置文件log4j2.xml
Spring boot对自定义配置文件的名称是有要求的,对Login4j2而言必须为log4j2-spring.xml or log4j2.xml
关于配置文件中的参数,详细参考官方文档
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<Configuration status="WARN" monitorInterval="30">
<!--全局属性-->
<Properties>
<Property name="APP_NAME">oss-log4j2</Property>
<Property name="LOG_FILE_PATH">f:/logs/${APP_NAME}</Property>
<Property name="PATTERN_FORMAT">%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%t] %class{36} (%L) %M - %msg%xEx%n</Property>
</Properties>
<Appenders>
<!--输出到控制台-->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${PATTERN_FORMAT}"/>
</Console>
<!--输出到文件 用来定义超过指定大小自动删除旧的创建新的的Appender.-->
<RollingFile name="RollingInfoFile" fileName="${LOG_FILE_PATH}/info.log"
filePattern="${LOG_FILE_PATH}/$${date:yyyyMM}/info-%d{yyyyMMdd}-%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<Filters>
<ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/>
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<PatternLayout>
<pattern>${PATTERN_FORMAT}</pattern>
</PatternLayout>
<Policies>
<!-- rollover on startup, daily and when the file reaches 10 MegaBytes -->
<OnStartupTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
<!--输出警告日志到文件-->
<RollingFile name="RollingWarnFile" fileName="${LOG_FILE_PATH}/warn.log"
filePattern="${LOG_FILE_PATH}/$${date:yyyyMM}/warn-%d{yyyyMMdd}-%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<Filters>
<ThresholdFilter level="error" onMatch="DENY" onMismatch="NEUTRAL"/>
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<PatternLayout>
<pattern>${PATTERN_FORMAT}</pattern>
</PatternLayout>
<Policies>
<!-- rollover on startup, daily and when the file reaches 10 MegaBytes -->
<OnStartupTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
<!--输出错误日志到文件-->
<RollingFile name="RollingErrorFile" fileName="${LOG_FILE_PATH}/error.log"
filePattern="${LOG_FILE_PATH}/$${date:yyyyMM}/error-%d{yyyyMMdd}-%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout>
<pattern>${PATTERN_FORMAT}</pattern>
</PatternLayout>
<Policies>
<!-- rollover on startup, daily and when the file reaches 10 MegaBytes -->
<OnStartupTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
<Logger name="org.springframework" level="INFO"/>
<Logger name="org.mybatis" level="INFO"/>
<!-- LOG "com.luis*" at TRACE level -->
<Logger name="com.luis" level="INFO"/>
<!-- LOG everything at INFO level -->
<Root level="ALL">
<AppenderRef ref="Console"/>
<AppenderRef ref="RollingInfoFile"/>
<AppenderRef ref="RollingWarnFile"/>
<AppenderRef ref="RollingErrorFile"/>
</Root>
</Loggers>
</Configuration>
2.3 使用Demo
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
获取日志对象
private static final Logger log = LogManager.getLogger(thisClass.class);
log.info("我是日志info");