Java ContextJNDISelector-class And Method Code Example


The ContextJNDISelector class is used to configure logback via JNDI, allowing different parts of a web application to have different logging configurations.

Here's an example of how you could use the ContextJNDISelector class to configure logback via JNDI in a web application:

  1. Create a logback.xml file in the WEB-INF directory of your web application, where you can specify your logback configuration.
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>/path/to/application.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="FILE" />
    </root>
</configuration>
  1. Create a logback-jndi.xml file in the WEB-INF directory of your web application, where you can specify the JNDI name for your logback configuration.
<included>
    <jndi name="java:comp/env/logback/configuration-file" value="/WEB-INF/logback.xml" />
</included>
  1. Add the logback-jndi.xml file as an to the logback-access servlet in the web.xml file of your web application.
<servlet>
    <servlet-name>logback-access</servlet-name>
    <servlet-class>ch.qos.logback.access.servlet.LogbackServlet</servlet-class>
    <init-param>
        <param-name>configuratorClass</param-name>
        <param-value>ch.qos.logback.classic.selector.servlet.ContextJNDISelector</param-value>
    </init-param>
    <init-param>
        <param-name>jndiConfiguratorContextName</param-name>
        <param-value>logback-jndi</param-value>
    </init-param>
    <init-param>
        <param-name>jndiConfiguratorFile</param-name>
        <param-value>/WEB-INF/logback-jndi.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

This way, when the servlet container starts, logback will be configured via JNDI and the logging configuration file will be loaded from the specified JNDI name.

You need to add logback classic library in the classpath to use this example.

This example is intended for use in web application, and the logback-access