public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); ContextJNDISelector sel = null; if (selector instanceof ContextJNDISelector) { sel = (ContextJNDISelector)selector; sel.setLocalContext(lc); } try { chain.doFilter(request, response); } finally { if (sel != null) { sel.removeLocalContext(); } } }
/** * Return the name of the current context name as found in the logging event. */ public String getDiscriminatingValue(ILoggingEvent event) { ContextSelector selector = ContextSelectorStaticBinder.getSingleton() .getContextSelector(); if (selector == null) { return defaultValue; } LoggerContext lc = selector.getLoggerContext(); if (lc == null) { return defaultValue; } return lc.getName(); }
public static ContextSelector getContextSelector() { if (useLogback) { ContextSelectorStaticBinder contextSelectorBinder = ContextSelectorStaticBinder.getSingleton(); ContextSelector selector = contextSelectorBinder.getContextSelector(); if (selector == null) { if (DEBUG) { System.err.println("Context selector was null, creating default context"); } LoggerContext defaultLoggerContext = new LoggerContext(); defaultLoggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME); try { contextSelectorBinder.init(defaultLoggerContext, null); selector = contextSelectorBinder.getContextSelector(); } catch (Exception e) { e.printStackTrace(); } } //System.out.printf("Context selector: %s%n", selector.getClass().getName()); return selector; } return null; }
public void contextDestroyed(ServletContextEvent servletContextEvent) { String loggerContextName = null; try { Context ctx = JNDIUtil.getInitialContext(); loggerContextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME); } catch (NamingException ne) { } if (loggerContextName != null) { System.out.println("About to detach context named " + loggerContextName); ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); if(selector == null) { System.out.println("Selector is null, cannot detach context. Skipping."); return; } LoggerContext context = selector.getLoggerContext(loggerContextName); if (context != null) { Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME); logger.warn("Stopping logger context " + loggerContextName); selector.detachLoggerContext(loggerContextName); // when the web-app is destroyed, its logger context should be stopped context.stop(); } else { System.out.println("No context named " + loggerContextName + " was found."); } } }
@Test public void testCreateContext() { MockInitialContext mic = MockInitialContextFactory.getContext(); mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "tata"); LoggerFactory.getLogger(ContextDetachingSCLTest.class); ContextJNDISelector selector = (ContextJNDISelector)ContextSelectorStaticBinder.getSingleton().getContextSelector(); Context context = selector.getLoggerContext(); assertEquals("tata", context.getName()); System.out.println(selector.getContextNames()); assertEquals(2, selector.getCount()); }
@Test public void defaultContext() { MockInitialContext mic = MockInitialContextFactory.getContext(); mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, null); ContextJNDISelector selector = (ContextJNDISelector)ContextSelectorStaticBinder.getSingleton().getContextSelector(); Context context = selector.getLoggerContext(); assertEquals("default", context.getName()); }
@Test public void testDetachWithMissingContext() { MockInitialContext mic = MockInitialContextFactory.getContext(); mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "tata"); ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); assertEquals("tata", selector.getLoggerContext().getName()); mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "titi"); assertEquals("titi", selector.getLoggerContext().getName()); contextDetachingSCL.contextDestroyed(null); assertEquals(2, selector.getCount()); }
public static void bind() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); if (selector instanceof LogbackContextSelector) { tlsLoggingContext.set(context); } }
@Override public void contextDestroyed(ServletContextEvent sce) { configWatchDog.interrupt(); ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); String contextId = HttpUtils.getContextId(sce.getServletContext()); selector.detachLoggerContext(contextId); configWatchDog.loggerContext.stop(); }
@Test public void testGetExistingContext() { ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); Context context = selector.getLoggerContext(); assertEquals("toto", context.getName()); }
@Test public void testDetach() { ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); contextDetachingSCL.contextDestroyed(null); assertEquals(0, selector.getCount()); }
@Override @SuppressWarnings({ CompilerWarnings.UNCHECKED }) public void environmentPrepared(ConfigurableEnvironment env) { this.buildInitializer(DefaultLoggingInitializer::new).initialize(env); this.loggerContext = ContextSelectorStaticBinder.getSingleton().getContextSelector().getDefaultLoggerContext(); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); this.loggerContext.stop(); this.loggerContext.reset(); LevelChangePropagator lvlChangePropagator = new LevelChangePropagator(); lvlChangePropagator.setContext(this.loggerContext); lvlChangePropagator.setResetJUL(true); this.loggerContext.addListener(lvlChangePropagator); this.loggerContext.putObject(SdcctApplication.BEAN_NAME, this.app); this.buildConversionRule(MessageMarkerConverter.WORD, MessageMarkerConverter.class); this.buildConversionRule(PriorityColorCompositeConverter.WORD, PriorityColorCompositeConverter.class); this.buildConversionRule(RootCauseThrowableProxyConverter.WORD, RootCauseThrowableProxyConverter.class); this.buildConversionRule(ThreadSectionConverter.WORD, ThreadSectionConverter.class); this.buildConversionRule(TxMdcConverter.WORD, TxMdcConverter.class); this.buildAppender(new ConsoleAppender<>(), AppenderType.CONSOLE, this.buildPatternLayoutEncoder(CONSOLE_APPENDER_PATTERN), true); this.buildFileAppender(AppenderType.FILE, this.buildPatternLayoutEncoder(FILE_APPENDER_PATTERN), new File( (this.logFileDir = this.app.getLogFileDirectory()), (this.app.getLogFileName() + FilenameUtils.EXTENSION_SEPARATOR + SdcctFileNameExtensions.LOG))); this.buildCachingAppender(AppenderType.LOGSTASH_FILE); this.buildLogger(org.slf4j.Logger.ROOT_LOGGER_NAME, Level.WARN, true, this.appenders.values()); PropertySourceUtils.getSubProperties(env.getPropertySources(), SdcctPropertyNames.LOGGING_LOGGER_PREFIX).forEach((loggerName, loggerPropValue) -> { String[] loggerPropValueParts = StringUtils.split(((String) loggerPropValue), SdcctStringUtils.COLON, 2); Level loggerLvl = Level.toLevel(loggerPropValueParts[0].toUpperCase(), null); if (loggerLvl == null) { throw new ApplicationContextException( String.format("Unknown application (name=%s) logger (name=%s) level: %s", this.app.getName(), loggerName, loggerPropValueParts[0])); } this.buildLogger(loggerName, loggerLvl, false, ((loggerPropValueParts.length == 2) ? Stream.of(org.springframework.util.StringUtils.commaDelimitedListToStringArray(loggerPropValueParts[1])).map(loggerAppenderName -> { AppenderType loggerAppenderType = SdcctEnumUtils.findById(AppenderType.class, loggerAppenderName); if (!this.appenders.containsKey(loggerAppenderType)) { throw new ApplicationContextException(String.format("Unknown application (name=%s) logger (name=%s) appender type (name=%s).", this.app.getName(), loggerName, loggerAppenderName)); } return this.appenders.get(loggerAppenderType); }).collect(Collectors.toList()) : this.appenders.values())); }); StatusManager statusManager = this.loggerContext.getStatusManager(); StatusUtil statusUtil = new StatusUtil(statusManager); long lastResetTime = statusUtil.timeOfLastReset(); if (statusUtil.getHighestLevel(lastResetTime) >= Status.WARN) { StatusPrinter.print(statusManager, lastResetTime); throw new ApplicationContextException(String.format("Unable to initialize application (name=%s) logging.", this.app.getName())); } this.loggerContext.getLogger(LoggingInitializerRunListener.class).info(String.format("Application (name=%s) logging initialized.", this.app.getName())); }
@Override public void started() { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); this.app.addListeners(this); LoggerContext loggerContext = ContextSelectorStaticBinder.getSingleton().getContextSelector().getLoggerContext(); loggerContext.stop(); loggerContext.reset(); String appName = this.app.getName(), consoleTty = System.getProperty(CrigttProperties.LOGGING_CONSOLE_TTY_NAME); CrigttLoggingInitializer loggingInit = buildComponent(CrigttLoggingInitializer.class, DefaultLoggingInitializer::new, this.app); loggerContext.setName(appName); loggerContext .putProperty(CrigttProperties.LOGGING_CONSOLE_TTY_NAME, ((consoleTty != null) ? consoleTty : Boolean.toString((System.console() != null)))); loggerContext.putProperty(CrigttProperties.LOGGING_FILE_DIR_NAME, loggingInit.buildLogDirectory().getPath()); loggerContext.putProperty(CrigttProperties.LOGGING_FILE_NAME_NAME, loggingInit.buildLogFileName()); String configFileUrlPath = LOGBACK_CONFIG_FILE_URL_PATH_PREFIX + appName + FilenameUtils.EXTENSION_SEPARATOR + CrigttFileExtensions.GROOVY; URL configFileUrl; try { GafferConfigurator configurator = new GafferConfigurator(loggerContext); loggerContext.putObject(ClassicConstants.GAFFER_CONFIGURATOR_FQCN, configurator); configurator.run(IOUtils.toString((configFileUrl = ResourceUtils.getURL(configFileUrlPath)))); } catch (IOException e) { throw new ApplicationContextException(String.format("Unable to process Logback configuration file (path=%s).", configFileUrlPath), e); } StatusManager statusManager = loggerContext.getStatusManager(); StatusUtil statusUtil = new StatusUtil(statusManager); long lastResetTime = statusUtil.timeOfLastReset(); if (statusUtil.getHighestLevel(lastResetTime) >= Status.WARN) { StatusPrinter.print(statusManager, lastResetTime); throw new ApplicationContextException(String.format("Unable to initialize Logback using configuration file (path=%s).", configFileUrlPath)); } loggingInit.postProcessContext(loggerContext); loggerContext.getLogger(LoggingApplicationRunListener.class).info( String.format("Logging initialized (initializerClass=%s, configFileUrl=%s).", loggingInit.getClass().getName(), configFileUrl.toString())); }