2009-06-26 110 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