@SLF4J : 如何配置 lombok 支持的 slf4j

@SLF4J : How to configure lombok supported slf4j

我有一个 Maven 项目,它使用 Lombok 的内置 @Slf4j 进行记录。目前我的日志在控制台中可见,如下所示

    06-Apr-2020 17:42:38.217 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    [2020-04-06 05:42:40,701] Artifact Tarkshala-Scholars-Engine:war exploded: Artifact is deployed successfully
    [2020-04-06 05:42:40,701] Artifact Tarkshala-Scholars-Engine:war exploded: Deploy took 4,521 milliseconds

    [http-nio-8080-exec-1] INFO com.tarkshala.scholars.engine.webservices.AuthenticationService - Welcome to Tarkshala Scholar APIs
    [http-nio-8080-exec-3] INFO com.tarkshala.scholars.engine.webservices.AuthenticationService - Welcome to Tarkshala Scholar APIs

    06-Apr-2020 17:42:45.808 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Users/kuldeep/Work/apps/apache-tomcat-9/webapps/manager]
    06-Apr-2020 17:42:45.843 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Users/kuldeep/Work/apps/apache-tomcat-9/webapps/manager] has finished in [35] ms

中间的一对线是slf4j记录的。

resources/log4j.properties 如下所示

    # Root logger option
    log4j.rootLogger=DEBUG, stdout, file

    # Redirect log messages to console
    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=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

    # Redirect log messages to a log file, support file rolling.
    log4j.appender.file=org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=/Users/kuldeep/Work/repos/Tarkshala-Scholars-APIs/logs/application.log
    log4j.appender.file.MaxFileSize=5MB
    log4j.appender.file.MaxBackupIndex=10
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

pom.xml 如下所示:

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

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>1.7.30</version>
</dependency>

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.10</version>
  <scope>provided</scope>
</dependency>

Java class 看起来像这样:

@Slf4j
@Path("/authentication")
@Authorization
public class AuthenticationService extends SpringApplication {

    @Path("/greet")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @PubliclyAllowed
    public Response greet(){
        log.info("Welcome to Tarkshala Scholar APIs");
        return getBean(AuthenticationServiceHandler.class).greet();
    }
}

我有几个问题:

不知道我到底错过了什么。任何 help/hint 表示赞赏。

经过官方了解后自己想通了apache manual page.

我会将整个答案分成以下两部分

1. Jersey2 Maven Webapp 的 Log4j2 设置

将以下依赖项添加到 pom.xml

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.13.1</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.13.1</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-web</artifactId>
  <version>2.13.1</version>
</dependency>

将以下过滤器添加到 web.xml

  <filter>
    <filter-name>log4jServletFilter</filter-name>
    <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>log4jServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

配置文件log4j2.xml。它需要遵循名称 log4j2.xml,因为扫描 class 路径中的配置会自动选择它,否则将需要 web.xml 中的几行来设置配置文件路径。不仅是名称,配置文件必须放在web.xml所在的WEB-INF目录下。

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Appenders>
        <Console name="LogToConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>

        <RollingRandomAccessFile name="LogToRollingRandomAccessFile" fileName="logs/TSE-app.log"
                                 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="1 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingRandomAccessFile>
    </Appenders>

    <Loggers>
        <!-- avoid duplicated logs with additivity=false -->
        <Logger name="com.tarkshala.scholars" level="debug" additivity="false">
            <AppenderRef ref="LogToConsole"/>
            <AppenderRef ref="LogToRollingRandomAccessFile"/>
        </Logger>
        <Root level="error">
            <AppenderRef ref="LogToRollingRandomAccessFile"/>
            <AppenderRef ref="LogToConsole"/>
        </Root>
    </Loggers>
</Configuration>

上面给出的配置包含两种类型的记录器,第一种用于控制台,第二种用于文件。还可以为各个记录器指定日志级别。有关日志模式等更多信息,请参阅 apache 手册 page

最后一点是 java class 中记录器的使用。 Logger 可以注入到 java class 中,如下所示:

@Path("/authentication")
public class AuthenticationService extends SpringApplication {

    private Logger logger = LogManager.getLogger(AuthenticationService.class);

    @Path("/greet")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response greet(){
        logger.info("Welcome to Tarkshala Scholar APIs");
        logger.error("THis is error log");
        logger.debug("THis is debug log");
        return getBean(AuthenticationServiceHandler.class).greet();
    }
}

做这么多的甜蜜结果看起来像这样


这工作正常,但通过在每个 class 中初始化实例来注入 Logger 很烦人,因此为了节省一些工作,Slf4j 可以提供帮助。 Slf4j 只是一个外观(抽象层),实际的日志框架(如 Log4j、Java 的内置 util.Logger 和 Logback 等)在其背后工作。因此,将来如果出现更好的日志记录框架,那么我们将不必触及已实例化记录器的 java classes,只需按照新需求。

2。 Slf4j和lombok除了log4j2

除了我们在案例 1 中所做的所有工作之外,我们还需要添加更多的依赖项。

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.13.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.13.1</version>
</dependency>

使用 Lombok 注解注入 logger 非常容易 @Slf4j

@Path("/authentication")
@Slf4j
public class AuthenticationService extends SpringApplication {

    private Logger logger = LogManager.getLogger(AuthenticationService.class);

    @Path("/greet")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response greet(){
        log.info("Welcome to Tarkshala Scholar APIs");
        log.error("THis is error log");
        log.debug("THis is debug log");
        return getBean(AuthenticationServiceHandler.class).greet();
    }
}

Lombok 负责初始化记录器实例(log 对象)并将其注入 class.

就是这样。乐于助人:)