一文读懂LogBack配置文件

一、level的理解

级别从低到高:trace<debug<info<warn<error

当然也可以all或者off。

配置某个级别的时候,只会打印比配置的这个级别高的级别日志。

如配置为info,那么会打印info,warn和error的日志。日志的级别是在打印日志的那行代码里指定的。

二、Configuration配置文件

在这里插入图片描述

2.1 配置文件生效

scan:

当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。

scanPeriod:

设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。

debug:

当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。

<configuration scan="true" scanPeriod="60 seconds" debug="false">
      <!-- 其他配置省略-->
</configuration>

2.2 代码修改日志级别

private static Slf4JLoggingSystem slf4JLoggingSystem = new LogbackLoggingSystem(Application.class.getClassLoader());

slf4JLoggingSystem.setLogLevel("root", LogLevel.INFO);

2.3 Appender

定义日志的打印目的地,如控制台,文件等。

Layout:同时定义打印的格式,如需要打印时间,代码行数等,空几个格式等。

在这里插入图片描述

PatternLayout

Below is a list of conversion specifiers for PatternLayout in logback-access.

Conversion WordEffect
a / remoteIPRemote IP address.
A / localIPLocal IP address.
b / B / bytesSentResponse’s content length.
h / clientHostRemote host.
H / protocolRequest protocol.
lRemote log name. In logback-access, this converter always returns the value “-”.
reqParameter{paramName}Parameter of the response.This conversion word takes the first option in braces and looks for the corresponding parameter in the request.%reqParameter{input_data} displays the corresponding parameter.
i{header} / header{header}Request header.This conversion word takes the first option in braces and looks for the corresponding header in the request.%header{Referer} displays the referer of the request.If no option is specified, it displays every available header.
m / requestMethodRequest method.
r / requestURLURL requested.
s / statusCodeStatus code of the request.
D / elapsedTimeThe time taken to serve the request, in milliseconds.
T / elapsedSecondsThe time taken to serve the request, in seconds.
t / dateOutputs the date of the logging event. The date conversion specifier may be followed by a set of braces containing a date and time pattern strings used by java.text.SimpleDateFormat. ISO8601 is also a valid value.For example, %t{HH:mm:ss,SSS} or %t{dd MMM yyyy ;HH:mm:ss,SSS}. If no date format specifier is given then the Common Log Format date format is assumed, that is: %t{dd/MMM/yyyy:HH:mm:ss Z}
u / userRemote user.
q / queryStringRequest query string, prepended with a ‘?’.
U / requestURIRequested URI.
S / sessionIDSession ID.
v / serverServer name.
I / threadNameName of the thread which processed the request.
localPortLocal port.
reqAttribute{attributeName}Attribute of the request.This conversion word takes the first option in braces and looks for the corresponding attribute in the request.%reqAttribute{SOME_ATTRIBUTE} displays the corresponding attribute.
reqCookie{cookie}Request cookie.This conversion word takes the first option in braces and looks for the corresponding cookie in the request.%cookie{COOKIE_NAME} displays corresponding cookie.
responseHeader{header}Header of the response.This conversion word takes the first option in braces and looks for the corresponding header in the response.%header{Referer} displays the referer of the response.
requestContentThis conversion word displays the content of the request, that is the request’s InputStream. It is used in conjunction with a TeeFilter, a javax.servlet.Filter that replaces the original HttpServletRequest by a TeeHttpServletRequest. The latter object allows access to the request’s InputStream multiple times without any loss of data.
fullRequestThis converter outputs the data associated with the request, including all headers and request contents.
responseContentThis conversion word displays the content of the response, that is the response’s InputStream. It is used in conjunction with a TeeFilter, a javax.servlet.Filter that replaces the original HttpServletResponse by a TeeHttpServletResponse. The latter object allows access to the request’s InputStream multiple times without any loss of data.
fullResponseThis conversion word takes all the available data associated with the response, including all headers of the response and response contents.

Logback access’ PatternLayout also recognizes three keywords, which act like shortcuts.

异步写入

<!-- 异步输出 -->
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
    <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
    <discardingThreshold>0</discardingThreshold>
    <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
    <queueSize>256</queueSize>
    <!-- 添加附加的appender,最多只能添加一个 -->
    <appender-ref ref="FILE_ERROR"/>
</appender>

异步的Appender引入(ref)其他的Appender,来达到异步的目的。

日志保留

在Appender下面有rollingPolicy节点里面可以设置,最大保留多少天的日志(maxHistory),文件最大可以的大小(maxFileSize)。

<appender name="rollingAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"> 
		<file>/tmp/logs/hyInfo.log</file> 
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 
        <fileNamePattern>/tmp/logs/hyInfo-%d{yyyy-MM-dd}.log</fileNamePattern> 
        <maxHistory>180</maxHistory> 
        <timeBasedFileNamingAndTriggeringPolicy  
        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
          <!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
          <maxFileSize>2MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy> 
    <encoder> 
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern> 
    </encoder> 
</appender>

2.4 Logger

定义某类目录(name属性),打印的级别(level属性),logger元素具有继承性**(当前有明确日志级别指定,则使用明确级别,否则使用父的级别指定,root为他们的最顶层)**。

其中可以指定使用哪些Appender。

<logger name="com.example.guava.controller" level="error" additivity="false">
    <appender-ref ref="STDOUT"/>
</logger>

additivity

additivity:这个属性属于logger,标志着这个logger的目录日志打印是否传递到root。

  • true:默认值,传递到root,同样的日志会打印两遍。
  • false:只会在logger定义范围内打印一次,root不会再打印了。

2.5 Root

默认打印级别为debug。

指定使用哪些Appender。

三、配置文件例子

logback-spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>INFO</level>
		</filter>
		<encoder>
			<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
	</appender>

	<appender name="FILE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<!--如果只是想要 Info 级别的日志,只是过滤 info 还是会输出 Error 日志,因为 Error 的级别高, 所以我们使用下面的策略,可以避免输出 Error 的日志-->
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<!--过滤 Error-->
			<level>ERROR</level>
			<!--匹配到就禁止-->
			<onMatch>DENY</onMatch>
			<!--没有匹配到就允许-->
			<onMismatch>ACCEPT</onMismatch>
		</filter>
		<!--日志名称,如果没有File 属性,那么只会使用FileNamePattern的文件路径规则如果同时有<File>和<FileNamePattern>,那么当天日志是<File>,明天会自动把今天的日志改名为今天的日期。即,<File> 的日志都是当天的。-->
		<!--<File>logs/info.spring-boot-demo-logback.log</File>-->
		<!--滚动策略,按照时间滚动 TimeBasedRollingPolicy-->
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--文件路径,定义了日志的切分方式——把每一天的日志归档到一个文件中,以防止日志填满整个磁盘空间-->
			<FileNamePattern>logs/spring-boot-demo-logback/info.created_on_%d{yyyy-MM-dd}.part_%i.log</FileNamePattern>
			<!--只保留最近90天的日志-->
			<maxHistory>90</maxHistory>
			<!--用来指定日志文件的上限大小,那么到了这个值,就会删除旧的日志-->
			<!--<totalSizeCap>1GB</totalSizeCap>-->
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
				<maxFileSize>2MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
		<!--<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
		<!--<maxFileSize>1KB</maxFileSize>-->
		<!--</triggeringPolicy>-->
		<encoder>
			<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
			<charset>UTF-8</charset> <!-- 此处设置字符集 -->
		</encoder>
	</appender>

	<appender name="FILE_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<!--如果只是想要 Error 级别的日志,那么需要过滤一下,默认是 info 级别的,ThresholdFilter-->
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>Error</level>
		</filter>
		<!--日志名称,如果没有File 属性,那么只会使用FileNamePattern的文件路径规则如果同时有<File>和<FileNamePattern>,那么当天日志是<File>,明天会自动把今天的日志改名为今天的日期。即,<File> 的日志都是当天的。-->
		<!--<File>logs/error.spring-boot-demo-logback.log</File>-->
		<!--滚动策略,按照时间滚动 TimeBasedRollingPolicy-->
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--文件路径,定义了日志的切分方式——把每一天的日志归档到一个文件中,以防止日志填满整个磁盘空间-->
			<FileNamePattern>logs/spring-boot-demo-logback/error.created_on_%d{yyyy-MM-dd}.part_%i.log</FileNamePattern>
			<!--只保留最近90天的日志-->
			<maxHistory>90</maxHistory>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
				<maxFileSize>2MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
		<encoder>
			<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
			<charset>UTF-8</charset> <!-- 此处设置字符集 -->
		</encoder>
	</appender>

	<root level="info">
		<appender-ref ref="CONSOLE"/>
		<appender-ref ref="FILE_INFO"/>
		<appender-ref ref="FILE_ERROR"/>
	</root>
</configuration>

四、Logback-access

Logback分为logback-core,logback-classic,logback-access。

  • core是基础模块。
  • classic实现了slf4j。
  • access是与容器相关的日志。与logback-spring.xml是两个配置文件,两个配置文件之间没有什么关系。对应的配置文件为log-access.xml。

Spring-boot2.0引入Logback-access

1、引入jar包:

<dependency>
    <groupId>net.rakugakibox.spring.boot</groupId>
    <artifactId>logback-access-spring-boot-starter</artifactId>
    <version>2.7.1</version>
</dependency>

2、加入配置文件,默认名字为Logback-access.xml

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator> <!-- 默认为 ch.qos.logback.classic.boolex.JaninoEventEvaluator -->
                <expression>(event.getRequestURI().contains("fileUpload"))</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>ACCEPT</OnMismatch>
        </filter>
        <encoder>
            <pattern>[请求]%n%fullRequest%n[请求时间]%date%n%n[响应]%n%fullResponse</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>/opt/logs/yinni-mobile-client/yinni-mobile-client-access.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>/opt/logs/yinni/yinni.%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>[请求]%n%fullRequest%n[请求时间]%date%n%n[响应]%n%fullResponse</pattern>
        </encoder>
    </appender>

    <appender-ref ref="STDOUT"/>
</configuration>

3、application中添加如下配置:

server:
  tomcat:
    accesslog:
      enabled: true
    basedir: /opt

4、在log-access.xml的Appender中添加如下的过滤器,既可以根据路径来过滤是否打印。

<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
    <evaluator> <!-- 默认为 ch.qos.logback.classic.boolex.JaninoEventEvaluator -->
        <expression>(event.getRequestURI().contains("fileUpload"))</expression>
    </evaluator>
    <OnMatch>DENY</OnMatch>
    <OnMismatch>ACCEPT</OnMismatch>
</filter>

5、注意以上的过滤器需要在pom文件中,添加如下依赖:

<!-- https://mvnrepository.com/artifact/org.codehaus.janino/janino -->
<dependency>
    <groupId>org.codehaus.janino</groupId>
    <artifactId>janino</artifactId>
    <version>3.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.janino/commons-compiler -->
<dependency>
    <groupId>org.codehaus.janino</groupId>
    <artifactId>commons-compiler</artifactId>
    <version>3.0.12</version>
</dependency>

五、参考文章

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值