本文介绍了Log4j多个日志文件并以通用代码登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据所使用的服务登录到单独的日志文件.所以可以说我有service1& service2和日志将进入service1.log&分别是service2.log.

I have to log to separate log files depending on the service being used. So lets say I have service1 & service2 and the logs are going to service1.log & service2.log respectively.

问题在于两个服务都使用了一些通用代码.现在如何制作日志,以便任何服务调用通用代码,然后登录到该特定日志文件.

The issue is that there is some common code being used from both the services. Now how do I make the logs such that if the common code is called by any of the service then log into that specific log file.

我创建记录器的方式是

private static final Logger logger = Logger.getLogger(ClassName.class);

我想处理此问题的方法是将字符串(记录器名称)传递给通用代​​码,并在方法级别而不是类上创建记录器.

The way I am thinking to handles this is by passing a string (logger name) to the common code and creating the logger at the method level instead of class.

示例:

someMethodInCommonCode(String loggerName) {
  Logger logger = Logger.getLogger(loggerName);
}

我已经了解到log4j维护着记录器的缓存,因此在方法中创建记录器不会造成开销.

I have read that log4j maintains a cache of loggers so create a logger in method won't be a overhead I guess.

是的,我不喜欢传递记录器名称.因此,有没有一种方法或任何配置可以实现上述方案或任何其他想法.

And yes I don't like logger name being passed. So is there a way or any configuration by which I can achieve the above scenario or any other ideas.

推荐答案

您可以使用log4j的嵌套/映射诊断上下文(NDC或MDC)功能.本质上,这些是带外"信息,这些信息按线程存储,并在执行日志操作时自动附加到日志事件. NDC中的信息可以输出到日志文件,或用于在附加程序之间路由日志消息,而这正是您真正需要的.您可以在log4j的官方Wiki 上找到有关这些的更多信息.

You can use the Nested/Mapped Diagnostic Context (NDC or MDC) feature of log4j. Essentially, these are "out of band" information which are stored on a per-thread basis and automatically attached to logging events when a log operation is performed. The information in NDC can be output to the log file or used to route log messages between appenders, and that is what you exactly need. You can find more information on these on the official wiki of log4j.

您可以在调用通用代码之前将服务名称或其他标识符存储到服务中的NDC中.然后,您可以配置一个log4j过滤器,以根据NDC中找到的服务名称将公共日志消息路由到适当的输出文件.通用代码甚至不需要修改.

You can store the service name or some other identifier into the NDC in your services, before calling the common code. Then you can configure a log4j filter to route the common log messages to the appropriate output file according to the service name found in the NDC. The common code doesn't even need to be modified.

这篇关于Log4j多个日志文件并以通用代码登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!