开发者

Can a log4j (or other Java logger) Appender accept or access request context objects?

开发者 https://www.devze.com 2023-01-22 12:35 出处:网络
I am currently writing a web service using Restlet, and logging with slf4j in front of log4j.Currently I have standard log4j Appenders in place for logging to files.What I was trying to do is also inc

I am currently writing a web service using Restlet, and logging with slf4j in front of log4j. Currently I have standard log4j Appenders in place for logging to files. What I was trying to do is also include log output in the HTTP Response, using a custom Appender.

The issue I am seeing is that Appenders by default have no ability to access the context of the request being made, which makes sense since theoretically the request could finish 开发者_高级运维before an asynchronous Appender gets around to executing. I am still curious as to whether this is possible, perhaps by making the Appender synchronous and passing a Response object with the log call. I can't find a way that log4j would support this, would another framework like logback? I wouldn't necessarily use this method in the end because of the performance implications, but still I am curious.

FYI my current workaround is a custom log method which adds the entry to the Response, then calls the slf4j method for standard logging. Downside to this is having to use a custom method, and I only get log entries for code I control (libraries I'm using that just use Appenders don't get logged to Response)


Most Appender operations don't happen asynchronously. I'm not sure how slf4j changes that equation, but you can certainly build an Appender that knows how to format any given object into a LogEvent. Asynchronicity shouldn't really matter, since the request context should be unchanging once it arrives in the Appender - holding a reference should be sufficient.

How do you access the Context of the request outside of the Log4J code?

I would probably just solve this using a custom appender that knew how to specially handle a Context for your logging purposes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号