I’m trying to use a logger across a web application. I have added the FileHandler to write the log into file. Now, I need to use the same handler across other classes/servlets in the project, so that logs from all classes are written to same text file.
How can I achieve this?
/***
* Initialize a logger
*/
public static Logger logger;
static {
try {
FileHandler fh = new FileHandler("log.txt", true);
fh.setFormatter(new SimpleFormatter());
logger = Logger.getLogger(MyClass.class.getName());
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
Do I need to initialize the logger and add handler in every class as in above code? Any other techniques?
I’d consider using a logging framework such as Log4J.
Using it would just boil down to configuring the appenders (e.g. FileAppender) and log levels in a central file (.xml or .properties) and in each class that needs to define a logger you’d just do
Log l = LogFactory.getLog(clazz);(where clazz is the class you define the logger for).You could make the logger public static and use it from other classes as well but I’d not recommend it, since you normally want to know which logger (i.e. which class that logger was defined for) generated a log entry.