8

ログバックを使い始めましたが、何かを行うためのより良い方法があるかどうか知りたいです。私はこのコードを持っています:

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は、リストを印刷するために何かに置き換える必要があります。匿名のクラス?

読んでくれてありがとう!

4

1 に答える 1

12

AspectJlog4jを使用すると、これを使用できます。javacの代わりにajcコンパイラを使用してコードをコンパイルしてから、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呼び出しを変更する方法については、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]

それとも、特に違うものが欲しいですか?

于 2009-06-26T20:24:03.413 に答える