【问题标题】:Spring Boot: Using Tomcat context parameters in logback configurationSpring Boot:在 logback 配置中使用 Tomcat 上下文参数
【发布时间】:2016-06-12 17:50:03
【问题描述】:

我有几个 Spring Boot 应用程序实例部署在一个独特的 Tomcat 中。 每个应用程序都配置了一个包含客户代码的 context.xml 文件

<Context path="/myApp1" reloadable="false">
    <Parameter name="CUSTOMER_CODE" value="CUSTOMER1" />
</Context>

我希望每个客户都有一个基于 context.xml 中定义的代码的单独日志。

不幸的是,这个配置在我的 logback-config.xml 中不起作用:

<property name="LOG_FILE" value="${ROOT_LOG}/${CUSTOMER_CODE}/myApp.log}"/>

在“ROOT_LOG”目录中创建了一个文件夹 CUSTOMER_CODE_IS_UNDEFINED。 “ROOT_LOG”由系统属性提供。

有没有办法让这个 logback 配置工作?

application.properties 中定义的属性的使用效果很好(我将 logback.xml 重命名为 logback-spring.xml)。在我看来,Spring boot 在初始化日志记录之前没有在 Environnement 中设置 Tomcat 上下文参数。任何解决方法的想法?谢谢。

【问题讨论】:

  • 我认为自定义 logback 配置 (logback-spring.xml) 将满足您的需求:docs.spring.io/spring-boot/docs/current/reference/html/… - 主要是您可能只需要重命名配置文件。
  • 感谢您的回答。我尝试使用 logback-spring.xml 但它没有用。我更新了帖子以添加更多信息。

标签: spring-boot logback tomcat8


【解决方案1】:

我终于找到了一个解决方案,可以在记录初始化之前让我的客户代码在 Spring Environment bean 中可用。不是很漂亮,但它正在工作:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

  public static String APP_CUSTOMER_CODE;

  /**
   * Initialization of Spring Boot App with context param customer code
   */
  @Override
  protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) {
    final Map<String, Object> initProps = new HashMap<>();
    initProps.put("CUSTOMER_CODE", APP_CUSTOMER_CODE);
    return builder.properties(initProps).sources(Application.class);
  }

  /**
   * Method called before Spring Initialization
   */
  @Override
  public void onStartup(final ServletContext servletContext) throws ServletException {
    APP_CUSTOMER_CODE = servletContext.getInitParameter("CUSTOMER_CODE");
    super.onStartup(servletContext);
  }

}

另外,我必须在 logback-spring.xml 中声明一个 springProperty 标签才能使用该变量:

 <springProperty name="CUSTOMER_CODE" source="CUSTOMER_CODE"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-25
    • 2020-01-18
    • 1970-01-01
    • 2015-09-17
    • 2017-05-17
    • 2019-10-14
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多