logback value from web.xml in file appender

2019-09-21 15:35发布

问题:

I am developing Java web application for Glassfish server. I have problem with setting path for File appender. I would like to use variable which is defined in web.xml.

Web.xml:

<context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>app.myApp-client.home</param-value>
</context-param>

Logback.xml (in src/main/resurces)

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">        
    <file>${app.myApp-client.home}/WEB-INF/app-log/client.log</file>        
    <encoder>
        <pattern>%date %level [%file:%line] %msg%n</pattern>
    </encoder>
</appender>

After deploy my application on Glassfish log file with name

/app.myApp-client.home_IS_UNDEFINED/WEB-INF/app-log/client.log

is created. Why parameter app.myApp-client.home is undefined? Is there any better option for put application path to file appender?

Thank you.

回答1:

It is possible to set variables to values obtained via JNDI. In your case, you would write:

  <insertFromJNDI env-entry-name="java:comp/env/webAppRootKey" as="webAppRootKey" />

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">        
    <file>${webAppRootKey}/WEB-INF/app-log/client.log</file>        
    <encoder>
      <pattern>%date %level [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>

The above should work nicely. In addition, you might also find it useful to set a default value for ${webAppRootKey}.



回答2:

You are trying to reference the value instead of the param name...

Try it like this:

<file>${webAppRootKey}/WEB-INF/app-log/client.log</file> 

But I guess this will give you /app.myApp-client.home/WEB-INF/app-log/client.log and that is also not what you expected? :)



回答3:

There is some info about configuring logback via JNDI here: http://logback.qos.ch/manual/loggingSeparation.html

Also there is discussion of ways to do it here: http://logback.10977.n7.nabble.com/Externalized-Logback-configuration-for-web-applications-td3629.html