org.slf4j.ILoggerFactory Java Examples

The following examples show how to use org.slf4j.ILoggerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AetherUtil.java    From buck with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: MultiAppLoggerSpaceManager.java    From sofa-common-tools with Apache License 2.0 6 votes vote down vote up
/***
 * 根据 spaceId 在日志空间里移除指定 spaceName 的 ILoggerFactory
 *
 * @param spaceId 指定的日志空间名称
 * @return 被移除的 ILoggerFactory;不存在指定的 spaceName,则返回 null
 */
public static ILoggerFactory removeILoggerFactoryBySpaceId(SpaceId spaceId) {
    if (spaceId == null) {
        return null;
    }
    SpaceInfo spaceInfo = SPACES_MAP.get(spaceId);
    if (isSpaceILoggerFactoryExisted(spaceId)) {
        AbstractLoggerSpaceFactory iLoggeriFactory = spaceInfo.getAbstractLoggerSpaceFactory();
        spaceInfo.setAbstractLoggerSpaceFactory(null);
        Logger rootLogger = iLoggeriFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.warn("Log Space Name[" + spaceId.toString()
                        + "] is Removed from Current Log Space Manager!");
        return iLoggeriFactory;
    }
    return null;
}
 
Example #3
Source File: LogManagerController.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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) {
    throw new RuntimeException("Error reloading log configuration", e);
  }
}
 
Example #4
Source File: LogManagerController.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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";
}
 
Example #5
Source File: TwillContainerService.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #6
Source File: SingularityAbort.java    From Singularity with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #7
Source File: HttpRequestLoggerTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: AbstractLoggingIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
private void configureLogging() {

		System.setProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY, getTestLogLevel().toString());

		ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();

		assertThat(loggerFactory).isInstanceOf(LoggerContext.class);

		LoggerContext loggerContext = (LoggerContext) loggerFactory;

		try {
			new ContextInitializer(loggerContext).autoConfig();
		}
		catch (Exception cause) {
			throw newIllegalStateException("Failed to configure and initialize SLF4J/Logback logging context", cause);
		}
	}
 
Example #9
Source File: ServiceMain.java    From twill with Apache License 2.0 6 votes vote down vote up
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());
    }
  }

  KafkaAppender kafkaAppender = getKafkaAppender(context);
  kafkaAppender.start();

  // Attach the KafkaAppender to the root logger
  context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(kafkaAppender);
}
 
Example #10
Source File: AbstractSmartClient.java    From SmartIM with Apache License 2.0 6 votes vote down vote up
@Override
public void setWorkDir(File path) {
    if (path == null) {
        throw new IllegalArgumentException("Work directory is null");
    }
    if (!path.exists()) {
        path.mkdirs();
    }
    this.workDir = path;
    System.setProperty("log.home", path.getAbsolutePath());
    ILoggerFactory fac = LoggerFactory.getILoggerFactory();
    if (fac != null && fac instanceof LoggerContext) {
        LoggerContext lc = (LoggerContext) fac;
        lc.getStatusManager().clear();
        lc.reset();
        lc.putProperty("log.home", path.getAbsolutePath());
        ContextInitializer ci = new ContextInitializer(lc);
        try {
            ci.autoConfig();
        } catch (JoranException e) {
            e.printStackTrace();
        }
    }
}
 
Example #11
Source File: LogbackLogManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #12
Source File: JsonixPlugin.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onActivated(Options opts) throws BadCommandLineException {
	final ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
	if (iLoggerFactory instanceof NOPLoggerFactory) {
		System.err
				.println("You seem to be using the NOP provider of the SLF4j logging facade. "
						+ "With this configuration, log messages will be completely suppressed. "
						+ "Please consider adding a SLF4j provider (for instance slf4j-simple) to enable logging.");
	}
}
 
Example #13
Source File: MessagingServiceShutdownHook.java    From pulsar with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example #14
Source File: Slf4jLoggerFactoryTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Before
public void initLogback() throws JoranException {
    InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
    System.setProperty("loggingDir", loggingDir);
    ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
    JoranConfigurator joranConfigurator = new JoranConfigurator();
    joranConfigurator.setContext((Context) iLoggerFactory);
    URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
    if (logbackConfigFile == null) {
        throw new RuntimeException("can't find logback_test.xml");
    } else {
        joranConfigurator.doConfigure(logbackConfigFile);
    }
}
 
Example #15
Source File: SpringBootWebApplication.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
	super.onStartup(servletContext);
	ILoggerFactory loggerFactory = StaticLoggerBinder.getSingleton().getLoggerFactory();
	if (loggerFactory instanceof LoggerContext)
	{
		LoggerContext loggerContext = (LoggerContext) loggerFactory;
		loggerContext.setPackagingDataEnabled(false);
		log.debug("Disabling logback packaging data");
	}
}
 
Example #16
Source File: Loggings.java    From twill with Apache License 2.0 5 votes vote down vote up
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();
    }
  }
}
 
Example #17
Source File: LogbackLoggingSystem.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: Slf4jLoggerFactoryTest.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
@Before
public void initLogback() throws JoranException {
    InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
    System.setProperty("loggingDir", loggingDir);
    ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
    JoranConfigurator joranConfigurator = new JoranConfigurator();
    joranConfigurator.setContext((Context) iLoggerFactory);
    URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
    if (logbackConfigFile == null) {
        throw new RuntimeException("can't find logback_test.xml");
    } else {
        joranConfigurator.doConfigure(logbackConfigFile);
    }
}
 
Example #19
Source File: ArkBootRunnerTest.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
/**
 * issue#234
 */
@Test
public void testLogClassCastBug() {
    Throwable throwable = null;
    try {
        ILoggerFactory iLoggerFactory = (ILoggerFactory) this.getClass().getClassLoader()
            .loadClass("org.apache.logging.slf4j.Log4jLoggerFactory").newInstance();
    } catch (Throwable t) {
        throwable = t;
    }
    Assert.assertNull(throwable);
}
 
Example #20
Source File: VaadinAppShellInitializerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private ConcurrentMap<String, Logger> clearIlogger() throws Exception {
    ILoggerFactory ilogger = LoggerFactory.getILoggerFactory();
    Field field = SimpleLoggerFactory.class.getDeclaredField("loggerMap");
    field.setAccessible(true);
    ConcurrentMap<String, Logger> map = (ConcurrentMap<String, Logger>) field
            .get(ilogger);
    map.clear();
    return map;
}
 
Example #21
Source File: DolphinLoggerFactory.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
public static void applyConfiguration(final DolphinLoggerConfiguration configuration) {
    final ILoggerFactory factory = LoggerFactory.getILoggerFactory();
    Objects.requireNonNull(factory);
    if(factory instanceof DolphinLoggerFactory) {
        ((DolphinLoggerFactory) factory).configure(configuration);
    } else {
        throw new IllegalStateException(LoggerFactory.class + " is not of type " + DolphinLoggerFactory.class);
    }
}
 
Example #22
Source File: DefaultJsonixContext.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public DefaultJsonixContext(ILoggerFactory loggerFactory) {
	this.loggerFactory = new LevelledLoggerFactoryWrapper(loggerFactory) {
		@Override
		protected int getLevel() {
			return DefaultJsonixContext.this.getLogLevel();
		}
	};
}
 
Example #23
Source File: Slf4jLoggerFactoryTest.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
@Before
public void initLogback() throws JoranException {
    InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
    System.setProperty("loggingDir", loggingDir);
    ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
    JoranConfigurator joranConfigurator = new JoranConfigurator();
    joranConfigurator.setContext((Context) iLoggerFactory);
    URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
    if (logbackConfigFile == null) {
        throw new RuntimeException("can't find logback_test.xml");
    } else {
        joranConfigurator.doConfigure(logbackConfigFile);
    }
}
 
Example #24
Source File: LogbackLoggersManager.java    From appstatus with Apache License 2.0 5 votes vote down vote up
public List<LoggerConfig> getLoggers() {
	List<LoggerConfig> loggers = new ArrayList<LoggerConfig>();
	ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
	if (loggerFactory instanceof LoggerContext) {
		LoggerContext context = (LoggerContext) loggerFactory;
		for (ch.qos.logback.classic.Logger l : context.getLoggerList()) {
			loggers.add(new LoggerConfig(l.getName(), l.getEffectiveLevel().toString()));
		}
	}
	return loggers;
}
 
Example #25
Source File: LogbackLoggersManager.java    From appstatus with Apache License 2.0 5 votes vote down vote up
public void update(LoggerConfig logger2Change) {
	ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
	if (loggerFactory instanceof LoggerContext) {
		LoggerContext context = (LoggerContext) loggerFactory;
		context.getLogger(logger2Change.getName()).setLevel(Level.valueOf(logger2Change.getLevel()));
	}
}
 
Example #26
Source File: LogbackUtil.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void setupLogger() {
	ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();

	if (loggerFactory instanceof LoggerContext) {
		LoggerContext lc = (LoggerContext) loggerFactory;

		if (U.isEmpty(lc.getCopyOfPropertyMap())) {
			Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
			root.setLevel(Level.INFO);
		}
	}
}
 
Example #27
Source File: SingularityExecutorRunner.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private static void stopLog() {
  ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
  if (loggerFactory instanceof LoggerContext) {
    LoggerContext context = (LoggerContext) loggerFactory;
    context.stop();
  }
}
 
Example #28
Source File: ChameleonInstanceHolder.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Fixes the Chameleon logging configuration to write the logs in the logs/wisdom.log file instead of chameleon.log
 * file.
 *
 * @param basedir the base directory of the chameleon
 */
public static void fixLoggingSystem(File basedir) {
    ILoggerFactory factory = LoggerFactory.getILoggerFactory();
    if (factory instanceof LoggerContext) {
        // We know that we are using logback from here.
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        ch.qos.logback.classic.Logger logbackLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
        if (logbackLogger == null) {
            return;
        }

        Iterator<Appender<ILoggingEvent>> iterator = logbackLogger.iteratorForAppenders();
        while (iterator.hasNext()) {
            Appender<ILoggingEvent> appender = iterator.next();

            if (appender instanceof AsyncAppender) {
                appender = ((AsyncAppender) appender).getAppender("FILE");
            }

            if (appender instanceof RollingFileAppender) {
                RollingFileAppender<ILoggingEvent> fileAppender =
                        (RollingFileAppender<ILoggingEvent>) appender;
                String file = new File(basedir, "logs/wisdom.log").getAbsolutePath();
                fileAppender.stop();
                // Remove the created log directory.
                // We do that afterwards because on Windows the file cannot be deleted while we still have a logger
                // using it.
                FileUtils.deleteQuietly(new File("logs"));
                fileAppender.setFile(file);
                fileAppender.setContext(lc);
                fileAppender.start();
            }
        }
    }
}
 
Example #29
Source File: LifecycleHelper.java    From Baragon with Apache License 2.0 5 votes vote down vote up
private void flushLogs() {
  final long millisToWait = 100;

  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);
  }
}
 
Example #30
Source File: Slf4jClassloadingTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotUseNopLoggerFactory() {
  ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();

  // verify that a SLF4J backend is used which is not the NOP logger
  assertFalse("Should not use NOPLoggerFactory", loggerFactory instanceof NOPLoggerFactory);

  // should either use slf4j-jdk14 or slf4j-jboss-logmanager
  String loggerFactoryClassName = loggerFactory.getClass().getCanonicalName();
  assertTrue("Should use slf4j-jdk14 or slf4j-jboss-logmanager",
      JDK14_LOGGER_FACTORY.equals(loggerFactoryClassName) || JBOSS_SLF4J_LOGGER_FACTORY.equals(loggerFactoryClassName));
}