You don't want to tie up all your business and data access code with the ServletContext
(I of course assume that your business and DB code is not tight coupled inside a servlet class, but just live in their own layer of classes, without any javax.servlet
references). So I wouldn't recommend to use ServletContext#log()
. It's also very seldom used in real world.
You're right that log4j is popular, even though it's been succeeded by logback. Setting up log4j doesn't need to be that troublesome. I suggest to start with a properties file which is less hard to understand than a XML file. You can always upgrade to a XML file once you understand what's going on in log4j configuration.
Create a file named log4j.properties
, put it somewhere in the root of the classpath, e.g. /WEB-INF/classes
(or if you're using an IDE, the root of the src
folder, it will eventually land in the right place). You can also keep it outside the webapp and add its path to the server's runtime classpath by specifying its path in shared.loader
property of Tomcat/conf/catalina.properties
. Finally fill it as follows:
# Set root logger level and appender name.
log4j.rootLogger = TRACE, console
# Specify appenders.
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.file = org.apache.log4j.DailyRollingFileAppender
# Configure console appender.
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = %d{ABSOLUTE} [%t] %-5p %m%n
# Configure file appender.
log4j.appender.file.File = /webapp/logs/web.log
log4j.appender.file.DatePattern = '.'yyyy-MM-dd
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %d{ABSOLUTE} [%t] %-5p %m%n
This kickoff example by default logs at a level of TRACE
. You can change it to DEBUG
or INFO
like so:
# Set root logger level and appender name.
log4j.rootLogger = INFO, console
This example also by default uses the console appender. It will log to the standard output as it is configured by Tomcat which by default lands in the /logs/localhost.yyyy-MM-dd.log
file.
You can however change it to use the file appender like so:
# Set root logger level and appender name.
log4j.rootLogger = INFO, file
The ConversionPattern
settings can be found in detail in the PatternLayout
javadoc.
Hope this helps to get you started.