@SLF4J : How to configure lombok supported slf4j

Viewed 8357

I have a maven project which logs using Lombok's inbuilt @Slf4j. Currently my logs are visible in console as below

    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

Pair of lines in the middle are the one logged by slf4j.

resources/log4j.properties looks like below

    # 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 looks like below:

<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 looks like this:

@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();
    }
}

I have few problems:

  • Statement formatting, it should contain time in square brackets[].
  • logs are not added to file given in configuration, infact I believe the configuration is not getting picked from the file.

No idea what exactly am I missing. Any help/hint is appreciated.

1 Answers

Figured it out myself after going through official apache manual page.

I will break whole answer into following two sections

1. Log4j2 setup for Jersey2 Maven Webapp

Add following dependencies into 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>

Add following filter into 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>

A configuration file log4j2.xml. It is required to follow the name log4j2.xml as scanning for configuration in classpath automatically picks it up or otherwise few more lines in web.xml will be needed to set the configuration file path. And not just the name, the configuration file must be put in WEB-INF directory where web.xml also resides.

    <?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>

The configuration given above contains two types of loggers, first for console and second for file. Also log levels can be specified for individual loggers. For more information like log pattern etc follow apache's manual page

And the last point is use of logger in java class. Logger can be injected into a java class as following:

@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();
    }
}

and the sweet result of doing so much looks like this logs


This works fine but it is annoying injecting Logger by initializing instance in every class, so to save a bit of work Slf4j can help. Slf4j is just a facade(abstract layer) behind which an actual logging framework(like Log4j, Java's inbuilt util.Logger and Logback etc) works. So in future if a better logging framework surfaces out then we won't have to touch java classes where logger have been instantiated, it is just the dependencies and config that will be taken care as per the new needs.

2. Slf4j and lombok in addition to log4j2

We need to add few more dependencies in addition to all the work we did in case 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>

It is very easy to inject logger using Lombok annotation @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 takes care of initialising and injecting the logger instance(log object) into class.

And that is it. Happy to help :)

Related