在此示例有用之前, 遗漏所有其它您需要解析的事项, 您只需要修改日志配置, 并在您打印日志消息时打印此类和行 。 @ info: whatsthis
我不想说是因为它已经过时了,但RTFM是这里最好的方法。这个页面将告诉大家,你最需要的就是开始:
http://logbook.apache.org/log4j/1.2/manual.html
您只需要为您的日志输入一个特定的转换 Patter 配置选项, 每次登录信件时, 它会记录类名甚至行信息 。 以下是该页面的一个例子 :
// Import log4j classes.
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
// log4j.appender.console.layout.ConversionPattern=%d{yyyyMMdd HH.mm.ss} %-5p %C.%M(%L): %m%n
class Simple
{
static Logger logger = Logger.getLogger(Simple.class);
protected static void doIt()
{
logger.info("oh yea, we re doing it!");
logger.error(" f-you! joe Boy, you are done!");
logger.fatal("and the world went to bed");
}
public static void main(String[] args)
{
// BasicConfigurator replaced with PropertyConfigurator.
PropertyConfigurator.configure(args[0]);
logger.info("Entering application.");
doIt();
logger.info("Exiting application.");
}
}
建造和运行时产生以下结果:
14:39:56:--> java -classpath log4j-1.2.15.jar:. Simple log4j.properties
20120623 14.41.17 INFO Simple.main(17): Entering application.
20120623 14.41.17 INFO Simple.doIt(24): oh yea, we re doing it!
20120623 14.41.17 ERROR Simple.doIt(25): f-you! joe Boy, you are done!
20120623 14.41.17 FATAL Simple.doIt(26): and the world went to bed
20120623 14.41.17 INFO Simple.main(19): Exiting application.
当您使用像这样的转换模式时 :% d{yyyyyyyyyyyMMMDdd HH.mm.ss}% -5p% C.% M(% L):% m%n
以下是更多具体细节:
1. get a copy of log4j jar and put it in directory
2. create Simple.java in directory
3. create a file log4j.properties in same directory, put this in file:
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyyMMdd HH.mm.ss} %-5p %C.%M(%L): %m%n
4. compile Simple.java with: javac -classpath log4j-1.2.15.jar:. Simple.java
5. run it with this: java -classpath log4j-1.2.15.jar:. Simple log4j.properties