Pergunta

Estou começando usando logback e eu quero saber se há melhores maneiras de fazer alguma coisa. Eu tenho esse código:

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;
}

Eu tenho algumas dúvidas até agora:

  • Cada classe terá um this.logger = LoggerFactory.getLogger(this.getClass().getName()); para criar um registrador.
  • Cada método terá um this.logger.debug("method()"); saber quando um método é chamado.

Isso não parece bom. Existe uma maneira de resolvê-lo?

Também quero imprimir uma lista no log nesta linha: this.logger.debug("names: {}", xxxxx);

o xxxxx deve ser substituído por algo para imprimir a lista. Uma classe anônima?

Obrigado por ler!

Foi útil?

Solução

Usando AspectJ e log4j você pode usar este. Compilar o código com o compilador AJC em vez de javac e execute como normal com executável Java.

Você precisa ter o aspectjrt.jar e log4j.jar no classpath.

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() + "]");
        }
    }
}

Confira a documentação AspectJ sobre como alterar as TraceMethodCalls chamadas.

// e.g. just caputre public method calls
// change this
: (execution(* *.*(..))
// to this
: (execution(public * *.*(..))

Em relação ao

Também quero imprimir uma lista na .log nesta linha: this.logger.debug("names: {}", xxxxx);

Isso é apoiado por slf4j / logback por padrão. Basta fazer

logger.debug("names: {}", names);

Por exemplo

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]

Ou você quer algo especificamente diferente?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top