如何在Logback中设置类似MDC的变量,但对于整个应用程序/JVM? [英] How to set a MDC-like variable in Logback, but for the entire app/JVM?

查看:403
本文介绍了如何在Logback中设置类似MDC的变量,但对于整个应用程序/JVM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的日志文件中有一个指示器,该应用程序针对该指示器进行记录.这意味着该变量对于整个应用程序都是相同的,但在应用程序实例之间是不同的.我尝试为此使用MDC,希望如果直接在main方法中进行设置,则该变量将由新产生的线程接管.过去,使用log4j或多或少都可以使用此功能,但使用logback则完全无效.我知道您可以在日志文件中显示系统变量,但是可能在同一台计算机上运行该应用程序的多个实例,因此无法正常工作.那么,如何将这个变量发送到我的日志文件中?

I'd like to have an indicator in my log file for which app logs something. This would mean a variable that's the same for the entire app, but different between instances of the app. I tried to use MDC for this, hoping that if I set it directly in the main method, the variable would be taken over by newly spawned threads. This used to work, more or less, using log4j, but it doesn't work at all with logback. I know you can show system variables in the log file, but there might be several instances of the app running on the same machine, so that won't work. So, how should I send this variable to my log file?

推荐答案

我将使用JVM系统属性.您可以在标志-Dthings.that.arent.bacon=turkey-bacon或以编程方式System.setProperty("no.matter.what.they.tell.you", "turkey bacon is not bacon");启动JVM时为每个进程设置它们.

I would use a JVM System Property. You can set them per process when the JVM is launched with a flag -Dthings.that.arent.bacon=turkey-bacon, or programmatically: System.setProperty("no.matter.what.they.tell.you", "turkey bacon is not bacon");.

如果您使用的是SLF4J/logback,则LogBack中似乎已经支持此功能: https ://logback.qos.ch/manual/layouts.html

It looks like this is already supportted in LogBack if you're using SLF4J/logback: https://logback.qos.ch/manual/layouts.html

这篇关于如何在Logback中设置类似MDC的变量,但对于整个应用程序/JVM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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