如何将整个 Web 请求的用户名插入到 MDC 中
我正在尝试使用映射诊断上下文将发出页面请求的用户的用户名添加到所有相关的日志记录语句。然而,我尝试了三种不同的方法来使其工作但没有成功:
- 登录后将用户名推送到 MDC 并在注销后删除。此方法最终会混淆来自哪个用户的日志记录语句。
- 使用 ServletFilter 在每个页面加载时将用户名推送到 MDC 中,并在请求结束时将其弹出。这仅捕获部分数据并且仅在 Spring 安全层中。
- 在所有控制器方法前面使用 AOP @Around 拦截器是行不通的。
有人对如何实现这一目标有任何建议吗?
I am trying to use a Mapped Diagnostic Context to add the username of the user making a page request to all relevant logging statements. However I have tried three different ways to make it work without success:
- Pushing the username into the MDC after login and removing after logout. This method ends up mixing up which logging statement came from which user.
- Using a ServletFilter to push the username into the MDC on each page load and pop it back off as the request ends. This only catches some of the data and only in Spring security layer.
- Using a AOP @Around interceptor in front of all the Controller methods flat out didn't work.
Does anyone have any suggestions on how to make this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MDC 存在哪些问题? Spring 安全层是什么意思?我在一个 Web 应用程序中使用了这种方法,效果很好。因为 MDC 绑定到线程,所以来自该线程的所有日志语句都将设置用户名,即服务和存储库层。
当然,如果某些用户使用线程(例如 servlet 3.0 异步处理、JMS 侦听器、执行器)提供服务,则您将需要在池线程中将用户名注入到 MDC 的其他方法。
另请参阅我的回答此处。
What were the problems with MDC? What do you mean by Spring security layer? I used this approach in one web application and it worked well. Because MDC is bound to thread, all logging statements coming from this thread will have username set, i.e. service and repository layer as well.
Of course if some users are served from using threads (e.g. servlet 3.0 asynchronous processing, JMS listeners, executors), you will need the other way of injecting username to MDC in pooled threads.
Also see my answer here.