简体   繁体   English

加载log4j.xml时如何记录异常

[英]how to log exception while loading log4j.xml

We have a Java program that gets packaged as a runnable jar. 我们有一个Java程序,它被打包为可运行的jar。 The logging is via slf4j with log4j. 通过slf4j和log4j进行日志记录。 We have placed log4j.xml outside the runnable jar - onto the file system. 我们已将log4j.xml放在可运行jar之外-放置在文件系统上。 As soon as the user clicks on the runnable jar, the main method is invoked which calls the function to load the log4j.xml file. 用户单击可运行jar时,将立即调用main方法,该方法将调用函数以加载log4j.xml文件。 My question is what if the loading of log4j.xml itself fails. 我的问题是,如果log4j.xml本身的加载失败,该怎么办? How can that exception be logged? 如何记录该异常? Logger is not yet initialized and sys.out to my knowledge will not be useful in that case. Logger尚未初始化,在我所知的情况下sys.out不会有用。 Here is the piece of code which gets invoked right after main method is invoked: 以下是在调用main方法之后立即被调用的代码:

/* This method loads the log4j.xml file from local directory */
public static void loadLog4jXml(){
        DOMConfigurator.configure( "C:\MyFirstJavaExecJar\log4j.xml" );
    }

I tried googling it, but could not find any pointers whatsoever. 我尝试使用Google搜索,但找不到任何指针。 Also tried going through the FAQ list on apache website: http://logging.apache.org/log4j/2.x/faq.html 还尝试浏览apache网站上的FAQ列表: http//logging.apache.org/log4j/2.x/faq.html

Any help is appreciated! 任何帮助表示赞赏!

Why it is not not working just capsulate the code with try catch blog and log it to Console or a file, because it is not a thing to be happened frequently. 为什么它不起作用,只是用try catch Blog封装代码并将其记录到Console或文件中,因为这不是经常发生的事情。

/* This method loads the log4j.xml file from local directory */
public static void loadLog4jXml(){
        try{
             DOMConfigurator.configure( "C:\MyFirstJavaExecJar\log4j.xml");
        }
        catch(Exception e){
          System.out.println("There is a problem about log4J file loading");
        }
    }

Ok first you encapsulate your code when you loading the log4j file with a try catch and if you run it in windows console, console is the dos screen at here, so if there is a problem at windows when you run it via java -jar yourJar.jar in that case it writes messages to your dos screen. 好吧,首先,当您使用try catch加载log4j文件时封装了代码,如果您在Windows控制台中运行它,则控制台是此处的dos屏幕,因此,当通过java -jar yourJar.jar运行它时,如果在Windows上存在问题, java -jar yourJar.jar在这种情况下会将消息写入您的dos屏幕。 Or you can give a file path to this jar and write your log to this file. 或者,您可以提供此jar的文件路径,并将日志写入此文件。 Or you can use event logging for more sophisticated solution, Please check this discussion for it. 或者,您可以将事件日志记录用于更复杂的解决方案,请查看此讨论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM