Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logback usage and printing lists

Tags:

java

logback

I am starting using logback and I want to know if there are better ways of doing something. I have this code:

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

I have some doubts so far:

  • Every class will have a this.logger = LoggerFactory.getLogger(this.getClass().getName()); to create a logger.
  • Every method will have a this.logger.debug("method()"); to know when a method is called.

That doesn't look good. Is there a way to solve it?

Also I want to print a list in the .log in this line: this.logger.debug("names: {}", xxxxx);

the xxxxx should be replaced with something to print the list. An anonymous class?

Thanks for reading!

like image 770
Macarse Avatar asked Jun 26 '09 19:06

Macarse


People also ask

What is use of Logback?

Logback is one of the most widely used logging frameworks in the Java Community. It's a replacement for its predecessor, Log4j. Logback offers a faster implementation, provides more options for configuration, and more flexibility in archiving old log files.

Is Log4j2 better than Logback?

Log4j, Logback, and Log4j2 are good logging frameworks that are broadly used. So which one should you use? I recommend using Log4j2 because it's the fastest and most advanced of the three frameworks. Logback is still a good option, if performance is not your highest priority.

Does slf4j use Logback?

Native implementation of slf4j is logback, thus using both as logger framework implies zero memory and computational overhead.

Why do we use Logback XML?

Logback executes an async appender in a separate thread to decouple the logging overhead from the thread executing your code. Using the async appender is incredibly easy. Refer the appender that should be asynchronously invoked within an <appender> element.


1 Answers

Using AspectJ and log4j you can use this. Compile your code with ajc compiler instead of javac and then run as normal with java executable.

You need to have the aspectjrt.jar and log4j.jar on the 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() + "]");
        }
    }
}

Check out the AspectJ documentation on how to change the TraceMethodCalls calls.

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

Regarding the

Also I want to print a list in the .log in this line: this.logger.debug("names: {}", xxxxx);

That's supported by slf4j/logback by default. Just do

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

for example

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]

Or do you want something specifically different?

like image 118
jitter Avatar answered Sep 23 '22 05:09

jitter