I am working on a project, and am currently working on implementing some logging with log4j and I was curious about how I should go about implementing the logs. The two implementations I am kicking around are as follows:
First Option
Use single log from super class for that class and all sub classes:
public abstract class AbstractFoo { protected static Log LOG = LogFactory.getLog(AbstractFoo.class); ... } public class Foo extends AbstractFoo { public void someMethod() { LOG.info("Using abstract log"); } }
Second Option
Use individual logs for each class, super and subs:
public abstract class AbstractFoo { private static Log LOG = LogFactory.getLog(AbstractFoo.class); ... } public class Foo extends AbstractFoo { private static Log LOG = LogFactory.getLog(Foo.class); public void someMethod() { LOG.info("Using own log"); } }
What makes more sense and why?
If you create the logger in the abstract class, the logs will all come out tagged as originating from AbstractFoo. If you want/need to see logs tagged with the child class from which the log occurred, create loggers for the children classes.
Use @Log4j annotation with all the classes in which you wish using logger. Benefits: Easy to maintain, easy to track down. Only one object of the logger is created which will be used through out.
One of the most popular solutions for the Java world is the Apache Log4j 2 framework. Maintained by the Apache Foundation, Log4j 2 is an improvement on the original Log4j, which was the most popular logging framework in Java for many years.
Short answer: yes, it decreases application performance as it uses some CPU cycles and other resources (memory, etc). Show activity on this post. Logging can be 30% of you cpu time or more. In terms of jitter, it as large (and more often) than your GC delays.
I wouldn't do either. Instead I would make it use the correct class in both cases.
public abstract class AbstractFoo { protected final Log log = LogFactory.getLog(getClass()); ... } public class Foo extends AbstractFoo { public void someMethod() { log.info("Using abstract log"); } }
If you are not doing lots of logging (which is a good idea anyway) you can use a method instead.
public abstract class AbstractFoo { protected Log log() { return LogFactory.getLog(getClass()); } ... }
If there is a class which calls this a lot you can override it to give you a cached instance.
This is my solution (final static logger):
public abstract class AbstractFoo { protected abstract Log getLogger(); public doSomething() { getLogger().info("log something"); } } public class Foo extends AbstractFoo { private static final Log log = Log.getLogger(Foo.class); protected Log getLogger() { return log; } public doSomethingElse() { log.info("log somethingElse"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With