Slf4j⽇志框架的使⽤及Logback、Log4j2的整合和性能对⽐
⼀、Slf4j
slf4j(Simple Logging Facade for Java)是⽇志框架的⼀种抽象,那么也就是说 slf4j 是不能单独使⽤的必须要有其他实现⽇志框架来配合使⽤,并且如果要启⽤slf4j框架要导⼊slf4j-api-xxx.jar 这个包, 这个包是slf4j 实现各种⽀持的⽇志框架的包。如 log4j、log4j2、logback等。
编码模式
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
...
private static final Logger logger = Logger(T.class);
logger.debug();
logger.info();
logger.warn();
<();
注解模式
IDEA需要安装Lombok插件
pom⽂件引⼊lombok依赖
@slf4j
public class OauthApp {
...
...
logger.debug();
logger.info();
logger.warn();
<();
}
⼆、Logback
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/l"/>
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
<springProperty scope="context" name="ELK_FILEBEAT_PATH" source="elk.filebeat_path" defaultValue="/PATHTO/log"/>
<springProperty scope="context" name="ELK_URL" source="elk.url" defaultValue="127.0.0.1"/>
<springProperty scope="context" name="ELK_QUEUE_SIZE" source="elk.queue_size" defaultValue="8192"/>
<!-- Example for logging into the build folder of your project -->
<property name="LOG_FILE" value="${BUILD_FOLDER:-build}/${springAppName}"/>
<!-- You can override this to have a custom pattern -->
<property name="CONSOLE_LOG_PATTERN"
value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15 t]){faint} %clr(%-40.40logger{39}){cyan} %clr(%X{transNo}){faint} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- Appender to log to console -->
<appender name="console" class="ch.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>DEBUG</level>
<level>DEBUG</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<destination>${ELK_URL}</destination>
<queueSize>${ELK_QUEUE_SIZE}</queueSize>
<encoder class="net.der.LoggingEventCompositeJsonEncoder">
<providers>
<timestamp>
<timeZone>UTC</timeZone>
</timestamp>
<pattern>
<pattern>
{
"logdate":"%date{ISO8601}",
"severity":"%level",
"service":"${springAppName:-}",
"trace":"%X{X-B3-TraceId:-}",
"span":"%X{X-B3-SpanId:-}",
"parent":"%X{X-B3-ParentSpanId:-}",
"exportable":"%X{X-Span-Export:-}",
"pid":"${PID:-}",
"thread":"%thread",
"class":"%logger{40}",
"rest":"%message",
"transNo":"%X{transNo}"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>
<appender name="FILE_INFO" class="ch.olling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.olling.SizeAndTimeBasedRollingPolicy">
<!-- daily rollover -->
<!--<fileNamePattern>C:/aaa/log/uw.%d{yyyy-MM-dd}.log</fileNamePattern>-->
<fileNamePattern>${ELK_FILEBEAT_PATH}/fin-info.%d{yyyy-MM-dd}-%i.log</fileNamePattern> <maxFileSize>128MB</maxFileSize>
<!-- keep 30 days' worth of history capped at 3GB total size -->
<maxHistory>30</maxHistory>
<totalSizeCap>2GB</totalSizeCap>
</rollingPolicy>
<encoder class="net.der.LoggingEventCompositeJsonEncoder">
<providers>
<!--<timestamp>-->
<!--<timeZone>UTC</timeZone>-->
<!--</timestamp>-->
<pattern>
<pattern>
{
"logdate":"%date{ISO8601}",
"severity": "%level",
"service": "${springAppName:-}",
"trace": "%X{X-B3-TraceId:-}",
"span": "%X{X-B3-SpanId:-}",
"span": "%X{X-B3-SpanId:-}",
"parent": "%X{X-B3-ParentSpanId:-}",
"exportable": "%X{X-Span-Export:-}",
"pid": "${PID:-}",
"thread": "%thread",
"class": "%logger{40}",
"rest": "%message",
"transNo": "%X{transNo}"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>
<appender name="FILE_DEBUG" class="ch.olling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.olling.SizeAndTimeBasedRollingPolicy">
<!-- daily rollover -->
<!--<fileNamePattern>C:/aaa/log/uw.%d{yyyy-MM-dd}.log</fileNamePattern>-->
<fileNamePattern>${ELK_FILEBEAT_PATH}/fin-debug.%d{yyyy-MM-dd}-%i.log</fileNamePattern> <maxFileSize>128MB</maxFileSize>
<!-- keep 30 days' worth of history capped at 3GB total size -->
<maxHistory>30</maxHistory>
<totalSizeCap>2GB</totalSizeCap>
</rollingPolicy>
<encoder class="net.der.LoggingEventCompositeJsonEncoder">
<providers>
<!--<timestamp>-->
<!--<timeZone>UTC</timeZone>-->
<!--</timestamp>-->
<pattern>
<pattern>
{
"logdate":"%date{ISO8601}",
"severity":"%level",
"service":"${springAppName:-}",
"trace":"%X{X-B3-TraceId:-}",
"span":"%X{X-B3-SpanId:-}",
"parent":"%X{X-B3-ParentSpanId:-}",
"exportable":"%X{X-Span-Export:-}",
"pid":"${PID:-}",
"thread":"%thread",
"class":"%logger{40}",
"rest":"%message",
"transNo":"%X{transNo}"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>
<!--<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">-->
<!--<appender-ref ref="FILE" />-->
<!--</appender>-->
<root level="info">
<appender-ref ref="console"/>
<!-- uncomment this to have also JSON logs -->
<appender-ref ref="logstash"/>
<!-- <appender-ref ref="FILE" />-->
<!--<appender-ref ref="ASYNC"/>-->
</root>
<logger name="com.sinosoft" level="INFO" additivity="false">
<appender-ref ref="console"/>
<!-- uncomment this to have also JSON logs -->
<appender-ref ref="logstash"/>
<appender-ref ref="logstash"/>
<appender-ref ref="FILE_INFO" />
</logger>
<logger name="com.sinosoft" level="DEBUG" additivity="false">
<appender-ref ref="console"/>
<!-- uncomment this to have also JSON logs -->
log4j2不打印日志<appender-ref ref="logstash"/>
<appender-ref ref="FILE_DEBUG" />
</logger>
</configuration>
属性配置:
elk.filebeat_path
elk.url
elk.queue_size
三、Log4j2
<?xml version="1.0" encoding="UTF-8"?>
<!--⽇志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--status="WARN" :⽤于设置log4j2⾃⾝内部⽇志的信息输出级别,默认是OFF-->
<!--monitorInterval="30" :间隔秒数,⾃动检测配置⽂件的变更和重新配置本⾝-->
<configuration status="warn" monitorInterval="60" strict="true">
<properties>
<!--⾃定义⼀些常量,之后使⽤${变量名}引⽤-->
<property name="logpath">./logs</property>
<property name="charset">UTF-8</property>
<!--⾃定义的输出格式-->
<property name="pattern">%-d{yyyy-MM-dd HH:mm:ss.SSS}@@%p@@%X{ip}@@%t %C@@%X{requestId} %M %m %n </property>
</properties>
<!--appenders:定义输出内容,输出格式,输出⽅式,⽇志保存策略等,常⽤其下三种标签[console,File,RollingFile]-->
<!--Appender可以理解为⽇志的输出⽬的地-->
<appenders>
<!--console :控制台输出的配置-->
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="${pattern}" charset="${charset}"/>
</Console>
<!--RollingRandomAccessFile性能⽐RollingFile提升官⽹宣称是20-200%-->
<RollingRandomAccessFile name="YZY.TRACE" immediateFlush="true" bufferSize="1024"
fileName="${logpath}/trace.log"
filePattern="${logpath}/trace.log.%d{yyyy-MM-dd}.gz">
<PatternLayout pattern="${pattern}" charset="${charset}"/>
<TimeBasedTriggeringPolicy/>
<DefaultRolloverStrategy>
<Delete basePath="${logpath}" maxDepth="2" followLinks="true">
<IfFileName glob="trace.log.*.gz"/>
<IfLastModified age="3d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="YZY.SYSTEM" immediateFlush="true" bufferSize="4096"
fileName="${logpath}/system.log"
filePattern="${logpath}/system.log.%d{yyyy-MM-dd}.gz"
ignoreExceptions="false">
<!--引⽤上⾯⾃定义的输出格式-->
<PatternLayout pattern="${pattern}" charset="${charset}"/>
<Filters>
<!--ThresholdFilter :⽇志输出过滤-->
<!--level="info" :⽇志级别,onMatch="ACCEPT" :级别在info之上则接受,onMismatch="DENY" :级别在info之下则拒绝-->
<!--与logger、root中定义的⽇志级别相配合,相当于两个闸门,先判断logger、root的级别,符合了才会⽤到该filter中的level,此时再进⾏⼀次筛选--> <ThresholdFilter level="TRACE" onMatch="ACCEPT" onMismatch="DENY"/>
<!--<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>-->
<!--<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>-->
<!--<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>-->
</Filters>
<!-- Policies :⽇志滚动策略-->
<Policies>
<!--<TimeBasedTriggeringPolicy interval="1" modulate="true"/>-->
<CronTriggeringPolicy schedule="0 0 2 * * ?" evaluateOnStartup="true"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同⼀⽂件夹下7个⽂件-->
<DefaultRolloverStrategy>
<Delete basePath="${logpath}" maxDepth="2" followLinks="true">
<IfFileName glob="system.log.*.gz"/>
<!--只保留7天,超过则删除-->
<IfLastModified age="7d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="YZY.ERROR" immediateFlush="true" bufferSize="4096" fileName="${logpath}/error.log"
filePattern="${logpath}/error.log.%d{yyyy-MM-dd}.gz"
ignoreExceptions="false">
<PatternLayout pattern="${pattern}" charset="${charset}"/>
<Filters>
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<TimeBasedTriggeringPolicy/>
<DefaultRolloverStrategy>
<Delete basePath="${logpath}" maxDepth="2" followLinks="true">
<IfFileName glob="error.log.*.gz"/>
<IfLastModified age="7d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="YZY.AUDIT" immediateFlush="false" bufferSize="8192"
fileName="${logpath}/audit.log"
filePattern="${logpath}/audit.log.%d{yyyy-MM-dd}.gz"
ignoreExceptions="false">
<PatternLayout pattern="${pattern}" charset="${charset}"/>
<Filters>
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<TimeBasedTriggeringPolicy/>
<DefaultRolloverStrategy>
<Delete basePath="${logpath}" maxDepth="2" followLinks="true">
<IfFileName glob="audit.log.*.gz"/>
<IfLastModified age="7d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="YZY.POOL" immediateFlush="true" bufferSize="1024"
fileName="${logpath}/pool.log"
filePattern="${logpath}/pool.log.%d{yyyy-MM-dd}.gz"
ignoreExceptions="false">
<PatternLayout pattern="${pattern}" charset="${charset}"/>
<TimeBasedTriggeringPolicy/>
<DefaultRolloverStrategy>
<Delete basePath="${logpath}" maxDepth="2" followLinks="true">
<IfFileName glob="pool.log.*.gz"/>
<IfLastModified age="3d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="YZY.MONITOR" immediateFlush="true" bufferSize="1024" fileName="${logpath}/monitor.log"
filePattern="${logpath}/pool.log.%d{yyyy-MM-dd}.gz"
ignoreExceptions="false">
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论