在这个例子之前你需要弄清楚的所有其他事情都会很有用,你所要做的就是修改日志配置,当你打印出日志消息时,它会为你打印类和行。
我不想这么说,因为它很陈词滥调,但 RTFM 是这里最好的方法。此页面将告诉您入门所需的大部分内容:
http://logging.apache.org/log4j/1.2/manual.html
您只需要为您的记录器提供一个特定的 ConversionPattern 配置选项,它会在您每次记录消息时记录类名甚至行信息。这是该页面的示例:
// 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{yyyyMMdd 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