[英]How to create process based log file using Log4j?
below are my class details. 以下是我的课程详细信息。 ClassA and ClassD are runnable classes. ClassA和ClassD是可运行的类。 From ClassA I am calling ClassB and ClassC. 我从ClassA呼叫ClassB和ClassC。
package comp1 -> Contains ClassA, ClassB, ClassC
package comp2 -> Contains ClassD, ClassE
Log for comp1 -> comp1.log
Log for comp2 -> comp2.log
I am using Log4j for logging. 我正在使用Log4j进行日志记录。 I have two loggers based on package name. 我有两个基于程序包名称的记录器。 I am calling ClassE
and ClassB
from ClassD
. 我从ClassD
调用ClassE
和ClassB
。 Now, comp1.log
contains logging messages from ClassB
and comp2.log
contains log froms ClassD
and ClassE
. 现在, comp1.log
包含来自ClassB
日志消息,而comp2.log
包含来自ClassD
和ClassE
日志。
How can I make a process based log? 如何制作基于流程的日志? If I run ClassD
there should only one log file for ClassD
, ClassE
and ClassB
. 如果我运行ClassD
则ClassD
, ClassE
和ClassB
应该只有一个日志文件。 Is this possible using Log4j? 使用Log4j是否可以?
One solution could be use System Variables. 一种解决方案是使用系统变量。 You can write something like this in your log4j.xml 您可以在log4j.xml中编写类似的内容
<appender name="ProductionLog" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="c:/logs/myLog-${myProcId}.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="10000KB"/>
<param name="MaxBackupIndex" value="10"/>
<layout class="org.apache.log4j.EnhancedPatternLayout">
<param name="ConversionPattern" value="[%d] [%-5p] {%c|%t}: %m%n"/>
</layout>
</appender>
Important is that usage of system variable ${myProcId} 重要的是系统变量$ {myProcId}的用法
You can provide system variable for example before you initialize Log4j eg 例如,您可以在初始化Log4j之前提供系统变量,例如
System.setProperty("myProcId", procId);
DOMConfigurator.configure(log4jFilePath);
There are many ways to do it, personally I would instrument the logs with extra information and then use log processing to split them back out again. 有很多方法可以执行此操作,就我个人而言,我将为日志记录额外的信息,然后使用日志处理将其重新拆分。 If you are Linux based then this should be pretty easy and transfers the extra processing to read time rather than write time. 如果您基于Linux,那么这应该非常容易,并将多余的处理转移到读取时间而不是写入时间上。
Ways to add extra information would be: - 添加额外信息的方法是:-
Another approach would be to use separate loggers which are intitialised by the constructor with a specific name (ProcessA, ProcessB). 另一种方法是使用由构造器初始化的具有特定名称(ProcessA,ProcessB)的单独记录器。 When you instantiate your dependencies you can then pass in the alternate logger name to use in the constructor or via property injection. 实例化依赖项时,您可以传入备用记录器名称以在构造函数中使用或通过属性注入。 If you are using Spring this will be easy, if not then I expect the factory pattern is your friend here. 如果您使用的是Spring,这会很容易,否则,我希望工厂模式是您的朋友。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.