在 Web 应用程序中记录用户活动

发布于 2024-11-09 08:34:03 字数 655 浏览 0 评论 0原文

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

典型的 Servlet 可能如下所示:

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

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

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

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

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

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.

A typical servlet could look like:

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

愚人国度 2024-11-16 08:34:03

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

实现 MDC 过滤器

首先,实现一个 servlet 过滤器,将用户名添加到 MDC/NDC。 Logback提供了方便的MDCInsertingServletFilter,Spring框架还添加了<一href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/filter/Log4jNestedDiagnosticContextFilter.html" rel="noreferrer">Log4jNestedDiagnosticContextFilter 到店铺。查看它们,但您将需要一个像这样的自定义过滤器:

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 线程本地映射中保存的所有值添加到每个日志记录语句中。在您的情况下,只需添加以下内容:

%X{user}

到您的日志记录 pattern< /a>.

不显眼的日志记录方法参数/值

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

<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>

最终想法

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

Implementing MDC filter

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");
        }
    }

    //...
}

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}

to your logging pattern.

Unobtrusive logging method parameters/values

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>

Final thoughts

被你宠の有点坏 2024-11-16 08:34:03

我过去使用 log4j 的目的不仅仅是记录错误。我在整个代码中添加了 INFO 标签并更改了日志记录级别。这样,如果您决定不再需要记录这些活动,您只需更改日志记录级别即可完成。我希望这有帮助。

I have used log4j in the past in order to log more than just errors. I added INFO tags throughout my code and change the logging level. That way if you decide you no longer need to log those activities you can just change the logging level and you are done. I hope that helps.

凉宸 2024-11-16 08:34:03

如果您想登录服务器日志,请使用 ServletContext.log() 方法,该方法使用容器日志记录机制并登录容器日志。

If you want to log in sever logs, Use ServletContext.log() method which uses the container logging mechanism and logs into container logs..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文