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

标签 java multithreading logging slf4j logback

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

server类为每个请求创建一个单独的servcie线程:

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

2:对于到达服务器的每个传入请求,我们生成一个新线程(服务类的新实例),但问题是我们不希望每个服务实例都有一个记录器实例(我猜这是一个坏习惯)练习!)

这是服务类:

enter image description here

*:logger 被定义为静态,因此不会为每个服务类实例实例化:

最佳答案

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.

这就是我在我的应用程序中所做的。效果很好。

我的许多类(class)都将其作为第一行:

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。

关于java - 在客户端服务器程序中使用 logback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23606031/

相关文章:

java - .pkr 和 .key 文件对于 PGP 有什么区别?

Java组件不显示+布局问题

.net - Thread.SpinWait 在单核 CPU 上有何用处?

.net - Automapper 向 Map 方法添加日志记录

java - 基元的默认值

java - 需要写一定的方法

java - ThreadLocal变量没有改变

windows - Visual C++和并发线程..为什么会这样?

MySQL 命令历史

azure - Azure 订阅 ID、AAD 租户 ID 和 AAD 应用程序客户端 ID 是否被视为 secret /PII?