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

查看:29
本文介绍了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?

推荐答案

扩展 link 西科尔斯基在评论中的评论:

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

在 NDC 中,N 代表 nested,这意味着您可以使用 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()) + " 这样的字符串要干净得多.成功"); 每次登录时.

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天全站免登陆