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!
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.
Check out the AspectJ documentation on how to change the TraceMethodCalls calls.
Regarding the
That’s supported by slf4j/logback by default. Just do
for example
Or do you want something specifically different?