How to use log4j in code?
We开发者_StackOverflow have to introduce logging in our application. We have decided to use log4j is it a good choice. Also somebody told that we should use singleton pattern for using log4j can somebody emphasise how and why?
In the singleton pattern, the Logger
field is static to the class:
public class SomeAwesomeClass {
private static final Logger logger = Logger.getLogger(SomeAwesomeClass.class);
}
The alternative is to make the Logger
field non-static (that is, each instance of SomeAwesomeClass
holds a reference to the Logger
):
public class SomeAwesomeClass {
private final Logger logger = Logger.getLogger(SomeAwesomeClass.class);
}
I don't think it makes a lot of difference which route you choose as I believe Log4j will continually return the same Logger
instance for each instance of SomeAwesomeClass
. Really, it's just unnecessary object references, so you might as well use the singleton pattern.
However, the non-singleton pattern becomes necessary if you do something like this:
public class SomeAwesomeClass {
private final Logger logger = Logger.getLogger(getClass());
public void doSomething() {
log.info("Doing something");
}
}
public class AwesomerClass extends SomeAwesomeClass {
}
Later...
SomeAwesomeClass o = new AwesomerClass();
o.doSomething();
In this example, the logger
field will correspond to AwesomerClass
, not SomeAwesomeClass
.
If you are introducing logging for the first time then use Logback. Use the configuration file as suggested here and add it to the classpath. Logging will be auto configured.
The reason why Singleton is sometimes preferable is that we want only one instance of the Logger per application, otherwise, for every new instance of the logger, there will be a newly created file or an overwrite of an existing log file.
As to whether Log4J is a good choice or not will depend on your research/experience with the different loggers available. It's all about your preference (I use Log4J all the time as I find it easier to configure, but I'm not biased to any loggers out there).
Famous ones out there are:
- Log4J
- SLF4J
- LogBack
- Java's own Logging....
There are some examples on the web that shows you how to use loggers. Here is a brief comparison for Log4J vs SLF4J.
精彩评论