Log4j example

Source Code:

package com.feifan.logging.log4j.ch2;


import org.apache.log4j.Logger;
public class FileBasedLoggingDemo implements Runnable{
private static Logger logger =
Logger.getLogger(FileBasedLoggingDemo.class.getPackage().getName());
/** Creates a new instance of FileBasedLoggingDemo */
public FileBasedLoggingDemo()
{
}
public void doLogging()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
int count=1;
while(count <3) {
//logging information
try {
logger.debug("Logging the information..."+count);
Thread.sleep(1000);
count++;
}catch(Exception e) {
logger.warn("Exception occurred", e);
}
}
}
public static void main(String args[])
{
FileBasedLoggingDemo demo = new FileBasedLoggingDemo();
demo.doLogging();
}
}

log4j.properties

#set the level of the root logger to DEBUG (the lowest level)
#and set its appenders named DEBUG and CONSOLE
log4j.rootLogger = DEBUG, CONSOLE
#set your own logger
log4j.logger.com.feifan.logging.log4j.ch2=DEBUG, FILE,ROLLING, DAILY
#set the appender CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
#set the appender FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${user.home}/out.log
#set the appender ROLLING
log4j.appender.ROLLING=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING.File=${user.home}/rolling.log
log4j.appender.ROLLING.MaxFileSize=1KB
#set the appender DAILY
log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY.DatePattern='.' yyyy-MM-dd-HH-mm
log4j.appender.DAILY.File=${user.home}/daily.log


#set the layout for the appenders
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.conversionPattern=%p - %m%n
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%p - %m%n
log4j.appender.ROLLING.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING.layout.conversionPattern=%p - %m%n
log4j.appender.DAILY.layout=org.apache.log4j.PatternLayout
log4j.appender.DAILY.layout.conversionPattern=%p - %m%n


Output:

DEBUG - Logging the information...1
DEBUG - Logging the information...2

你可能感兴趣的:(Log4j example)