如何在log4j文件名中插入当前webapp的文件夹名称

b1zrtrql  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(123)

我正在编写一个部署在Tomcat中的Java Web应用程序,我使用log4j进行日志记录。我喜欢在生成的日志文件名中自动插入Web应用程序的文件夹名。
目前,www.example.com中的文件名设置如下所示log4j.properties:

log4j.appender.R.File=${catalina.home}/logs/mywebapp.log

我需要这样的东西:

log4j.appender.R.File=${catalina.home}/logs/${current.webapp.folder}.log

是否有某种环境变量可以在属性文件中指定,或者我必须从代码中示例化记录器?

tag5nh1u

tag5nh1u1#

您可以使用上下文侦听器来设置系统属性,然后在log4j配置中使用该属性来实现这一点。

步骤1:设置系统属性

您可以首先将系统属性(例如contextPath)设置为应用程序的Tomcat上下文路径的值。您可以在上下文侦听器中执行此操作。

package my.package.listener;

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

public class ContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        defineContextPath(event);
    }

    private void defineContextPath(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        String contextPath = context.getContextPath();

        if (contextPath != null) {
            String pattern = ".*/(.*)";
            String contex = contextPath.replaceAll(pattern, "$1");
            System.setProperty("contextPath", contex);
            System.out.println("contextPath: " + contex);
        } else {
            System.out.println("contextPath not found");
        }
    }
}

在web.xml中声明侦听器:

<!-- Be sure to keep my.package.ContextListener as the first listener 
     if you have more listeners as below --> 
<listener>
    <listener-class>my.package.ContextListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

步骤2:使用system属性设置log4j文件名

然后,在log4j配置文件中,可以使用系统属性contextPath设置log4j文件名。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %5p %c{1}:%L - %m%n" />
        </Console>
        <RollingFile name="RollingFile" fileName="${catalina.base}/logs/${tomcat.hostname}/${contextPath}.log" 
            filePattern="${catalina.base}/logs/${tomcat.hostname}/$${date:yyyy-MM}/${contextPath}-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n" />
            <TimeBasedTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="500 MB" />
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="org.apache.log4j.xml" level="info" />
        <Root level="info">
            <AppenderRef ref="STDOUT" />
            <AppenderRef ref="RollingFile"/> 
        </Root>
    </Loggers>
</Configuration>

参考

yxyvkwin

yxyvkwin2#

这不是一个配置文件唯一的解决方案,所以我保持了一段时间的问题开放。
我已将log4j.properties重命名为myapp-log4j.properties,并将日志文件名称属性修改为:

log4j.appender.R.File=${catalina.base}/logs/#{context.name}.log

因为我有一个在启动时加载的servlet,所以我在init()函数中初始化log4j。

String contextPath = getServletContext().getContextPath();

// First reconfigure log4j
String contextName = contextPath.substring(1);
if (!configureLog4J(contextName)) {
  return;
}

此函数:

public static final String LOG4JAPPENDERRFILE = "log4j.appender.R.File";

  private boolean configureLog4J(String contextName) {
    Properties props = new Properties();
    try {
       InputStream configStream = getClass().getResourceAsStream("/myapp-log4j.properties");
       props.load(configStream);
       configStream.close();
    } catch(IOException e) {
       System.out.println("FATAL! Cannot load log4j configuration file from classpath.");
       e.printStackTrace(System.out);
       return false;
    }

    String logFile = props.getProperty(LOG4JAPPENDERRFILE);
    logFile=logFile.replace("#{context.name}", contextName);
    props.setProperty(LOG4JAPPENDERRFILE, logFile);
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(props);
    return true;
  }

它看起来工作得很好,但我真的不喜欢我必须修改代码中的属性文件。

tjrkku2a

tjrkku2a3#

首先尝试附加“log4j.properties“。

current.webapp.folder=myapp

第二,如果您使用“PropertyConfigurator”...

Properties props = new Property();
/* Read "log4j.properties" */

Properties webappProps = new Property();
/* Read setting ex."current.webapp.folder=myapp" */

Enumeration<Object> e = props.propertyNames();
while (e.hasMoreElements()) {
    String key = (String) e.nextElement();
    // used org.apache.log4j.helpers.OptionConverter
    props.setProperty(
            key, 
            OptionConverter.substVars(props.getProperty(key), webappProps));
}

PropertyConfigurator.configure(props);

相关问题