【发布时间】:2017-08-07 22:36:29
【问题描述】:
我有一个实例化多个线程的应用程序。每个服务都具有相同的 log4j2 配置,用于写入日志和套接字附加程序。 我需要在所有日志和套接字输出中获取主机信息,但使用
InetAddress addr = InetAddress.getLocalHost();
ThreadContext.put("Host", addr.getHostName());
我只在“主”线程中收到该信息。
在一些异步模型中,工作可能被委托给多个线程,而从概念上讲,这项工作共享相同的上下文。在此类模型中,将上下文数据存储在 ThreadLocal 变量中既不方便也不可取。用户可以配置 ContextDataInjectorFactory 以提供自定义的 ContextDataInjector 对象,以便使用来自任意上下文的上下文数据初始化日志事件。
我应该创建一个自定义的 ContextDataInjector,但我无法编写代码。 我编码了这个
List<Property> propertiesTest = new ArrayList<>();
propertiesTest.add(Property.createProperty("Host", "test"));
StringMap reusabletest = null;
ContextDataInjector prueba = ContextDataInjectorFactory.createInjector();
prueba.injectContextData(propertiesTest, reusabletest);
但它不起作用......
另一种方式是这样实现ContextDataInjector:
public class Log4j2Manager implements ContextDataInjector
{
private static Log4j2Configuration config;
private static final String PROPERTIES_PATH = "/etc//Log4j2Manager/Log4j2Manager.properties";
private final static Logger LOG = LogManager.getLogger(Log4j2Manager.class);
private static Log4j2slave[] workers = null;
public Log4j2Manager(String configPath) throws Exception
{
List<Property> propertiesTest = new ArrayList<>();
propertiesTest.add(Property.createProperty("Host", "test"));
StringMap reusableTest = null;
injectContextData(propertiesTest, reusableTest);
workers = new Log4j2slave[config.NumWorkers];
for (int i = 0; i < workers.length; i++)
{
workers[i] = new Log4j2slave(i);
Thread.sleep(1000);
}
....
}
....
@Override
public StringMap injectContextData(List<Property> properties, StringMap reusable)
{
if (properties == null || properties.isEmpty())
{
// assume context data is stored in a copy-on-write data structure
// that is safe to pass to another thread
return (StringMap) rawContextData();
}
// first copy configuration properties into the result
ThreadContextDataInjector.copyProperties(properties, reusable);
// then copy context data key-value pairs (may overwrite configuration
// properties)
reusable.putAll(rawContextData());
return reusable;
}
@Override
public ReadOnlyStringMap rawContextData() {
// TODO Auto-generated method stub
return null;
}
但它返回空点异常。 请问有什么建议吗?
最好的问候
【问题讨论】:
标签: java multithreading logging configuration log4j2