我正在开发一个使用 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/