简体   繁体   English

Log4J-J2EE-动态变量

[英]Log4J - J2EE - dynamic variable

Using a JVM variable in log4j.xml configuration does not work... 在log4j.xml配置中使用JVM变量不起作用...

System.setProperty("log_dir", logDirPath);

<param name="file" value="${log_dir}\toto.log" />

It works if I reload my web server while it is running in debug... 如果我在调试中运行Web服务器时重新加载它,则它可以工作...

** UPDATE **更新

package com.webapp.startup;

import java.io.PrintStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.webapp.objects.impl.LoggingOutputStream;

public class Log4jStartup implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        try {
            ServletContext context = event.getServletContext();

            System.setProperty("log_dir", "C:/path");

            System.setErr(new PrintStream(new LoggingOutputStream(Logger.getRootLogger(), Level.ERROR), true));
            System.setOut(new PrintStream(new LoggingOutputStream(Logger.getRootLogger(), Level.INFO), true));

            String path = context.getRealPath("/WEB-INF/classes/log4j.xml");
        PropertyConfigurator.configure(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Initializing the property before setErr and setOut... Thanks to all ! 在setErr和setOut之前初始化属性...谢谢大家!

You are probably populating that property after the log4j system has been initialized. log4j系统初始化之后,您可能正在填充该属性。

In order to have it done before, you can either supply it from the command line when starting the server, or use an initialization servlet like in this example . 为了之前完成它,您可以在启动服务器时从命令行提供它,也可以使用本示例中的初始化servlet。 Scroll to Default Initialization under Tomcat and keep in mind that you only need to specify the property instead of the log4j config file. 滚动到“ Tomcat”下的“默认初始化”,并记住,您只需要指定属性即可,而不是log4j配置文件。

You should tell us when this property is set but nevertheless it will be too late. 您应该告诉我们何时设置了此属性,但为时已晚。 Log4j is typically initialized very early before this property is set. 通常在设置此属性之前很早就初始化Log4j。 I recommend you to set this parameter in initialization block of your web server start script. 我建议您在Web服务器启动脚本的初始化块中设置此参数。 Use -Dlog_dir=path syntax. 使用-Dlog_dir=path语法。

PS what server is it? PS是什么服务器? Tomcat? Tomcat的?

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

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