【问题标题】:logback value from web.xml来自 web.xml 的 logback 值
【发布时间】:2018-11-22 20:07:19
【问题描述】:

我正在尝试从 web.xml 中设置的 spring 配置文件中获取一个值。我已经遇到了解决我的问题的question,但问题解决方案的实施似乎不起作用。这是我的源代码:

web.xml:

<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>local-jboss</param-value>
</context-param>

logback.xml:

<insertFromJNDI env-entry-name="java:comp/env/spring.profiles.default" as="spring.profiles.default" />

<appender name="STASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <destination>x.x.x.x:yyyy</destination>
    <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
        <providers>
            <mdc /> <!-- MDC variables on the Thread will be written as JSON fields -->
            <context /> <!-- Outputs entries from logback's context -->
            <version /> <!-- Logstash json format version, the @version field in the output -->
            <logLevel />
            <loggerName />
            <pattern>
                <pattern>
                {
                    "APP": "MyApp",
                    "PROFILE": "${spring.profiles.default}"
                }
                </pattern>
            </pattern>
            <threadName />
            <message />
            <logstashMarkers /> <!-- Useful so we can add extra information for specific log lines as Markers -->
            <arguments /> <!-- or through StructuredArguments -->
            <stackTrace />
        </providers>
    </encoder>
</appender>

有谁知道我如何从 web.xml 中获取值并放入 logback.xml 中?

【问题讨论】:

    标签: java spring logback web.xml


    【解决方案1】:

    第一种解决方案:

    如果您使用的是 spring 3.1+,那么这些上下文参数将作为 env 变量使用,在 logback 中您可以轻松地引用它们,如下所示:

    <springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
            defaultValue="localhost"/>
    

    source 是您的密钥的名称。进一步Documentation

    第二个解决方案: 您也可以使用它,我们将 context-param 定义为 spring 属性,然后在 logback 中引用与上述第一个解决方案相同的内容。

    @SpringBootApplication
    class DemoApp extends SpringBootServletInitializer {
        private ServletContext servletContext;
        public static void main(String[] args){SpringApplication.run(DemoApp.class,args);}
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            builder = builder.properties("test.property:" + servletContext.getInitParameter("test.property"));
            return builder.sources(DemoApp.class);
        }
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            this.servletContext = servletContext;
            super.onStartup(servletContext);
        }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2019-04-06
      • 1970-01-01
      • 2015-02-19
      • 2021-03-20
      • 2011-11-21
      相关资源
      最近更新 更多