slf4j

title: slf4j使用说明

使用介绍

slf4j简介

SLF4J不是具体的日志解决方案,它只服务于各种各样的日志系统。按照官方的说法,SLF4J是一个用于日志系统的简单Facade,允许最终用户在部署其应用时使用其所希望的日志系统。

实际上,SLF4J所提供的核心API是一些接口以及一个LoggerFactory的工厂类。从某种程度上,SLF4J有点类似JDBC,不过比JDBC更简单,在JDBC中,你需要指定驱动程序,而在使用SLF4J的时候,不需要在代码中或配置文件中指定你打算使用那个具体的日志系统。如同使用JDBC基本不用考虑具体数据库一样,SLF4J提供了统一的记录日志的接口,只要按照其提供的方法记录即可,最终日志的格式、记录级别、输出方式等通过具体日志系统的配置来实现,因此可以在应用中灵活切换日志系统。

为什么要使用slf4j

  1. 使得你的程序独立于任意特定的日志类库,这意味着不需要管理多个日志配置或者多个日志类库。
  2. SLF4J提供了基于占位符的日志方法,这通过去除检查isDebugEnabled(), isInfoEnabled()等等,提高了代码可读性。
  3. 通过使用SLF4J的日志方法,你可以延迟构建日志信息(String)的开销,直到你真正需要,这对于内存和CPU都是高效的。
  4. 替代Commons Logging,解决其存在的ClassLoader问题。
  5. 这些好处只是冰山一角,你将在开始使用SL4J和阅读其中代码的时候知道更多的好处。任何一个新的Java程序员,都应该使用SLF4J做日志而不是使用包括Log4J在内的其他日志API。

配置

  1. 项目pom.xml中添加dependency

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

    之后会添加三个包:slf4j-api-1.7.6.jar, slf4j-log4j12-1.7.6.jar, log4j-1.2.17.jar

  2. 项目下添加 log4j.properties

    Example: log4j.properties

    #config root logger  
    log4j.rootLogger = INFO,system.out  
    log4j.appender.system.out=org.apache.log4j.ConsoleAppender  
    log4j.appender.system.out.layout=org.apache.log4j.PatternLayout  
    log4j.appender.system.out.layout.ConversionPattern=MINAServer Logger-->%5p{%F:%L}-%m%n  
    
    #config this Project.file logger  
    log4j.logger.thisProject.file=INFO,thisProject.file.out  
    log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppender  
    log4j.appender.thisProject.file.out.File=logContentFile.log  
    log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout 
    
  3. 在代码中添加

    private static final Logger logger = LoggerFactory.getLogger(MINAServer.class);
        .
        .
    logger.info("now {}" , "starting server");
    

代码中与log4j写法不一样的地方

这是你在Log4j(或者Commons Logging)中使用的方案,降低了代码可读性因为增加了不必要的繁琐代码。

    if (logger.isDebugEnabled()) {
        logger.debug("Processing trade with id: " + id + " symbol: " + symbol);
    }

如果你使用SLF4J的话,你可以得到在极简洁的格式的结果,就像以下展示的一样:

    logger.debug("Processing trade with id: {} and symbol : {} ", id, symbol);

在SLF4J,我们不需要字符串连接而且不会导致暂时不需要的字符串消耗。取而代之的,我们在一个以占位符和以参数传递实际值的模板格式下写日志信息。

在生产最终日志信息的字符串之前,这个方法会检查一个特定的日志级别是不是打开了,这不仅降低了内存消耗而且预先降低了CPU去处理字符串连接命令的时间。这里是使用SLF4J日志方法的代码,来自于slf4j-log4j12-1.7.6.jar中的Log4j的适配器类Log4jLoggerAdapter

    public void debug(String format, Object arg) {
        if (logger.isDebugEnabled()) {
            FormattingTuple ft = MessageFormatter.format(format, arg);
            logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
        }
    }

同时,我们需要知道记录日志是对应用程序的性能有着很大影响的,在生产环节上只进行必要的日志记录。

注意

  1. log4j.properties具体配置信息请自行搜索,也可使用log4j.xml。
  2. log4j.properties文件放在src目录下,默认加载。

参考资料

  1. 《slf4j-api、slf4j-log4j12以及log4j之间什么关系》 http://blog.youkuaiyun.com/tengdazhang770960436/article/details/18006127
  2. 《slf4j和log4j合用的(Maven)配置》 http://blog.youkuaiyun.com/anialy/article/details/8529188
  3. 《为什么要使用SLF4J而不是Log4J》 http://www.importnew.com/7450.html
06-18
### SLF4J Logging Framework Introduction and Usage SLF4J (Simple Logging Facade for Java) is a popular logging facade that provides a common interface to various logging frameworks, such as Log4J, Logback, and java.util.logging. It allows developers to use a single logging API across their applications while still being able to configure different underlying logging implementations[^1]. By using SLF4J, developers can easily switch between different logging frameworks without modifying the application code. To integrate SLF4J with Spring, it is necessary to replace the `commons-logging` dependency with the SLF4J-JCL bridge. This ensures that all logging calls made by Spring are translated into SLF4J API calls[^1]. If other libraries in the application also use the SLF4J API, then there will be a centralized location for configuring and managing logging. For Maven-based projects, integrating SLF4J involves adding four dependencies: excluding the existing `commons-logging`, including the SLF4J-JCL bridge, the SLF4J API, and the binding for Log4J or another logging framework[^2]. Below is an example of how this can be configured in a Maven `pom.xml` file: ```xml <dependencies> <!-- Exclude commons-logging --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.10</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- SLF4J JCL Bridge --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.32</version> </dependency> <!-- SLF4J API --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.32</version> </dependency> <!-- SLF4J Log4J Binding --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.32</version> </dependency> <!-- Log4J Implementation --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> ``` Alternatively, to disable `commons-logging`, one can either exclude the dependency from the `spring-core` module or depend on a special `commons-logging` dependency that replaces the library with an empty jar[^3]. This approach ensures that no conflicting logging frameworks interfere with SLF4J's operation. ### Example Usage of SLF4J in Code Below is an example of how SLF4J can be used in a Java application: ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExampleClass { private static final Logger logger = LoggerFactory.getLogger(ExampleClass.class); public void performTask() { logger.debug("This is a debug message."); logger.info("This is an info message."); logger.warn("This is a warning message."); logger.error("This is an error message."); } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值