1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.selector.servlet;
15
16 import static ch.qos.logback.classic.ClassicConstants.JNDI_CONTEXT_NAME;
17
18 import javax.naming.Context;
19 import javax.naming.NamingException;
20 import jakarta.servlet.ServletContextEvent;
21 import jakarta.servlet.ServletContextListener;
22
23 import org.slf4j.Logger;
24
25 import ch.qos.logback.classic.LoggerContext;
26 import ch.qos.logback.classic.selector.ContextSelector;
27 import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
28 import ch.qos.logback.core.util.JNDIUtil;
29
30 public class ContextDetachingSCL implements ServletContextListener {
31
32 public void contextInitialized(ServletContextEvent arg0) {
33
34 }
35
36 public void contextDestroyed(ServletContextEvent servletContextEvent) {
37 String loggerContextName = null;
38
39 try {
40 Context ctx = JNDIUtil.getInitialContext();
41 loggerContextName = (String) JNDIUtil.lookupString(ctx, JNDI_CONTEXT_NAME);
42 } catch (NamingException ne) {
43 }
44
45 if (loggerContextName != null) {
46 System.out.println("About to detach context named " + loggerContextName);
47
48 ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
49 if (selector == null) {
50 System.out.println("Selector is null, cannot detach context. Skipping.");
51 return;
52 }
53 LoggerContext context = selector.getLoggerContext(loggerContextName);
54 if (context != null) {
55 Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME);
56 logger.warn("Stopping logger context " + loggerContextName);
57 selector.detachLoggerContext(loggerContextName);
58
59 context.stop();
60 } else {
61 System.out.println("No context named " + loggerContextName + " was found.");
62 }
63 }
64 }
65
66 }