【问题标题】:How to use properties in a Spring project to configure log4j.xml如何在 Spring 项目中使用属性来配置 log4j.xml
【发布时间】:2011-05-25 16:10:27
【问题描述】:

我的 Spring 项目中有多个属性文件。 spring 上下文加载这些属性并以方便的方式处理属性覆盖。有没有办法获取我的 Spring 配置 XML 文件(即${myprop})可用的属性,并在我的log4j.xml 文件中以类似的方式使用它们?我知道我可以在启动时使用-Dprop=value 将系统属性传递给 log4j,但我更希望在项目的属性文件中包含所有配置。这可能吗?

我的应用在 Tomcat 中运行。

【问题讨论】:

  • 我不认为你能做到这一点——log4j 不提供这种内省。
  • 即使这是可能的,您也可能会错过一些日志记录,因为 Spring 本身会在启动上下文和加载属性时记录到 log4j。

标签: spring logging log4j


【解决方案1】:

在将多个属性文件集成到一个属性后,尝试使用此类。

public class DOMConfiguratorWithProperties extends DOMConfigurator {

    private Properties propertiesField = null;

    public synchronized Properties getProperties() {
        return propertiesField;
    }

    public synchronized void setProperties(final Properties properties) {
        propertiesField = properties;
    }

    @Override
    protected String subst(final String value) {
        return super.subst(value, getProperties());
    }

    public static void configure(final String filename) {
        new DOMConfiguratorWithProperties().doConfigure(
                filename,
                LogManager.getLoggerRepository());
    }

    public static void configure(
            final String filename,
            final Properties properties) {
        DOMConfiguratorWithProperties configurator = new DOMConfiguratorWithProperties();
        configurator.setProperties(properties);
        configurator.doConfigure(
                filename,
                LogManager.getLoggerRepository());
    }
}

【讨论】:

  • 这看起来像是一个有效的解决方案。不幸的是,因为我在 Spring Web 容器中工作,所以在大部分上下文已经加载之前,我无法执行此代码。这意味着会有很多初始日志不会转到我的新日志位置(由我的属性文件定义)。我不喜欢应用程序记录到多个位置的想法,所以我想我会放弃通过属性文件使记录位置更加灵活的希望。感谢您的回答。我相信有人会从这段代码 sn-p 中受益。
【解决方案2】:

我认为与 Log4J 交互的唯一方法是通过Nested diagnostic context

因此,如果您非常绝望,您可以编写一个 Spring AOP 方面,为您的 Spring Bean 日志设置诊断上下文(并且您可以使用那里的属性)。但是,这将要求 Spring Bean 可以使用 Log,因此您需要将 getLog() 方法添加到您的服务接口(如果您使用静态 AspectJ 编译,这将变得容易得多,在 AspectJ in Action 中有描述) .

但是由于没有使用 AOP,我想不出一个明智的方式让 Spring 和 Log4J 交互。

【讨论】:

  • 感谢您的意见。根据您所说,我有一个问题:是否可以让 log4j.xml 文件使用外部属性文件 - 以便将某些设置硬编码在 xml 文件中?
  • 使用maven或ant进行资源过滤怎么样?
猜你喜欢
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 2017-08-14
  • 2015-11-11
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多