Log4j的NDC和MDC设施有什么区别? [英] What is the difference between Log4j's NDC and MDC facilities?

查看:114
本文介绍了Log4j的NDC和MDC设施有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Log4j中,NDC和MDC有什么区别?我可以举一个使用它们的简单示例吗?

In Log4j, what is the difference between NDC and MDC? Can I have a simple example where they are used?

推荐答案

要在链接西科斯基(Sikorski)的评论:

To expand on the link which Sikorski put in the comments:

在NDC中,N表示嵌套,这意味着您可以使用Stack控制单个值.您推送"一个字符串,然后在处理命令时可以推送"另一个字符串.处理完成后,您可以将其弹出以查看以前的值.这种上下文记录将在某些深度嵌套的处理中很有用.

In NDC, the N stands for nested, meaning you control a single value with a Stack. You "push" a string, then you can "push" another whenever processing dictates; and when processing is complete you can pop it off to see the former value. This sort of contextual logging would be useful in some deeply-nested processing.

NDC.push("processingLevel2"); 
log.info("success");

这将在具有%x(小写)模式的日志中获取输出:

This will get output in your log where you have the %x (lowercase) pattern:

log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %C %x = %m%n

MDC

M代表 mapped ,这为您提供了另一种控件类型.您可以使用名称/值对,而不是使用单个堆栈来控制单个上下文字符串.这对于跟踪多个上下文位很有用,例如将用户名和IP放入日志中.

MDC

The M stands for mapped, and this gives you a different type of control. Instead of using a single stack to control a single contextual string, you use name/value pairs. This is useful for tracking multiple contextual bits, such as putting username and IP into the log.

MDC.put("userIP", req.getRemoteAddr());
MDC.put("userName", foo.getName());
log.info("success");

示例MDC log4j模式

带有示例"userIP""userName"字符串的大写X.这些必须在您的代码和log4j配置中匹配:

Example MDC log4j pattern

Uppercase X with the example "userIP" and "userName" strings. These must match in your code and in the log4j config:

log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %X{userIP}  %C %X{userName} = %m%n

我会将它们组合成一个)上下文字符串*.

I would combine these into one )context string*.

在两种情况下,每当您执行log.info("success");时,输出都会具有您提供的其他上下文.这比每次登录时都将诸如log.info(req.getRemoteAddr()) + " success");之类的字符串串联起来要干净得多.

In both cases, whenever you do the log.info("success");, the output will have the additional context you have provided. This is much cleaner than concatenating strings like log.info(req.getRemoteAddr()) + " success"); every time you log.

请注意,两者在线程和资源方面存在严重差异.特别是,如果您不努力弹出和清除NDC堆栈,则NDC会保留线程的句柄,这可能会影响资源的释放.

Note that there are serious differences between the two with respect to threading and resources. In particular, NDC will keep handles to your threads which can affect the freeing of resources if you are not diligent about popping and clearing the NDC stack.

通过链接:如果不定期调用NDC.remove()方法,则使用NDC可能会导致内存泄漏.

From the link: NDC use can lead to memory leaks if you do not periodically call the NDC.remove() method.

这篇关于Log4j的NDC和MDC设施有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆