初始Java中的日志记录工具slf4j

it2022-05-05  211

前言

至于slf4j和log4j还有其他日志工具的关系这里就不具体说明。 具体可参考如下: https://www.techug.com/post/how-log4j-designed.html

初识slf4j

创建Maven项目 这里使用IDEA工具: 其他参数默认即可。。。 添加依赖到pom.xml <dependencies> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> <!--<scope>test</scope>--> </dependency> </dependencies> 添加资源log4j.properties 在 src/main/resources/ 下创建 log4j.properties,内容如下: 注意修改输出的路径 ### 设置### log4j.rootLogger = debug,stdout,D,E,I ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n ### 输出DEBUG 级别以上的日志到=E://project//LoggerTest//target//log//debug.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = E://project//LoggerTest//target//log//debug.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 输出ERROR 级别以上的日志到=E://project//LoggerTest//target//log//error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File = E://project//LoggerTest//target//log//error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 输出INFO 级别以上的日志到=E://project//LoggerTest//target//log//info.log ### log4j.appender.I = org.apache.log4j.DailyRollingFileAppender log4j.appender.I.File = E://project//LoggerTest//target//log//info.log log4j.appender.I.Append = true log4j.appender.I.Threshold = INFO log4j.appender.I.layout = org.apache.log4j.PatternLayout log4j.appender.I.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 编写测试代码 package cn.com.gyt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggerTesting { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger("SimpleLogger"); logger.info("info messages!"); logger.debug("debug messages!"); logger.error("error messages!"); } }

项目结构:

运行: 参考:https://www.yiibai.com/slf4j/slf4j_firstapp.html#article-start

完!


最新回复(0)