有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在客户机-服务器程序中使用logback

我需要在客户机-服务器程序中使用logback,对于到达服务器的每个请求,它将创建一个新的服务,该服务将在单独的线程中运行。我需要记录服务执行期间发生的操作。但我不想为每个服务线程生成单独的记录器对象。我知道一个解决方案是将logger对象设置为静态。所以它不会每次都被引用,但是对于这类问题有没有标准的解决方案。下面是我的源代码中的一些代码片段:

服务器类,它为每个请求创建一个单独的服务线程:

1:特定于服务器类的记录器

2:对于每个进入服务器的请求,我们都会生成一个新线程(服务类的新实例),但问题是我们不希望每个服务实例都有一个记录器实例(我想这是一个糟糕的做法!)

下面是服务类:

enter image description here

*:记录器是静态定义的,因此不会为每个服务类实例实例化:


共 (1) 个答案

  1. # 1 楼答案

    i know that one solution would be to set the logger object as static so it wont be instanciated every time but is there any standard solution for this kind of problem.

    这就是我在应用程序中所做的。它工作得很好

    我的许多课程都将此作为第一行:

    public class SomeClass {
        private static final Logger LOG = LoggerFactory.getLogger(SomeClass.class);
    
        // the rest of the class
    }
    

    Also, if you want the log messages to reflect which overall request is the one doing the logging, you should use MDC:

    One of the design goals of logback is to audit and debug complex distributed applications. Most real-world distributed systems need to deal with multiple clients simultaneously. In a typical multithreaded implementation of such a system, different threads will handle different clients. A possible but slightly discouraged approach to differentiate the logging output of one client from another consists of instantiating a new and separate logger for each client. This technique promotes the proliferation of loggers and may increase their management overhead.

    阅读整个链接,它在解释MDC方面比我以前做得更好