1

I am working on a JAVA project where all the logging in the code is done by using slf4j. e.g.

package my.project.package;

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


    public class MyClass {

        private Logger logger = LoggerFactory.getLogger(MyClass.class);

        //some attributes, their getters and setters


        public void initialize() {
        //some code

        logger.info("Data received successfully!");

        //some code

    }
}

Now, we also have a log4j2.xml file. This file is loaded when the servlet context is initialized by

Configurator.initialize(null, FileFinderUtil.findFile("log4j2.xml", projectName, fallback).getAbsolutePath()); 

where configurator is a class from log4j2 library. We also deploy this log4j2.xml file on the server(tomcat)

1) I have read this SO link about slf4j and log4j2 working together. If slf4j2 is an abstraction (i understand this as abstract class), how is it possible to initialize an object of this class? In java, abstract classes can not have objects

2) For the two working together, is it so that the slf4j object is writing the logs but is actually behind the scene using log4j2 library for it? Can some body explain this process in simple terms?

overflow
  • 85
  • 1
  • 1
  • 8
  • slf4j comes as a bunch of different .jar files. Your application code just uses the API jar. To select the backend logging implementation you just provide at runtime the correct slf4j implementation jar that will delegate to the logging backend. – Henry Feb 14 '18 at 15:29
  • "To select the backend logging implementation you just provide at runtime the correct slf4j implementation jar" -- so log4j2 is the backend logging implementation in this case? – overflow Feb 15 '18 at 08:00
  • See here https://logging.apache.org/log4j/2.0/log4j-slf4j-impl/ You add log4j-slf4j-impl-2.0.jar – Henry Feb 15 '18 at 08:27
  • ok, so all that i wrote above about the abstraction means that it is just that idea wise and not really an abstract class and so on? – overflow Feb 15 '18 at 08:45
  • SLF4J is a facade, a small layer in front of the actual logger. The classes in log4j-slf4j-impl-2.0.jar translate the calls to the SLF4J API to corresponding calls to the log4j2 API. – Henry Feb 15 '18 at 08:52

1 Answers1

0

1) slf4j2 is not an abstract class it is just an abstraction for log4j2.

2) log4j2 is kind of a wrapper for slf4j. The java application uses slf4j for logging but tomcat uses log4j2 to do the logging at the server.

So the problem with log4j2 is that when one instance of tomcat has many applications deployed on it and they all have their own log4j2 instance, this results in collapse on tomcat. For this situation, we can use multiple versions of slf4j2 on the server and they all in turn use only one instance on tomcat.

overflow
  • 85
  • 1
  • 1
  • 8