简体   繁体   English

创建动态log4j输出文件

[英]Creating a dynamic log4j output file

I am trying to make a log4j file using html layout. 我正在尝试使用html布局制作一个log4j文件。 Heres my log4j files 这是我的log4j文件

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/htmlLayout.html

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=HTML Layout Example
log4j.appender.FILE.layout.LocationInfo=true

This is static, but I want to make it such that my main method will pass this line 这是静态的,但是我要使其成为主方法可以通过此行

 log4j.appender.FILE.File=myfilepath/myfilename.html 

How can I do this? 我怎样才能做到这一点? currently I was trying to use properties, but it deletes everything and only this line shows up. 当前,我正在尝试使用属性,但是它删除了所有内容,并且仅显示此行。

Please Note that the log file path depends on the location from where the jar file of my project is being executed it will be like this 请注意,日志文件路径取决于执行我的项目的jar文件的位置,它将像这样

(jarDir)/logs/myfilename.html (jarDir)/logs/myfilename.html

You'll have to call the log4j configurator directly rather than being able to rely on the default initialisation behaviour. 您必须直接调用log4j配置器,而不是能够依赖默认的初始化行为。 Name the properties file something other than log4j.properties so the default procedure doesn't find it, then in your code you can do 将属性文件命名为log4j.properties以外的名称,以便默认过程找不到它,然后可以在代码中执行

Properties props = new Properties();
// if MyClass is in package com.example, look for
// com/example/log4j-config.properties inside the jar
InputStream in = MyClass.class.getResourceAsStream("log4j-config.properties");
try {
  props.load(in);
} finally {
  in.close();
}

// override file location
props.setProperty("log4j.appender.FILE.File", "myfilepath/myfilename.html");

LogManager.resetConfiguration();
PropertyConfigurator.configure(props);

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

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