log4j(或其他 Java 记录器)Appender 可以接受或访问请求上下文对象吗?
我目前正在使用 Restlet 编写一个 Web 服务,并在 log4j 前面使用 slf4j 进行日志记录。目前我有标准的 log4j Appenders 用于记录到文件。我试图做的还包括使用自定义 Appender 将日志输出包含在 HTTP 响应中。
我看到的问题是,Appender 默认情况下无法访问所发出请求的上下文,这是有道理的,因为理论上请求可以在异步 Appender 开始执行之前完成。我仍然很好奇这是否可能,也许可以通过使 Appender 同步并通过日志调用传递 Response 对象来实现。我找不到 log4j 支持此功能的方法,是否有其他框架(例如 logback)?由于性能影响,我最终不一定会使用这种方法,但我仍然很好奇。
仅供参考,我当前的解决方法是自定义日志方法,它将条目添加到响应中,然后调用 slf4j 方法进行标准日志记录。这样做的缺点是必须使用自定义方法,并且我只能获取我控制的代码的日志条目(我正在使用的仅使用 Appender 的库不会记录到 Response)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大多数 Appender 操作不是异步发生的。我不确定 slf4j 如何改变这个等式,但是您当然可以构建一个知道如何将任何给定对象格式化为 LogEvent 的 Appender。异步性实际上并不重要,因为请求上下文一旦到达 Appender 就应该保持不变 - 持有引用就足够了。
如何在 Log4J 代码之外访问请求的上下文?
我可能会使用一个自定义附加程序来解决这个问题,该附加程序知道如何专门处理上下文以用于日志记录目的。
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.