import java.io.FileOutputStream;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.ConsoleAppender;
public class Log4jTest {
private static Logger logger= Logger.getLogger( Log4jTest.class );
/**
* Simpler Layout and File Appender test.
*/
private void doSimpleFileTest(){
SimpleLayout layout = new SimpleLayout();
FileAppender appender = null;
try {
appender = new FileAppender(layout,"output1.txt",false);
} catch (Exception ex) {}
logger.addAppender( appender );
logger.setLevel( Level.DEBUG );
// test log
testLog();
}// end doSimpleFileTest method
/**
* HTML layout and writer appender test.
*/
private void doHTMLWriterTest(){
HTMLLayout layout = new HTMLLayout();
layout.setTitle( "Log4j test: html format" );
WriterAppender appender = new WriterAppender();
try {
FileOutputStream out = new FileOutputStream("output2.html",false);
appender = new WriterAppender(layout, out);
} catch (Exception ex) {}
logger.addAppender( appender );
logger.setLevel( Level.DEBUG );
// test log
testLog();
}
/**
* Pattern layout and console appender test.
*/
private void doPatternConsoleTest(){
// pattern
String pattern = "Milliseconds since program start: %r %n" +
"Classname of caller: %C %n" +
"Data in ISO8601 format: %d{ISO8601} %n" +
"Data in DATE format: %d{DATE} %n" +
"Data in ABSOLUTE format: %d{ABSOLUTE} %n" +
"Location of log event: %l %n" +
"Message: %m %n %n";
PatternLayout layout = new PatternLayout( pattern );
ConsoleAppender appender = new ConsoleAppender( layout );
logger.addAppender( appender );
logger.setLevel( Level.DEBUG );
// test
testLog();
}
// helper method testLog
private void testLog(){
logger.debug( "Here is some DEBUG" );
logger.info( "Here is some INFO" );
logger.warn( "Here is some WARN" );
logger.error( "Here is some ERROR" );
logger.fatal( "Here is some FATAL" );
logger.info( "中文日志");
}
public static void main( String[] args ){
Log4jTest test = new Log4jTest();
test.doSimpleFileTest();
test.doHTMLWriterTest();
test.doPatternConsoleTest();
}
}