I want to use log4j for a bit of logging on my Tomcat webapp. I have a data-access class that should log the activity when eg a user's information is requested etc. I have added a filehandler and a consolehandler to my rootlogger and I'm perfectly able to see the correct log-messages in the console, but unfortunately not in the specified file.
My code is as follows:
imports...
public class UserDao {
private final Logger logger = Logger.getRootLogger();
public UserDao() {
FileAppender fa = new FileAppender();
fa.setLayout(new PatternLayout("%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %t %c \u2013 %m%n"));
fa.setName("UserDaoFileAppender");
fa.setFile("UserDao.log");
fa.setThreshold(Level.INFO);
fa.setAppend(true);
fa.activateOptions();
logger.addAppender(fa);
ConsoleAppender ca = new ConsoleAppender();
ca.setLayout(new PatternLayout("%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %t %c \u2013 %m%n"));
ca.setThreshold(Level.WARN);
ca.activateOptions();
logger.addAppender(ca);
logger.warn("Test warning");
logger.error("Test error");
logger.info("Test info");
logger.debug("test debug");
}
// Rest of the class.
}
I have tried using the properties-file way of setting up the appender-configuration, but I was never able to get it working. I tried both putting it in the WEB-INF/classes folder and the src-root as some people here proposes.
You are using no-argument constructor for FileAppender. Please use constructor with atleast 2 arguments.
FileAppender fa = new FileAppender();
fa.setLayout(new PatternLayout("%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %t %c \u2013 %m%n"));
replace these 2 lines with below:
FileAppender fa = new FileAppender(new PatternLayout("%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %t %c \u2013 %m%n"), "path of the log file");
I have working sample ( if you are fine with properties file). you would need to copy the log4j.properties in to WEB-INF folder
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${billing.root}/WEB-INF/billing.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.