我开始使用logback,我想知道是否有更好的方法可以做某事。 我有这段代码:
public class ClassA {
private List<String> l;
private Logger logger;
public ClassA(){
this.logger = LoggerFactory.getLogger(this.getClass().getName());
}
....
public List<String> method() {
this.logger.debug("method()");
List<String> names;
try {
names = otherClass.getNames();
} catch (Exception e) {
String msg = "Error getting names";
this.logger.error(msg);
throw new ClassAexception(msg, e);
}
this.logger.debug("names: {}", xxxxx);
return names;
}
到目前为止我有些疑惑:
this.logger = LoggerFactory.getLogger(this.getClass().getName());
来创建记录器。this.logger.debug("method()");
来知道何时调用方法。看起来不太好看。有办法解决吗?
此外,我想在此行的.log中打印一个列表:this.logger.debug("names: {}", xxxxx);
xxxxx应替换为打印列表的东西。一个匿名的课程?
感谢阅读!
答案 0 :(得分:7)
使用AspectJ和log4j即可使用此功能。使用ajc编译器而不是javac编译代码,然后使用java可执行文件正常运行。
您需要在类路径上包含aspectjrt.jar和log4j.jar。
import org.aspectj.lang.*;
import org.apache.log4j.*;
public aspect TraceMethodCalls {
Logger logger = Logger.getLogger("trace");
TraceMethodCalls() {
logger.setLevel(Level.ALL);
}
pointcut traceMethods()
//give me all method calls of every class with every visibility
: (execution(* *.*(..))
//give me also constructor calls
|| execution(*.new(..)))
//stop recursion don't get method calls in this aspect class itself
&& !within(TraceMethodCalls);
//advice before: do something before method is really executed
before() : traceMethods() {
if (logger.isEnabledFor(Level.INFO)) {
//get info about captured method and log it
Signature sig = thisJoinPointStaticPart.getSignature();
logger.log(Level.INFO,
"Entering ["
+ sig.getDeclaringType().getName() + "."
+ sig.getName() + "]");
}
}
}
查看AspectJ文档,了解如何更改TraceMethodCalls调用。
// e.g. just caputre public method calls
// change this
: (execution(* *.*(..))
// to this
: (execution(public * *.*(..))
关于
另外我想打印一个列表 .log在这一行:
this.logger.debug("names: {}", xxxxx);
默认情况下,slf4j / logback支持。只是做
logger.debug("names: {}", names);
例如
List<String> list = new ArrayList<String>();
list.add("Test1"); list.add("Test2"); list.add("Test3");
logger.debug("names: {}", list);
//produces
//xx::xx.xxx [main] DEBUG [classname] - names: [Test1, Test2, Test3]
或者你想要一些特别不同的东西?