题
我开始使用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()");
要知道当一个方法。
那看起来并不好。有没有办法解决它吗?
我也想打印名单。登录这一行: this.logger.debug("names: {}", xxxxx);
该xxxxx应替换为什么要打印的名单。一个匿名的课吗?
谢谢你读!
解决方案
使用 模型或许 和 log4j 你可以用这个。编译代码与犹太委员会编译器而不是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() + "]");
}
}
}
检查出来的模型或许文件上,如何改变TraceMethodCalls话。
// e.g. just caputre public method calls
// change this
: (execution(* *.*(..))
// to this
: (execution(public * *.*(..))
关于
我也想打印中的一个列表 .登录这一行:
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]
或者你想要的东西的具体的不同?
不隶属于 StackOverflow