Spring:不同ApplicationContext的不同日志记录行为

标签 spring logging javabeans

我正在开发一个使用 Spring 和 slf4j 的应用程序。该应用程序并行使用更多 ApplicationContext。 有没有办法让这些不同的 ApplicationContexts 使用不同的日志记录属性? 所以第一个 AC 可以登录到“x.txt”,而第二个可以登录到“y.txt”。

我不想使用更多的属性文件。适当的方法是在 Spring XML 配置文件中定义一个 Logger Bean,我可以在其中为适当的属性设置不同的输出目标。

例如:

<bean id="LoggerBean" class="???">
     <property name="target" value="${target}" />
</bean>

在这里我可以从源操作目标变量,这会非常方便。

private static final Logger log = LoggerFactory.getLogger(MyClass.class);

因此 LoggerFactory.getLogger 将使用 LoggerBean bean 配置来实例化一个 Logger 类。

我需要一种方法,其中每个 ApplicationContext 都有自己的 LoggerFactory 对象,具有不同的属性(如不同的目标输出)。所以我不必重写当前代码。

我使用由相同的 xml 配置文件配置的 ApplicationContexts。所以这些ApplicationContexts使用 同一个类(class)。因此,所有 Logger 都是从 LoggerFactory 实例化的,具有它们在其中使用的相同类名。 所有 Logger 都由 LoggerFactory.getLogger(MyClass.class) 形式实例化,因为这些类在所有 ApplicationContext ("MyClass") 中都是相同的,我不能定义不同的名称记录器

感谢任何回复。

最佳答案

您可以定义一个 Spring 管理的 bean 来配置记录器。例如,假设你使用logback实现slf4j API,这个类会在Spring设置属性后加载一个指定的日志配置文件到logback中:

public class LogBackConfigurer implements InitializingBean {
    private Resource location;

    public void setLocation(Resource location) {
        this.location = location;
    }

    public void afterPropertiesSet() throws Exception {
        JoranConfigurator configurator = new JoranConfigurator();
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        configurator.setContext(loggerContext);
        configurator.doConfigure(location.getInputStream());
    }
}

在每个 Spring 配置文件中,您希望具有不同的日志记录配置,定义一个如下所示的 bean,并使用不同的日志记录配置文件位置。

<bean class="com.example.log.LogBackConfigurer">
  <property name="location" value="classpath:a-logback.xml"/>
</bean>

该类修改单个应用程序范围的日志记录上下文,这是必需的,因为您想在应用程序代码中调用静态 Logger 工厂方法。为确保日志记录配置文件不会相互干扰,它们各自必须定义不同名称的记录器。

关于Spring:不同ApplicationContext的不同日志记录行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4429853/

相关文章:

java - 在 IntelliJ 中启用 Spring 插件时,某些插件显示错误 'com.spring.intellij not installed'

json - Lucene多重删除查询(JSON)

java - SLF4J:类路径包含多个 SLF4J 绑定(bind) slf4j-test 与 logback-classic

regex - 是否可以排除 apache 访问日志中指定的 GET 参数?

java - Play Framework 2.0 中公共(public)字段的使用

spring - 我需要一个 context.xml 文件来将 spring webapp 部署到 tomcat

eclipse - Spring Eclipse 插件更新站点

concurrency - Java中的不可变bean

google-app-engine - 使用 Spring 连接 Google AppEngine 的 UserServiceFactory

java - SimpleStringProperty set() 与 setValue()