Java:是否可以将日志语句自动添加到方法中? [英] Java: Is it possible to automatically add log statements to methods?

查看:67
本文介绍了Java:是否可以将日志语句自动添加到方法中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中的大多数方法都是这样写的:

Most of the methods in my application are written like this:

public void m() {
    long t1 = System.currentTimeMillis();
    log.info("begin - m()");

    /* method body */

    long t2 = System.currentTimeMillis();
    log.info("end - m(), took " + (t2 - t1) + "ms.");
}

我希望我可以简单地注释我的方法,并让日志语句自动生成:

I wish I could simply annotate my method and have the log statements be automagically generated instead:

@Log("executionTime")
public void m() {
    /* method body */
}

有关如何进行此方法的任何想法?有什么已知的解决方案吗?

Any ideas on how to proceed with this approach ? Is there any known solution ?

有人为此建议 AOP .问题在于,对于AspectJ或Spring AOP,我将不得不描述与方法本身中的日志调用一样多的代码.

Someone suggested AOP for this. The problem is that with AspectJ or Spring AOP I would have to describe all the methods which ammounts to as much code as the log calls in the method itself.

推荐答案

AspectJ Spring AOP 支持以下内容:

execution(* com.company.project..*.*(..))

将涵盖project的所有子包中的所有方法.因此,无需一一定义所有方法.

which will cover all methods in all sub-packages of project. So no need to define all methods one by one.

这篇关于Java:是否可以将日志语句自动添加到方法中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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