类org.slf4j.ILoggerFactory源码实例Demo

下面列出了怎么用org.slf4j.ILoggerFactory的API类实例代码及写法,或者点击链接到github查看源代码。

/***
 * 根据 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;
}
 
源代码2 项目: SmartIM   文件: AbstractSmartClient.java
@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();
        }
    }
}
 
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);
		}
	}
 
源代码4 项目: twill   文件: ServiceMain.java
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);
}
 
源代码5 项目: twill   文件: TwillContainerService.java
/**
 * 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();
}
 
源代码6 项目: cougar   文件: HttpRequestLoggerTest.java
@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);
}
 
源代码7 项目: Singularity   文件: SingularityAbort.java
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);
  }
}
 
源代码8 项目: molgenis   文件: LogManagerController.java
@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";
}
 
源代码9 项目: molgenis   文件: LogManagerController.java
@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);
  }
}
 
源代码10 项目: buck   文件: AetherUtil.java
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;
}
 
源代码11 项目: chaosblade-exec-jvm   文件: LogUtil.java
/**
 * 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");
}
 
源代码12 项目: rocketmq-4.3.0   文件: Slf4jLoggerFactoryTest.java
@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);
    }
}
 
源代码13 项目: rocketmq-read   文件: Slf4jLoggerFactoryTest.java
@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);
    }
}
 
源代码14 项目: sofa-ark   文件: ArkBootRunnerTest.java
/**
 * 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);
}
 
源代码15 项目: super-cloudops   文件: LogbackLoggingSystem.java
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;
}
 
源代码16 项目: super-cloudops   文件: LogbackLoggingSystem.java
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";
}
 
/**
 * 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());
}
 
源代码18 项目: spring-boot-data-geode   文件: LogbackSupport.java
/**
 * 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);
}
 
源代码19 项目: twill   文件: Loggings.java
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();
    }
  }
}
 
源代码20 项目: runelite   文件: SpringBootWebApplication.java
@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");
	}
}
 
源代码21 项目: rocketmq   文件: Slf4jLoggerFactoryTest.java
@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);
    }
}
 
源代码22 项目: pulsar   文件: MessagingServiceShutdownHook.java
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);
        }
    }
}
 
源代码23 项目: nexus-public   文件: LogbackLogManager.java
/**
 * 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();
}
 
源代码24 项目: flow   文件: VaadinAppShellInitializerTest.java
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;
}
 
源代码25 项目: dolphin-platform   文件: DolphinLoggerFactory.java
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);
    }
}
 
public DefaultJsonixContext(ILoggerFactory loggerFactory) {
	this.loggerFactory = new LevelledLoggerFactoryWrapper(loggerFactory) {
		@Override
		protected int getLevel() {
			return DefaultJsonixContext.this.getLogLevel();
		}
	};
}
 
源代码27 项目: jsonix-schema-compiler   文件: JsonixPlugin.java
@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.");
	}
}
 
源代码28 项目: appstatus   文件: LogbackLoggersManager.java
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;
}
 
源代码29 项目: appstatus   文件: LogbackLoggersManager.java
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()));
	}
}
 
源代码30 项目: rapidoid   文件: LogbackUtil.java
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);
		}
	}
}