我如何使用log4j自动记录类中调用的每个方法 [英] How can i log every method called in a class automatically with log4j

查看:105
本文介绍了我如何使用log4j自动记录类中调用的每个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有数据库调用的类,并且我通常想用log4j记录该类中每个被调用的方法(带有参数):

I have a class with database calls, and I generally want to log every method called (with arguments) in this class with log4j:

logger.debug("foo(id="+id+") initiated");

是否可以自动执行此操作?也许通过在每种方法的开头使用某种注释,而不是编写每个logger.debug?

Is it possible to do this automatically? Maybe by using some sort of annotation in start of each method instead of writing every single logger.debug?

今天,每次更改参数或方法名称时,我都必须更新logging.debug.

Today I have to update my logging.debug every time I change arguments or method name.

推荐答案

尝试 @Loggable 注释和来自 jcabi-aspects (我是开发人员)的AspectJ方面:

Try @Loggable annotation and an AspectJ aspect from jcabi-aspects (I'm a developer):

@Loggable(Loggable.INFO)
public String load(URL url) {
  return url.openConnection().getContent();
}

所有方法调用都通过SLF4J记录.

All method calls are logged through SLF4J.

此博客文章逐步解释了该问题:

This blog post explains it step by step: Java Method Logging with AOP and Annotations

这篇关于我如何使用log4j自动记录类中调用的每个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆