[英]How to set log level per instance and per package hierarchy
My application manages devices in a network. 我的应用程序管理网络中的设备。 Those are represented in my application by objects and compositions of objects. 这些在我的应用程序中由对象和对象组成表示。 Each of these devices has an ID and each object related to a device knows about its ID. 这些设备中的每一个都有一个ID,并且与设备相关的每个对象都知道其ID。
When configuring logging, in addition to set the log level per the package hierarchy, I would like to be able to set it per device - that is, all instances related to one device should be eg. 配置日志记录时,除了按包层次结构设置日志级别外,我还希望能够按设备设置日志级别-也就是说,与一台设备相关的所有实例都应为例如。 put in DEBUG level. 置于DEBUG级别。
How can I set the log level by the package hierarchy and also by an instance ID? 如何通过程序包层次结构和实例ID设置日志级别?
My thoughts so far: 到目前为止,我的想法是:
Currently my loggers are created the "standard" way, by the class type 目前,我的记录器是通过类类型以“标准”方式创建的
public class Thermometer extends AnalogDevice {
private static final Logger logger = LoggerFactory.getLogger(Thermometer.class);
...
}
But I want to be able to choose the log level for specific devices. 但是我希望能够为特定设备选择日志级别。 My current idea would be to use the ID in the logger name, like this: 我当前的想法是在记录器名称中使用ID,如下所示:
public class Thermometer extends AnalogDevice {
private final Logger logger;
public Thermometer(String deviceId){
logger = LoggerFactory.getLogger(deviceId+"."+Thermometer.class);
...
}
...
}
(and the same for other classes in the hierarchy and other classes bound to this device) This would allow to configure log4j to have all messages for device "mydevice123" on DEBUG level. (以及层次结构中的其他类以及与此设备绑定的其他类的相同)这将允许将log4j配置为在调试级别具有设备“ mydevice123”的所有消息。
log4j.logger.mydevice123=DEBUG
But this will potentially create many loggers (per device / per class): 但这可能会创建许多记录器(每个设备/每个类):
mydevice123.com.example.dev.Thermometer.class
mydevice123.com.example.dev.AnalogDevice.class
mydevice123.com.example.dev.SomeOtherDeviceSpecific.class
Also I now lost the possibility to set the level on a package hierarchy. 现在,我也失去了在软件包层次结构上设置级别的可能性。 This won't work anymore. 这将不再起作用。
log4j.logger.com.example.dev=DEBUG
What's a better way? 有什么更好的方法?
Use logback as your logging implementation. 使用logback作为您的日志记录实现。
Set your device id in the MDC ( Mapped Diagnostic Context ) (*) 在MDC( 映射的诊断上下文 )(*)中设置设备ID
Set up a DynamicThresholdFilter 设置一个DynamicThresholdFilter
(*) IMHO a good approach to set the device id in the MDC is using an aspect applied on every business method which will get the device id from the targeted object ( exemple with spring aspects ), set the id in context before the method invocation and remove it after (*) 恕我直言,在MDC中设置设备ID的一种好方法是使用应用于每个业务方法的方面,该方面将从目标对象中获取设备ID( 例如spring方面 ),在方法调用之前在上下文中设置ID然后将其删除
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.