我开始使用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;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我有些疑惑:
this.logger = LoggerFactory.getLogger(this.getClass().getName());创建记录器.this.logger.debug("method()");知道何时调用方法的方法.这看起来不太好.有办法解决吗?
另外,我想在此行的.log中打印一个列表: this.logger.debug("names: {}", xxxxx);
xxxxx应替换为打印列表的东西.一个匿名的课程?
谢谢阅读!
使用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() + "]");
}
}
}
Run Code Online (Sandbox Code Playgroud)
查看AspectJ文档,了解如何更改TraceMethodCalls调用.
// e.g. just caputre public method calls
// change this
: (execution(* *.*(..))
// to this
: (execution(public * *.*(..))
Run Code Online (Sandbox Code Playgroud)
关于
另外,我想在此行的.log中打印一个列表:
this.logger.debug("names: {}", xxxxx);
默认情况下,slf4j/logback支持这一点.做就是了
logger.debug("names: {}", names);
Run Code Online (Sandbox Code Playgroud)
例如
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]
Run Code Online (Sandbox Code Playgroud)
或者你想要一些特别不同的东西?