How to get other than root logger from SLF4J using Log4J

I have seen that this is getting root logger by default

No it is not.

Assume FQN of Name is foo.bar.Name), when you call private final Logger logger = LoggerFactory.getLogger(Name.class); , you are getting a logger with name foo.bar.Name, for which inherits from foo.bar, for which inherits from foo, for which inherits from root.

You can get the root logger in SLF4J by LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)

Loggers are hierarchical. Child level logger inherits configurations from its parent (including appenders, level etc). I believe you were confused about "getting a child logger which inherited config from ROOT logger" and "getting the ROOT logger"

2.How can i get other loggers which are defined in log4j.xml file?

For example, if you want to get logger com.example.foo, it is simply by private final Logger logger = LoggerFactory.getLogger("com.example.foo");

As mentioned above, loggers are hierarchical. If you get the logger "com.example.foo.Bar", given there are no specific setting for "com.example.foo.Bar", its behaviour should be the same as using "com.example.foo" (except the logger name being show in log of course).

As it is a common practice to use the class name itself as the logger name, SLF4J also provide a method to get logger by providing a class (as what you do in your question), by Logger logger = LoggerFactory.getLogger(Bar.class);. This make it more refactoring-friendly. In this case, the logger name got will be the same as the FQN of the class provided ("com.example.foo.Bar")

Tags:

Java

Log4J

Slf4J