简体   繁体   English

动态设置Log4j.xml日志文件名

[英]Set Log4j.xml logging file name dynamically

I would like to set the log file name for a log4j.xml. 我想为log4j.xml设置日志文件名。 We are doing Daily rollovers. 我们正在做每日展期。 The log file name format would be hostname_current datetime.log. 日志文件名格式为hostname_current datetime.log。 I am using application server as JBoss EAP 6.2 我正在将应用程序服务器用作JBoss EAP 6.2

You can configure log4j on runtime with PropertyConfigurator.configure(path.log4j.properties); 您可以使用PropertyConfigurator.configure(path.log4j.properties);在运行时配置log4j。 Now, if you want to change the log file name, you can use different paths each time or change the properties file dynamically. 现在,如果要更改日志文件名,则可以每次使用不同的路径,也可以动态更改属性文件。 Maybe there is a better way to do that without using the file, but I do not know it. 也许有一种更好的方法可以在不使用文件的情况下执行此操作,但是我不知道。

I dont know if you use log4j 1.x or log4j 2.x. 我不知道您是否使用log4j 1.x或log4j2.x。 In log4j there are appenders where you clearly define what the name of your log-file is and where log4j has to deploy it etc... 在log4j中,有一些附加程序,您可以在其中清楚地定义日志文件的名称以及log4j的部署位置等...

If you want to set it dynamically you have to rewrite the log4j.xml by a programm or whatever. 如果要动态设置它,则必须通过程序或其他方法重写log4j.xml。

Here is a snip of a settings-file using a FileAppender : 这是使用FileAppender的设置文件的FileAppender

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
  <Appenders>
    <File name="MyFile" fileName="logs/anameyouwant.log" append="true">
      <PatternLayout>
        <Pattern>%d{HH:mm:ss.SSS} [%-5level] %msg [%t] %logger{30} %n</Pattern>
      </PatternLayout>
    </File>
  </Appenders>
  <Loggers>
    <Root level="all">
      <AppenderRef ref="MyFile"/>
    </Root>
  </Loggers>
</Configuration> 

In this example I use a FileAppender which writes the log to /logs/anameyouwant.log . 在此示例中,我使用FileAppender将日志写入/logs/anameyouwant.log It appends the information to the logfile. 它将信息附加到日志文件。 This is the part you have to rewrite dynamically: fileName="logs/anameyouwant.log" I dont see other ways to resolve the problem except this solution where you rewrite the settings-file at the beginning before your run your programm and start logging. 这是您必须动态重写的部分: fileName="logs/anameyouwant.log"我看不到其他解决问题的方法,除了该解决方案,您需要在运行程序并开始记录之前从头重写设置文件。

Here are maybe some helpfull Links: 这里可能是一些有用的链接:

Appenders of Log4j Log4j的追加者

A DailyRollingFileAppender DailyRollingFileAppender

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

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