简体   繁体   English

使用slf4j作为log4j2的抽象

[英]Using slf4j as an abstraction for log4j2

I am working on a JAVA project where all the logging in the code is done by using slf4j. 我正在一个JAVA项目中,其中所有的代码记录都通过使用slf4j完成。 eg 例如

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. 现在,我们还有一个log4j2.xml文件。 This file is loaded when the servlet context is initialized by 当servlet上下文初始化时,将加载此文件。

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

where configurator is a class from log4j2 library. 其中configurator是log4j2库中的类。 We also deploy this log4j2.xml file on the server(tomcat) 我们还将这个log4j2.xml文件部署在服务器上(tomcat)

1) I have read this SO link about slf4j and log4j2 working together. 1)我看过这个关于SLF4J和log4j2工作在一起,使链路。 If slf4j2 is an abstraction (i understand this as abstract class), how is it possible to initialize an object of this class? 如果slf4j2是一个抽象(我将其理解为抽象类),那么如何初始化该类的对象呢? In java, abstract classes can not have objects 在Java中,抽象类不能具有对象

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? 2)对于两者一起工作,是slf4j对象正在编写日志,但实际上是使用log4j2库在后台吗? Can some body explain this process in simple terms? 有人可以用简单的方式解释这个过程吗?

1) slf4j2 is not an abstract class it is just an abstraction for log4j2. 1)slf4j2不是抽象类,它只是log4j2的抽象。

2) log4j2 is kind of a wrapper for slf4j. 2)log4j2是slf4j的包装器。 The java application uses slf4j for logging but tomcat uses log4j2 to do the logging at the server. Java应用程序使用slf4j进行日志记录,但是tomcat使用log4j2在服务器上进行日志记录。

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. 因此,log4j2的问题在于,当tomcat的一个实例上部署了许多应用程序并且它们都拥有自己的log4j2实例时,这会导致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. 对于这种情况,我们可以在服务器上使用slf4j2的多个版本,而它们在Tomcat上依次仅使用一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM