简体   繁体   English

在Web应用程序中使用log4j的最佳方法是什么?

[英]What is the best way to use log4j in the web application?

We are starting a Spring MVC based web application. 我们正在启动一个基于Spring MVC的Web应用程序。 We will be using tomcat as the web server. 我们将使用tomcat作为Web服务器。

I need to configure log4j in the application and log to the application specific file and not to the tomcat log files. 我需要在应用程序中配置log4j并登录到特定于应用程序的文件,而不是tomcat日志文件。

eg tomcat has its own log files like localhost.log etc. I want something like myAppName.log in the tomcats log folder. 例如,tomcat有其自己的日志文件,如localhost.log等。我想要tomcats日志文件夹中的myAppName.log之类的东西。

The logging configuration will go in lo4j.xml or log4j.properties in the application war file. 日志记录配置将进入应用程序war文件中的lo4j.xml或log4j.properties。

Plus I dont want to hard code the output log file in the web application. 另外,我不想在Web应用程序中对输出日志文件进行硬编码。

But I am not sure how to do this. 但是我不确定该怎么做。

Please help me. 请帮我。 As well correct me if I am wrong somewhere. 如果我在某个地方错了,也请纠正我。

Do like this, initialize the logger with following code, 这样做,用以下代码初始化记录器,

Logger log = Logger.getLogger(this.getClass());

log the information like follows, 记录如下信息

log.debug("My message");

and place the log4j.xml in your class path. 并将log4j.xml放在您的类路径中。 content like follows, 内容如下

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
     <appender name="infoLogsFile" class="org.apache.log4j.RollingFileAppender">
         <param name="File" value="MyApplication.log"/>     
         <param name="Threshold" value="DEBUG"/>
         <param name="MaxFileSize" value="100MB"/>
         <param name="ImmediateFlush" value="TRUE"/>
         <layout class="org.apache.log4j.PatternLayout">
           <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
         </layout>
    </appender>
   <root> 
      <priority value ="DEBUG" /> 
      <appender-ref ref="infoLogsFile"/>
   </root>
</log4j:configuration>

Do not forget to add the required jars like log4jXXX.jars and apache common logging jars. 不要忘记添加所需的jar,例如log4jXXX.jars和apache常用日志记录jar。 with this you will be able to see all log messages in MyApplication.log file creates in bin folder of your tomcat. 有了它,您将能够查看在tomcat的bin文件夹中创建的MyApplication.log文件中的所有日志消息。

Try this: 尝试这个:

  • Put the log4j jar as part of the web application 将log4j jar作为Web应用程序的一部分

  • Do not put a configuration as part of your web application 不要将配置作为Web应用程序的一部分

  • Create your log4j.xml wherever you like 随时随地创建log4j.xml

  • When you start tomcat provide this argument -Dlog4j.configuration=file:///.../log4j.xml 当您启动tomcat时,请提供此参数-Dlog4j.configuration = file:///.../log4j.xml

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

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