学习log4j刚开始从网上找一些例子,相当粗糙也不给力,花了两天功夫现在明白点,总算是搞定了。
做个笔记。很给力的写下自己的心得。
1.log4j 硬编码在程序里.
下面给几个例子:
在这之前你得干两件事:
首先你得下载log4j.jar,找不到就迅雷下载,百度也可以搜到,解压后,会找到一个log4j-1.2.16.jar 如图:
最后,将log4j-1.2.1.16.jar 引进来,担心说的不明白,见图:
没有lib就新建一个文件夹,将jar复制进去,然后点击右键--->build path-->add jar
那么下面的代码才不会提示错误.
基本示例
a.这里是一个非常简单的例子,程序实现了SimpleLayout和FileAppender:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;
public class simpandfile {
static Logger logger = Logger.getLogger(simpandfile.class); //日志记录器
public static void main(String args[]) {
SimpleLayout layout = new SimpleLayout(); //输出格式:级别-日志信息
FileAppender appender = null;
try {
appender = new FileAppender(layout,"output1.txt",false); //对指定的文件不进行追加的方式输出
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
logger.debug("11Here 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");
} catch(Exception e) {}
}
b.这里是一个非常简单的例子,程序实现了 HTMLLayout和WriterAppender:
import java.io.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.WriterAppender;
public class htmlandwrite {
static Logger logger = Logger.getLogger(htmlandwrite.class);
public static void main(String args[]) {
HTMLLayout layout = new HTMLLayout();
WriterAppender appender = null;
try {
FileOutputStream output = new FileOutputStream("output2.html");
appender = new WriterAppender(layout,output);
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
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");
} catch(Exception e) {}
}
c.这里是一个非常简单的例子,程序实现了PatternLayout和ConsoleAppender:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.ConsoleAppender;
public class consandpatt {
static Logger logger = Logger.getLogger(consandpatt.class);
public static void main(String args[]) {
// Note, %n is newline
String pattern = "Milliseconds since program start: %r %n";
pattern += "Classname of caller: %C %n";
pattern += "Date in ISO8601 format: %d{ISO8601} %n";
pattern += "Location of log event: %l %n";
pattern += "Message: %m %n %n";
PatternLayout layout = new PatternLayout(pattern);
ConsoleAppender appender = new ConsoleAppender(layout);
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
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");
}
}
通过运行,查看运行结果
+上面标题为:
log4j Logger and FileAppender 的学习
log4j HTMLLayout和WriterAppender学习
结合看是没有大问题问题的。
下面接着 log4j的外部配置