2009-06-26 115 views
5

我开始使用logback,我想知道是否有更好的方法做某事。 我有这样的代码: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

第一个问题是http://en.wikipedia.org/wiki/Aspect-oriented_programming的教科书案例,但我自己并不熟悉写一个实际的答案。 – 2009-06-26 19:20:50

回答

4

使用AspectJlog4j你可以使用这个。用ajc编译器代替javac编译你的代码,然后用java可执行文件正常运行。

您需要在classpath上具有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调用AspectJ的文档。

// 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] 

或者你想要的东西特别有什么不同?

+0

对打印列表问题添加了答案 – jitter 2009-06-27 08:58:16