问题描述
我们有一个模块化应用程序,其中模块具有自己的log4j日志(即通信日志和错误日志).这些附录和类别均在核心log4j XML中配置,但并非所有模块始终安装. DailyrollollingFileAppender不管使用什么都可以创建其文件,并且虽然不存在,但它会揭露完整的模块,因为其中一些是客户特定的,我们想隐藏不使用的日志. 有没有办法使dailyrolllingfileappender在首次使用中创建文件,而不是在启动时自动创建文件?
推荐答案
文件附录无法懒惰地创建日志文件 - setFile方法会自动创建该文件,如果该文件尚不存在:ostream = new FileOutputStream(fileName, append);
您必须扩展附录并自己覆盖文件初始化代码才能获得您追求的行为.
其他推荐答案
我也有同样的问题,所以我扩展了标准的fileappender类,并且创建了一个新的 lazyfileappender 这是一个懒惰的fileappender,它懒惰地初始化日志文件(仅在第一次写入操作时就创建它).
您可以查看源以开发自己的扩展名,也可以按原样使用它来使用它.
其他推荐答案
在log4j 2中,fileappender和rollingfileappender均具有参数" create -demand",可用于配置仅当传递给appender的日志事件时,才能将其用于创建日志文件.
示例:
<RollingFile name="LogFile" fileName="test.log" filePattern="test-%i.log.gz" createOnDemand="true"> <Policies> <SizeBasedTriggeringPolicy size="1MB"/> </Policies> <DefaultRolloverStrategy max="5"/> </RollingFile>
更多详细信息在这里: org/log4j/2.x/Manual/appenders.html#rollingRandomAccessfileAppender
问题描述
We have a modular application where modules have their own log4j logs (i.e. communication log and error log). The appenders and categories for these are all configured in the core log4j XML, but not all modules are always installed. The DailyRollingFileAppender creates its file regardless of use and that exposes the full set of modules although not present and as some of them are customer specific we'd like to hide logs not in use. Is there a way to make DailyRollingFileAppender create its file on first use instead of automatically at startup?
推荐答案
The file appenders have no option to lazily create the log files - the setFile method automatically creates the file if it doesn't already exist: ostream = new FileOutputStream(fileName, append);
You'll have to extend the appender and overwrite the file initialisation code yourself to get the behaviour you're after.
其他推荐答案
I had the same problem, so I have extended the standard FileAppender class and I have created a new LazyFileAppender that is a FileAppender that lazily initialize the log file(creates it only when the first write operation happens).
The LazyFileAppender and some other additions to the standard log4j library can be found into a simple library that I have created : log4j-additions .
You can look at the source to develop your own extension or you can use it as is ...
其他推荐答案
In Log4j 2, both FileAppender and RollingFileAppender has the parameter "createOnDemand" which can be used to configure to create the log file only when a log event passed to the appender.
Example:
<RollingFile name="LogFile" fileName="test.log" filePattern="test-%i.log.gz" createOnDemand="true"> <Policies> <SizeBasedTriggeringPolicy size="1MB"/> </Policies> <DefaultRolloverStrategy max="5"/> </RollingFile>
More details here: https://logging.apache.org/log4j/2.x/manual/appenders.html#RollingRandomAccessFileAppender