Java Code Examples for org.slf4j.ILoggerFactory

The following examples show how to use org.slf4j.ILoggerFactory. These examples are extracted from open source projects. 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
/***
 * 根据 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 2
Source Project: SmartIM   Source File: AbstractSmartClient.java    License: 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 3
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 4
Source Project: twill   Source File: ServiceMain.java    License: 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 5
Source Project: twill   Source File: TwillContainerService.java    License: 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 Project: cougar   Source File: HttpRequestLoggerTest.java    License: 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 7
Source Project: Singularity   Source File: SingularityAbort.java    License: 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 8
@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 9
@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 10
Source Project: buck   Source File: AetherUtil.java    License: 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 11
Source Project: chaosblade-exec-jvm   Source File: LogUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set log level
 *
 * @param level DEBUG
 */
public static void setLogLevel(String level) {
    ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
    if (loggerFactory instanceof LoggerContext) {
        LoggerContext loggerContext = (LoggerContext)loggerFactory;
        Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
        ((ch.qos.logback.classic.Logger)logger).setLevel(Level.toLevel(level));
        return;
    }
    throw new IllegalStateException("not support the log context object");
}
 
Example 12
Source Project: rocketmq-4.3.0   Source File: Slf4jLoggerFactoryTest.java    License: 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 13
Source Project: rocketmq-read   Source File: Slf4jLoggerFactoryTest.java    License: 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 14
Source Project: sofa-ark   Source File: ArkBootRunnerTest.java    License: 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 15
Source Project: super-cloudops   Source File: LogbackLoggingSystem.java    License: 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 16
Source Project: super-cloudops   Source File: LogbackLoggingSystem.java    License: Apache License 2.0 5 votes vote down vote up
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";
}
 
Example 17
Source Project: springboot-shiro-cas-mybatis   Source File: CasLoggerFactory.java    License: MIT License 5 votes vote down vote up
/**
 * 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());
}
 
Example 18
Source Project: spring-boot-data-geode   Source File: LogbackSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Resolves the SLF4J, Logback {@link LoggerContext}.
 *
 * If the {@link LoggerContext} could not be resolve then the returned {@link Optional}
 * will be {@link Optional#empty() empty}.
 *
 * @return an {@link Optional} {@link LoggerContext}.
 * @see ch.qos.logback.classic.LoggerContext
 */
public static Optional<LoggerContext> resolveLoggerContext() {

	ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();

	LoggerContext resolvedLoggerContext = loggerFactory instanceof LoggerContext
		? (LoggerContext) loggerFactory
		: null;

	return Optional.ofNullable(resolvedLoggerContext);
}
 
Example 19
Source Project: twill   Source File: Loggings.java    License: 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 20
@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 21
Source Project: rocketmq   Source File: Slf4jLoggerFactoryTest.java    License: 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 22
Source Project: pulsar   Source File: MessagingServiceShutdownHook.java    License: 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 23
Source Project: nexus-public   Source File: LogbackLogManager.java    License: 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 24
Source Project: flow   Source File: VaadinAppShellInitializerTest.java    License: 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 25
Source Project: dolphin-platform   Source File: DolphinLoggerFactory.java    License: 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 26
public DefaultJsonixContext(ILoggerFactory loggerFactory) {
	this.loggerFactory = new LevelledLoggerFactoryWrapper(loggerFactory) {
		@Override
		protected int getLevel() {
			return DefaultJsonixContext.this.getLogLevel();
		}
	};
}
 
Example 27
@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 28
Source Project: appstatus   Source File: LogbackLoggersManager.java    License: 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 29
Source Project: appstatus   Source File: LogbackLoggersManager.java    License: 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 30
Source Project: rapidoid   Source File: LogbackUtil.java    License: 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);
		}
	}
}