0

我有一个查询可以说我开发了一个简单的类...

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

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

4

2 回答 2

1

在这个例子之前你需要弄清楚的所有其他事情都会很有用,你所要做的就是修改日志配置,当你打印出日志消息时,它会为你打印类和行。

我不想这么说,因为它很陈词滥调,但 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
于 2012-06-23T19:55:46.383 回答
0

我们过去常常这样做来跟踪应用程序何时会失败。(如果我正确理解您的问题)我们会进行某种类型的日志记录,以便我们可以跟踪它并确切了解它是如何失败的,以及由于一系列事件而失败的时间。有点像审计线索。我们会添加如下内容。

class Simple
{
    public static void main(String args[])
    {
        log.info("Entering " + this.getClass().getName());
        System.out.println("I am a good bouy");
        log.info("Exiting " + this.getClass().getName());
    }
}

当然你也可以把方法名放在那里。完全取决于您的类和方法的执行方式。

于 2012-05-25T02:35:14.273 回答