使用注释的 Java 代码检测
我有一个包含大量代码的巨大java项目。让我们假设它看起来像:
fn1(int arg1){...}
fn2(int arg1,int arg2){...}
fn23(){...}
...
fn134(){...}
我想使用注释记录每次函数调用:
@logme("arg1")
fn1(int arg1){...}
@logme("all args")
fn2(int arg1,int arg2){...}
fn23(){...}
...
fn134(){...}
并期望
fn1(arg1=223)
fn1(arg1=213,arg2=46)
在我的日志文件中
看到您能向我推荐一些工具吗?
史蒂夫
I've got a huge java project with tons of code. Let us assume it looks like:
fn1(int arg1){...}
fn2(int arg1,int arg2){...}
fn23(){...}
...
fn134(){...}
I want to log each invocation of functions using annotations:
@logme("arg1")
fn1(int arg1){...}
@logme("all args")
fn2(int arg1,int arg2){...}
fn23(){...}
...
fn134(){...}
and expect seeing
fn1(arg1=223)
fn1(arg1=213,arg2=46)
in my log files
Would you be so kind to propose me some tool?
Steve
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用 AspectJ 来实现此目的。在这里您可以找到一个简短的文档,了解如何定义适当的切入点
I would recommend to use AspectJ for this purpose. Here you can find a short documentation how to define the appropriate PointCuts
您可以使用 AspectJ &任何可以处理此要求的日志框架,
所以你需要执行以下操作:
1-创建你的注释,它可以根据你的意愿接受参数,甚至可以接受一串未定义数量的参数,并像
'arg1=q,arg2=w,arg3= 那样处理它们e'
2- 在新注释上创建一个带有切点的切面,如下所示,
注意这里使用 argNames 将注释本身发送到处理程序方法,因此您可以从中获取参数,如
'arg1=q ,arg2=w,arg3=e'
,并处理它们3-在继续方法调用之前,记录你想要的内容,你可以从参数中获取几乎所有需要的信息,
注释代码如下所示
:剪切代码如下所示:
然后在
doLoggingUserActivity
中,您可以使用类似的方法then 使用 logger 来记录它们
You may use AspectJ & any logging framework to handle this requirement,
so you need to do the following:
1- create your annotation which take arguments as you may wish, or even take a string of undefined number of arguments, and process them like
'arg1=q,arg2=w,arg3=e'
2- create an aspect with point cut on your new annotation like this
notice that argNames used here to send the annotation itself to the handler method, so you can get arguments from it like
'arg1=q,arg2=w,arg3=e'
, and process them3- before proceeding the method call, log what ever you want about it, you can get almost all needed info from your arguments,
Annotation code looks like:
point cut code looks like:
then inside
doLoggingUserActivity
you may use methods likethen use logger to log them