gpt4 book ai didi

java - 使用配置的 log4j 跟踪日志中的类

转载 作者:行者123 更新时间:2023-12-01 15:22:11 25 4
gpt4 key购买 nike

我有一个查询,假设我开发了一个简单的类...

    class Simple
{
public static void main(String args[])
{
System.out.println("I am a good bouy");
}
}

现在,在我的应用程序的前端,假设还有 50 个其他类也被执行,我已经配置 Log4j 也可以在日志中跟踪日志,我只想知道我的上面的类何时被执行,那么我应该做什么进入这个类,这样我就可以跟踪日志并知道此时我上面的类被执行了..它是 log.info("inside Simple class");

最佳答案

在这个示例变得非常有用之前,忽略您需要弄清楚的所有其他事情,您所要做的就是修改日志配置,当您打印出一个日志时,它会为您打印类和行记录消息。

我不想这么说,因为它很陈词滥调,但 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

关于java - 使用配置的 log4j 跟踪日志中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10741756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com