private Set<Class<? extends ILoggerFactory>> lookUpConfiguredLoggerFactory() { final Set<Class<? extends ILoggerFactory>> loggerFactories = new HashSet<>(); final String configuredLoggerFactory = System.getProperty(ENVIRONMENT_VAR_LOGGER_FACTORY); if (StringUtils.isNotBlank(configuredLoggerFactory)) { Util.report("Instructed logger factory to use is " + configuredLoggerFactory); try { final Class clazz = Class.forName(configuredLoggerFactory); loggerFactories.add(clazz); } catch (final Exception e) { Util.report("Could not locate the provided logger factory: " + configuredLoggerFactory + ". Error: " + e.getMessage()); } } return loggerFactories; }
private void flushLogs() { final long millisToWait = 100; LOG.info("Attempting to flush logs and wait {} ...", JavaUtils.durationFromMillis(millisToWait)); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { LoggerContext context = (LoggerContext) loggerFactory; context.stop(); } try { Thread.sleep(millisToWait); } catch (Exception e) { LOG.info("While sleeping for log flush", e); } }
/** * Sets references to the LoggerContext. Must be called whenever logging * configuration changes between {@link #startCaching()} and {@link #stopAndFlush()} */ public static synchronized void initContext() { ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if (!(iLoggerFactory instanceof LoggerContext)) { // Not using LogBack, CacheAppender not applicable LOGGER.debug("Not using LogBack, aborting CacheLogger"); loggerContext = null; return; } else if (!isActive()) { LOGGER.error("initContext() cannot be called while isActive() is false"); return; } loggerContext = (LoggerContext) iLoggerFactory; rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); disposeOfAppenders(); detachRootAppenders(); if (!rootLogger.isAttached(cacheAppender)) { rootLogger.addAppender(cacheAppender); } cacheAppender.setContext(loggerContext); cacheAppender.setName("CacheAppender"); cacheAppender.start(); }
private static boolean setContextAndRoot() { ILoggerFactory ilf = LoggerFactory.getILoggerFactory(); if (!(ilf instanceof LoggerContext)) { // Not using LogBack. // Can't configure the logger, so just exit LOGGER.debug("Not using LogBack, aborting LogBack configuration"); return false; } loggerContext = (LoggerContext) ilf; rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); if (rootLogger == null) { // Shouldn't be possible LOGGER.error("Couldn't find root logger, aborting LogBack configuration"); return false; } return true; }
/** * Set the log level for the requested logger name. * * @param loggerName name of the logger * @param logLevel the log level to set to. * @return the current log level of the given logger. If there is no log level configured for the given logger or * if the logging implementation is not logback, {@code null} will be returned */ @Nullable private String setLogLevel(String loggerName, @Nullable String logLevel) { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (!(loggerFactory instanceof LoggerContext)) { LOG.error("LoggerFactory is not a logback LoggerContext, cannot make the log level change"); return null; } LoggerContext loggerContext = (LoggerContext) loggerFactory; ch.qos.logback.classic.Logger logger = loggerContext.getLogger(loggerName); LogEntry.Level oldLogLevel = logger.getLevel() == null ? null : LogEntry.Level.valueOf(logger.getLevel().toString()); LOG.debug("Log level of {} changed from {} to {}", loggerName, oldLogLevel, logLevel); logger.setLevel(logLevel == null ? null : Level.toLevel(logLevel, Level.ERROR)); return oldLogLevel == null ? null : oldLogLevel.name(); }
public static LoggerContext buildLoggerContext(Map<String, String> props) { if (loggerContext == null) { ILoggerFactory lcObject = LoggerFactory.getILoggerFactory(); if (!(lcObject instanceof LoggerContext)) { throw new LogbackException("Expected LOGBACK binding with SLF4J, but another log system has taken the place: " + lcObject.getClass().getSimpleName()); } loggerContext = (LoggerContext) lcObject; if (props != null) { for (Map.Entry<String, String> entry : props.entrySet()) { loggerContext.putProperty(entry.getKey(), entry.getValue()); } } } return loggerContext; }
private void configureLogger() { // Check if SLF4J is bound to logback in the current environment ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (!(loggerFactory instanceof LoggerContext)) { return; } LoggerContext context = (LoggerContext) loggerFactory; context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try { File twillLogback = new File(Constants.Files.LOGBACK_TEMPLATE); if (twillLogback.exists()) { configurator.doConfigure(twillLogback); } new ContextInitializer(context).autoConfig(); } catch (JoranException e) { throw Throwables.propagate(e); } doConfigure(configurator, getLogConfig(getLoggerLevel(context.getLogger(Logger.ROOT_LOGGER_NAME)))); }
private void init() { BlockingQueue<ILoggingEvent> queue = new LinkedBlockingDeque<ILoggingEvent>(); installClient(queue); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (!(loggerFactory instanceof LoggerContext)) throw new IllegalStateException("This service must be run with Logback Classic"); LoggerContext loggerContext = (LoggerContext) loggerFactory; ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); String appenderName = getClass().getName(); Appender<ILoggingEvent> appender = root.getAppender(appenderName); if (appender != null) throw new IllegalStateException("Appender " + appenderName + " already configured"); RemoteLoggerAppender remoteAppender = new RemoteLoggerAppender(queue, hostname); remoteAppender.setContext(loggerContext); remoteAppender.addFilter(MDCFilter.instance); remoteAppender.start(); root.addAppender(remoteAppender); }
@Before public void init() throws Exception { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); request = mock(HttpServletRequest.class); response = mock(HttpServletResponse.class); registry = new EventLoggingRegistry(); EventLogDefinition eld = new EventLogDefinition(); eld.setRegistry(registry); eld.setLogName("ACCESS-LOG"); eld.register(); loggerFactory = mock(ILoggerFactory.class); oldLoggerFactory = HttpRequestLogger.setLoggerFactory(loggerFactory); eventLog = mock(Logger.class); }
@GetMapping public String init(Model model) { ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if (!(iLoggerFactory instanceof LoggerContext)) { throw new RuntimeException("Logger factory is not a Logback logger context"); } LoggerContext loggerContext = (LoggerContext) iLoggerFactory; List<Logger> loggers = new ArrayList<>(); for (ch.qos.logback.classic.Logger logger : loggerContext.getLoggerList()) { if (logger.getLevel() != null || logger.iteratorForAppenders().hasNext()) { loggers.add(logger); } } model.addAttribute("loggers", loggers); model.addAttribute("levels", LOG_LEVELS); model.addAttribute("hasWritePermission", SecurityUtils.currentUserIsSu()); return "view-logmanager"; }
@PreAuthorize("hasAnyRole('ROLE_SU')") @PostMapping("/loggers/reset") @ResponseStatus(HttpStatus.OK) public void resetLoggers() { ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if (!(iLoggerFactory instanceof LoggerContext)) { throw new RuntimeException("Logger factory is not a Logback logger context"); } LoggerContext loggerContext = (LoggerContext) iLoggerFactory; ContextInitializer ci = new ContextInitializer(loggerContext); URL url = ci.findURLOfDefaultConfigurationFile(true); loggerContext.reset(); try { ci.configureByResource(url); } catch (JoranException e) { LOG.error("Error reloading log configuration", e); throw new RuntimeException(e); } }
public static ServiceLocator initServiceLocator() { DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.setErrorHandler( new DefaultServiceLocator.ErrorHandler() { @Override public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable exception) { throw new RuntimeException( String.format( "Failed to initialize service %s, implemented by %s: %s", type.getName(), impl.getName(), exception.getMessage()), exception); } }); locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); locator.addService(TransporterFactory.class, HttpTransporterFactory.class); locator.addService(TransporterFactory.class, FileTransporterFactory.class); // Use a no-op logger. Leaving this out would introduce a runtime dependency on log4j locator.addService(ILoggerFactory.class, NOPLoggerFactory.class); // Also requires log4j // locator.addService(ILoggerFactory.class, Log4jLoggerFactory.class); return locator; }
private Set<Class<? extends ILoggerFactory>> scanContextForLoggerFactories() { final Set<Class<? extends ILoggerFactory>> loggerFactories; final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN); final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner())); loggerFactories = reflections.getSubTypesOf(ILoggerFactory.class); loggerFactories.remove(this.getClass()); return loggerFactories; }
private static ILoggerFactory getLoggerFactoryBeInstantiated(final Class<? extends ILoggerFactory> loggerFactory) { try { return loggerFactory.newInstance(); } catch (final Exception e) { return null; } }
/** * Instantiates a new Cas logger factory. * Configures the reflection scanning engine to be prepared to scan <code>org.slf4j.impl</code> * in order to find other available factories. */ public CasLoggerFactory() { this.loggerMap = new ConcurrentHashMap<>(); final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN); final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner())); final Set<Class<? extends ILoggerFactory>> subTypesOf = reflections.getSubTypesOf(ILoggerFactory.class); subTypesOf.remove(this.getClass()); if (subTypesOf.size() > 1) { Util.report("Multiple ILoggerFactory bindings are found on the classpath:"); for (final Class<? extends ILoggerFactory> c : subTypesOf) { Util.report("* " + c.getCanonicalName()); } } if (subTypesOf.isEmpty()) { final RuntimeException e = new RuntimeException("No ILoggerFactory could be found on the classpath." + " CAS cannot determine the logging framework." + " Examine the project dependencies and ensure that there is one and only one logging framework available."); Util.report(e.getMessage(), e); throw e; } this.realLoggerFactoryClass = subTypesOf.iterator().next(); Util.report("ILoggerFactory to be used for logging is: " + this.realLoggerFactoryClass.getName()); }
/** * Find the actual {@code Logger} instance that is available on the classpath. * This is usually the logger adapter that is provided by the real logging framework, * such as log4j, etc. The method will scan the runtime to find logger factories that * are of type {@link org.slf4j.ILoggerFactory}. It will remove itself from this list * first and then attempts to locate the next best factory from which real logger instances * can be created. * @param name requested logger name * @return the logger instance created by the logger factory available on the classpath during runtime, or null. */ private Logger getRealLoggerInstance(final String name) { try { final ILoggerFactory factInstance = getLoggerFactoryBeInstantiated(this.realLoggerFactoryClass); if (factInstance == null) { throw new RuntimeException("ILoggerFactory cannot be created from " + this.realLoggerFactoryClass.getName()); } return factInstance.getLogger(name); } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } }
private void configureLogging() { ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); LoggerContext loggerContext = (LoggerContext) iLoggerFactory; loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); try { configurator.doConfigure(getClass().getResourceAsStream("/logback.xml")); logger.info("Logging has been {0} configured", "correctly"); } catch (JoranException e) { logger.error(e); } }
private void initLogback() throws IOException { ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); LoggerContext loggerContext = (LoggerContext) iLoggerFactory; loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); try { configurator.doConfigure(getClass().getResourceAsStream("/logback.xml")); } catch (JoranException e) { throw new IOException(e.getMessage(), e); } }
/** * Loads the logging configuration from the specified stream. * * @param stream * The stream that contains the logging configuration document. * @param delayedLogging */ private static void loadLoggingConfiguration(final InputStream stream, final ArrayList<String> delayedLogging) { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { configureLogback((LoggerContext) loggerFactory, stream); } else { delayedLogging.add((EELFResourceManager.format(EELFMsgs.UNSUPPORTED_LOGGING_FRAMEWORK))); } }
private void configureLogger() throws MalformedURLException, JoranException { // Check if SLF4J is bound to logback in the current environment ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (!(loggerFactory instanceof LoggerContext)) { return; } LoggerContext context = (LoggerContext) loggerFactory; ContextInitializer contextInitializer = new ContextInitializer(context); URL url = contextInitializer.findURLOfDefaultConfigurationFile(false); if (url == null) { // The logger context was not initialized using configuration file, initialize it with the logback template. File twillLogback = new File(Constants.Files.RUNTIME_CONFIG_JAR, Constants.Files.LOGBACK_TEMPLATE); if (twillLogback.exists()) { contextInitializer.configureByResource(twillLogback.toURI().toURL()); } } // Attach the KafkaAppender to the root logger KafkaAppender kafkaAppender = new KafkaAppender(); kafkaAppender.setName("KAFKA"); kafkaAppender.setTopic(Constants.LOG_TOPIC); kafkaAppender.setHostname(getHostname()); // The Kafka ZK Connection shouldn't be null as this method only get called if log collection is enabled kafkaAppender.setZookeeper(getTwillRuntimeSpecification().getKafkaZKConnect()); String runnableName = getRunnableName(); if (runnableName != null) { kafkaAppender.setRunnableName(runnableName); } kafkaAppender.setContext(context); kafkaAppender.start(); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(kafkaAppender); }
public static void forceFlush() { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { Appender<ILoggingEvent> appender = ((LoggerContext) loggerFactory).getLogger(Logger.ROOT_LOGGER_NAME) .getAppender("KAFKA"); if (appender != null && appender instanceof KafkaAppender) { ((KafkaAppender) appender).forceFlush(); } } }
public static void immediateFlushBufferedLogs() { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory.getClass().getName().equals(LogbackLoggerContextClassName)) { // Use reflection to force the flush on the logger try { Class<?> logbackLoggerContextClass = Class.forName(LogbackLoggerContextClassName); Method stop = logbackLoggerContextClass.getMethod("stop"); stop.invoke(loggerFactory); } catch (Throwable t) { LOG.info("Failed to flush logs", t); } } }
private LoggerContext getLoggerContext() { ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); Assert.isInstanceOf(LoggerContext.class, factory, String.format( "LoggerFactory is not a Logback LoggerContext but Logback is on " + "the classpath. Either remove Logback or the competing " + "implementation (%s loaded from %s). If you are using " + "WebLogic you will need to add 'org.slf4j' to " + "prefer-application-packages in WEB-INF/weblogic.xml", factory.getClass(), getLocation(factory))); return (LoggerContext) factory; }
private Object getLocation(ILoggerFactory factory) { try { ProtectionDomain protectionDomain = factory.getClass().getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); if (codeSource != null) { return codeSource.getLocation(); } } catch (SecurityException ex) { // Unable to determine location } return "unknown location"; }
@Test public void testBasicConfigLocation() throws Exception { this.loggingSystem.beforeInitialize(); ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); LoggerContext context = (LoggerContext) factory; Logger root = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); assertThat(root.getAppender("CONSOLE")).isNotNull(); }
/** * Returns the current logger-context. */ @VisibleForTesting static LoggerContext loggerContext() { ILoggerFactory factory = LoggerFactory.getILoggerFactory(); if (factory instanceof LoggerContext) { return (LoggerContext) factory; } // Pax-Logging registers a custom implementation of ILoggerFactory which hides logback; as a workaround // we set org.ops4j.pax.logging.StaticLogbackContext=true in system.properties and access it statically return (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory(); }
public ILoggerFactory getLoggerFactory() { if (!initialized) { return defaultLoggerContext; } if (contextSelectorBinder.getContextSelector() == null) { throw new IllegalStateException( "contextSelector cannot be null. See also " + NULL_CS_URL); } return contextSelectorBinder.getContextSelector().getLoggerContext(); }
private LoggerContext getLoggerContext() { ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); Assert.isInstanceOf(LoggerContext.class, factory, String.format( "LoggerFactory is not a Logback LoggerContext but Logback is on " + "the classpath. Either remove Logback or the competing " + "implementation (%s loaded from %s). If you are using " + "Weblogic you will need to add 'org.slf4j' to " + "prefer-application-packages in WEB-INF/weblogic.xml", factory.getClass(), getLocation(factory))); return (LoggerContext) factory; }
@Test public void testBasicConfigLocation() throws Exception { this.loggingSystem.beforeInitialize(); ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); LoggerContext context = (LoggerContext) factory; Logger root = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); assertNotNull(root.getAppender("CONSOLE")); }
void reloadLogback() { // reload the logback configuration, without introducing a dependency on // logback ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if (iLoggerFactory.getClass().getName().equals("ch.qos.logback.classic.LoggerContext")) { // original code: // LoggerContext // loggerContext=(LoggerContext)LoggerFactory.getILoggerFactory() // ContextInitializer ci = new // ContextInitializer(loggerContext); // URL url = ci.findURLOfDefaultConfigurationFile(true); // loggerContext.reset(); // ci.configureByResource(url); try { Class<?> cContextInitializer = Class.forName("ch.qos.logback.classic.util.ContextInitializer"); Class<?> cLoggerContext = Class.forName("ch.qos.logback.classic.LoggerContext"); Object loggerContext = iLoggerFactory; Object ci = cContextInitializer.getConstructor(cLoggerContext).newInstance(loggerContext); Object url1 = cContextInitializer.getMethod("findURLOfDefaultConfigurationFile", boolean.class) .invoke(ci, true); cLoggerContext.getMethod("reset").invoke(loggerContext); cContextInitializer.getMethod("configureByResource", URL.class).invoke(ci, url1); } catch (Throwable t) { log.error("Error updating logback configuration, continuing...", t); } } }
public static final MetasfreshIssueAppender get() { final ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { final LoggerContext loggerContext = (LoggerContext)loggerFactory; final Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); return (MetasfreshIssueAppender)rootLogger.getAppender(NAME); } return null; }