Reputation: 5386
I'm working on a servlet which needs to log a few things now and then. However, I am uncertain as to how I should configure things.
My first attempt to get things up and running was to create a logging.properties file and then read the logging configuration using the below piece of code.
LogManager.getLogManager().readConfiguration(this.getClass().getResourceAsStream("/logging.properties"));
This works fairly well, but not everything seems to work 100% (I can't really put my finger on what it is, since some things work but others not).
However, I am uncertain about what this does. Does it override all settings from the default logging.properties provided by tomcat - or does it add to the properties provided by tomcat?
Upvotes: 0
Views: 1626
Reputation: 5386
In case someone else should find this question in their hunt for a tutorial which explains how to configure tomcat6 logging, I'll post a brief explanation of how I got things to work.
First of all, even if you know that you will be using java.util.logging I'd still say that it is a good idea to use slf4j. The slf4j library is nothing but a logging facade that simply forwards all logging to java.util.logging. However, if for some reason you should decide, at a later point, to use log4j or commons logging then this will be done in 2 minutes. The slf4j lets you specify which logging framework to use, and it simply forwards logging to that framework.
I chose to use slf4j and then have it to forward all logging to java.util.logging. Just add the 'slf4j-api' and 'slf4j-jdk14' jars to your project and you are good to go. You do not have to do anything to initialise the logging framework in your application. However, you do need to create a properties file which holds details about the logging format, which file to log to and the like. This file is used by java.util.logging and not slf4j, since slf4j just forwards all log events to java.util.logging. Create the file WEB-INF\classes\logging.properties and paste the following code into that file:
handlers = 1yourapplication.org.apache.juli.FileHandler
com.yourpplication.level = ALL
com.yourapplication.handlers = 1yourapplication.org.apache.juli.FileHandler
1yourapplication.org.apache.juli.FileHandler.level = WARNING
1yourapplication.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
1yourapplication.org.apache.juli.FileHandler.prefix = yourapplication.
1yourapplication.org.apache.juli.FileHandler.formatter = java.util.logging.SimpleFormatter
1yourapplication.org.apache.juli.FileHandler.bufferSize = -1
That's it. The file 'yourapplication-YYYY-MM-DD.log' will be created (where YYYY-MM-DD will be replaced with the current date) and logs will be written to that file. A new log file will be created every midnight.
Now, to log something to that file you simply invoke the following code:
LoggerFactory.getLogger(getClass()).info("This is a logging test!");
Your now logging to your applications log file.
Upvotes: 1