本文介绍了在 Web 应用程序中记录用户活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在网络应用中记录用户活动.我目前正在使用 log4j,它可以很好地记录错误等,但我不确定最好的方法是记录用户、执行的 servlet 方法和方法参数.我正在使用 Spring Security 进行身份验证.

I'd like to be able to log user activities in a web app. I'm currently using log4j which works well for logging errors etc, but I'm unsure what the best approach is to log the user, executed servlet method, and method params. I'm using spring security for the authentication.

典型的 servlet 可能如下所示:

A typical servlet could look like:

public class BankAccountServlet {
    @RequestMapping("/deposit")
    public void deposit(double amount) {
        ...
    }

    @RequestMapping("/checkBalance")
    public double checkBalance() {
        ...
    }
}

如果有两个用户,foo 和 bar,其中 foo 检查他的余额,bar 存入两笔现金 10.00 和 5.00.我希望日志看起来像:

If there are two users, foo and bar, where foo checks his balance and bar deposits two sums of cash 10.00 and 5.00. I'd like the logs to look like:

01/01/1970 23:59:59 - foo - checkBalance
02/01/1970 23:59:59 - bar - deposit - 10.00
02/01/1970 23:59:59 - bar - deposit - 5.00

如果有人可以提供一些建议,我将非常感谢他们的帮助.

If anyone could offer some advice I'd really appreciate their help.

推荐答案

使用 Log4J 中内置的 MDC/NDC 功能来实现实际上非常简单(SLF4J 和 Logback 仅支持 MDC).

It's actually pretty simple to achieve using MDC/NDC functionality built into Log4J (SLF4J and Logback only support MDC).

首先,实现一个 servlet 过滤器,将用户名添加到 MDC/NDC.Logback 提供了方便的MDCInsertingServletFilter,Spring 框架还增加了Log4jNestedDiagnosticContextFilter到商店.看看它们,但你需要一个像这样的自定义:

First, implement a servlet filter that will add username to MDC/NDC. Logback provides convenient MDCInsertingServletFilter, Spring framework also adds Log4jNestedDiagnosticContextFilter to the store. Look at them but you will need a custom one like this:

public class UserToMdcFilter implements javax.servlet.Filter
{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        MDC.put("user", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove("user");
        }
    }

    //...
}

将 MDC 值添加到您的日志记录模式

确保在 Spring 安全过滤器之后的 web.xml 中应用此过滤器.MDC 功能非常灵活 - 如果需要,它会将保存在 MDC 线程本地映射中的所有值添加到每个日志记录语句中.在您的情况下,只需添加以下内容:

Adding MDC value to your logging pattern

Make sure this filter is applied in web.xml after Spring security filter. MDC feature is really slick - it will add all values saved in MDC thread-local map to each and every logging statement if requested. In your case, simply add this:

%X{user}

到您的日志记录模式.

记录方法名称、参数和返回值由您决定(用户名将自动添加),但有一些优雅的方法可以完全删除样板记录代码.试试这个 Spring 内置方面:

Logging method name, parameters and return values is up to you (username will be added automatically), but there are some elegant ways to remove boilerplate logging code completely. Try this Spring built-in aspect:

<bean id="customizableTraceInterceptor" class="org.springframework.aop.interceptor.CustomizableTraceInterceptor">
    <property name="enterMessage" value="Entering $[methodName]($[arguments])"/>
    <property name="exitMessage" value="Leaving $[methodName](): $[returnValue]"/>
</bean>
<aop:config>
    <aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * BankAccountServlet.*(..))"/>
</aop:config>

最后的想法

  • 看看这个线程:http://forum.springsource.org/showthread.php?88890-MDC-Log4j-Filter-with-Spring-Security-3.0.2
  • 考虑使用 Logback 作为日志库并坚持使用 SLF4J API.
  • Final thoughts

    • Look at this thread: http://forum.springsource.org/showthread.php?88890-MDC-Log4j-Filter-with-Spring-Security-3.0.2
    • Consider using Logback as a logging library and stick with SLF4J API.
    • 这篇关于在 Web 应用程序中记录用户活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 16:02