slf4j+log4j 使用

上接:slf4j介绍

说明

slf4j不能单独使用,需要搭配日志框架,这里介绍 log4j

依赖方式

jar包依赖

  • slf4j-api-xxx.jar
  • slf4j-log4j12-xxx.jar
  • log4j-1.2.17.jar

maven依赖

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.22</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.22</version>
</dependency>

log4j.properties

log4j.rootLogger=DEBUG, stdout ,file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.file = org.apache.log4j.FileAppender
log4j.appender.file.File = 1.log
log4j.appender.file.Encoding=UTF-8
#只将ERROR输出到文件中
#log4j.appender.file.Threshold=ERROR
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}[ %p ]%m%n
log4j.appender.file.append = true

java代码

引包

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

创建log对象

Logger log= LoggerFactory.getLogger(当前类.class);

log对象打印日志

log.trace("trace级别:: {}",content);
log.debug("debug级别:: {}",content);
log.info("info级别:: {}",content);
log.warn("warn级别:: {}",content);
log.error("error级别:: {}",content);

原文出处:https://malaoshi.top/show_1IX3WLQaSBVR.html