slf4j-log4j将对象转换为字符串,然后再传递给Asynchronus记录器 [英] slf4j-log4j converts objects to string before passing to Asynchronus logger

查看:322
本文介绍了slf4j-log4j将对象转换为字符串,然后再传递给Asynchronus记录器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找登录请求和响应于web服务.我正在将slf4j与底层log4j2实现一起使用.我的记录器语句如下所示.

I'm looking to log the request and response to a web service. I'm using slf4j with underlying log4j2 implementation. My logger statement looks like the below.

LOGGER.info("{}",新的CustomObject(request,response,param1,param2));

LOGGER.info("{}",new CustomObject(request,response,param1,param2));

我已经在所有必需的对象和CustomObject类中实现了toString方法,以记录该对象的所有属性.

I have implemented the toString methods in all the necessary objects and in the CustomObject class to log all attributes of that object.

我看到CustomObject的toString方法在将日志消息传递给Asynch记录器之前被调用.

I see that the toString method of the CustomObject is called before it passes the log message to the Asynch logger.

无论如何,在实际记录发生时,是否将自定义对象的序列化/toString方法调用推迟到?

Is there anyway that the serialization / toString method call of the custom object be deferred to when the actual logging takes place?

推荐答案

这是设计使然:如果记录了对象,则有可能在后台线程将其记录之前对其进行了更改,最终您将获得一个日志条目与您的预期不同.

This is by design: if an Object is logged it's possible that it is mutated before the background thread can log it, and you would end up with a log entry different from what you intended.

在您的示例中,您的应用程序未保存对CustomObject的引用,因此无法更改,但Log4j2无法知道,因此采用了保守的方法.

In your example your application doesn't hold a reference to the CustomObject, so it cannot change, but Log4j2 can't know that, so it takes the conservative approach.

有一个系统属性来关掉这个功能,但是使用它意味着全部登录对象必须是有效不可变的,否则你会发现你的日志骗你...(我还没有100%地肯定由于Log4j2在2.6版中变为无垃圾垃圾,因此系统属性仍然有效.)

There is a system property to switch this off, but using it means all objects logged must be effectively immutable or you will find your logs are lying to you... (I'm also not 100% sure that the system property still works since Log4j2 became garbage free in version 2.6.)

更新(2017-12-09):系统属性在2.6版之后的版本中仍然有效. (但我不建议您在后台线程中显示该消息,除非您非常确信该应用程序不会修改已记录的对象.)

Update (2017-12-09): the system property still works in post 2.6 versions. (But I would not recommend rendering the message in the background thread unless you are very confident that the application doesn’t modify the objects that were logged.)

这篇关于slf4j-log4j将对象转换为字符串,然后再传递给Asynchronus记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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