ch.qos.logback.classic.util.ContextInitializer Java Examples

The following examples show how to use ch.qos.logback.classic.util.ContextInitializer. 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: LogbackLoggerSpaceFactory.java    From sofa-common-tools with Apache License 2.0 6 votes vote down vote up
private void initialize(boolean willReInitialize) {
    AssertUtil.notNull(loggerContext);
    AssertUtil.notNull(properties);
    AssertUtil.notNull(confFile);

    for (Map.Entry entry : properties.entrySet()) {
        loggerContext.putProperty((String) entry.getKey(), (String) entry.getValue());
    }

    if (confFile != null && !willReInitialize) {
        try {
            new ContextInitializer(loggerContext).configureByResource(confFile);
        } catch (JoranException e) {
            throw new IllegalStateException("Logback loggerSpaceFactory build error", e);
        }
    } else {
        BasicConfigurator basicConfigurator = new BasicConfigurator();
        basicConfigurator.setContext(loggerContext);
        basicConfigurator.configure(loggerContext);
    }
}
 
Example #2
Source File: LogbackTest.java    From sofa-common-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndependentSpaceLogback() throws JoranException {

    URL url1 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/logback/log-conf.xml");
    LoggerContext loggerContext1 = new LoggerContext();
    new ContextInitializer(loggerContext1).configureByResource(url1);
    ch.qos.logback.classic.Logger logger1 = loggerContext1.getLogger("com.foo.Bar");
    logger1.info("log4j2 - 1");
    Assert.assertNotNull(logger1);

    //logback logger 2

    URL url2 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/logback/logback_b.xml");
    LoggerContext loggerContext2 = new LoggerContext();
    new ContextInitializer(loggerContext2).configureByResource(url2);
    Logger logger2 = loggerContext2.getLogger("com.foo.Bar2");
    logger2.info("log4j2 - 222");
    Assert.assertNotNull(logger2);

    Assert.assertNotSame(logger1, logger2);

}
 
Example #3
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 #4
Source File: LOGBackConfigurer.java    From styx with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize LOGBack from the given URL.
 *
 * @param url              the url pointing to the location of the config file.
 * @param installJULBridge set to true to install SLF4J JUL bridge
 * @throws IllegalArgumentException if the url points to a non existing location or an error occurs during the parsing operation.
 */
public static void initLogging(URL url, boolean installJULBridge) {
    StaticLoggerBinder.getSingleton();
    ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
    LoggerContext loggerContext = selector.getLoggerContext();
    loggerContext.stop();
    ContextInitializer ctxi = new ContextInitializer(loggerContext);
    try {
        ctxi.configureByResource(url);
        loggerContext.start();
        if (installJULBridge) {
            //uninstall already present handlers we want to
            //continue logging through SLF4J after this point
            Logger l = LogManager.getLogManager().getLogger("");
            for (Handler h : l.getHandlers()) {
                l.removeHandler(h);
            }
            SLF4JBridgeHandler.install();

        }
    } catch (JoranException e) {
        throw new IllegalArgumentException("exception while initializing LOGBack", e);
    }
}
 
Example #5
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 #6
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 #7
Source File: Log.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 在日志中记录一些系统信息
 */
public static void logSystemProperties(String[] args)
{
	info("java.version = {}; os = {}, {}, {}", System.getProperty("java.version"),
			System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"));
	Runtime runtime = Runtime.getRuntime();
	info("processors = {}; jvm.heap = {}/{}M; file.encoding = {}", runtime.availableProcessors(),
			runtime.totalMemory() >> 20, runtime.maxMemory() >> 20, System.getProperty("file.encoding"));
	info("user.name = {}; user.dir = {}", System.getProperty("user.name"), System.getProperty("user.dir"));
	info("java.class.path = {}", System.getProperty("java.class.path"));
	URL url = new ContextInitializer(logCtx).findURLOfDefaultConfigurationFile(true);
	if (url == null)
		throw new Error("not found logback.xml from classpath");
	info("logback.path = {}", url.getPath());
	if (args != null)
	{
		for (int i = 0, n = args.length; i < n; ++i)
			info("arg{} = {}", i, args[i]);
	}
}
 
Example #8
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 #9
Source File: EcsEncoderIntegrationTest.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws JoranException {
    LoggerContext context = new LoggerContext();
    ContextInitializer contextInitializer = new ContextInitializer(context);
    contextInitializer.configureByResource(this.getClass().getResource("/logback-config.xml"));
    logger = context.getLogger("root");
    appender = (OutputStreamAppender) logger.getAppender("out");
}
 
Example #10
Source File: DefaultLogbackReInitializer.java    From sofa-common-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void reInitialize(final SpaceId spaceId, LoggerContext loggerContext,
                         final Properties properties, URL confFile) {
    if (isAlreadyReInitialized(loggerContext)) {
        return;
    }
    stopAndReset(loggerContext);
    loggerContext.getTurboFilterList().remove(DefaultLogbackFilterGenerator.FILTER);
    markAsReInitialized(loggerContext);
    initProperties(loggerContext, properties);
    if (isConsoleAppenderOpen(spaceId.getSpaceName(), properties)) {
        final ConsoleAppender appender = consoleAppender(loggerContext, properties);
        loggerContext.addTurboFilter(new TurboFilter() {
            @Override
            public FilterReply decide(Marker marker, Logger logger, Level level, String format,
                                      Object[] params, Throwable t) {
                if (!logger.isAttached(appender)) {
                    logger.detachAndStopAllAppenders();
                    logger.setLevel(getConsoleLevel(spaceId.getSpaceName(), properties));
                    logger.addAppender(appender);
                }
                return FilterReply.NEUTRAL;
            }
        });
    } else {
        try {
            new ContextInitializer(loggerContext).configureByResource(confFile);
        } catch (JoranException e) {
            throw new IllegalStateException("Logback loggerSpaceFactory re-build error", e);
        }
    }

}
 
Example #11
Source File: BaseCommand.java    From emissary with Apache License 2.0 5 votes vote down vote up
private void doLogbackReinit(LoggerContext loggerContext, String configFilePath) {
    System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, configFilePath);
    loggerContext.reset();
    ContextInitializer newContext = new ContextInitializer(loggerContext);
    try {
        newContext.autoConfig();
    } catch (JoranException e) {
        LOG.error("Problem reconfiguring logback with {}", getLogbackConfig(), e);
    }
}
 
Example #12
Source File: LogbackLoggingSystem.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
private void configureByResourceUrl(LoggingInitializationContext initializationContext, LoggerContext loggerContext, URL url)
		throws JoranException {
	if (url.toString().endsWith("xml")) {
		JoranConfigurator configurator = new SpringBootJoranConfigurator(initializationContext);
		configurator.setContext(loggerContext);
		configurator.doConfigure(url);
	} else {
		new ContextInitializer(loggerContext).configureByResource(url);
	}
}
 
Example #13
Source File: SampleApplication.java    From cukes with Apache License 2.0 5 votes vote down vote up
public static void overrideLogging() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    ContextInitializer initializer = new ContextInitializer(context);
    try {
        initializer.autoConfig();
    } catch (JoranException ignored) {}
}
 
Example #14
Source File: CLI.java    From sqlhelper with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
    // run mode
    boolean devMode = Boolean.parseBoolean(System.getProperty("dev", "false"));
    System.clearProperty("dev");
    String runMode = devMode ? "dev" : "production";
    System.setProperty(RUN_MODE_KEY, runMode);

    // homeDir
    String applicationDefaultConfigPath = Reflects.getCodeLocation(CLI.class).getPath();
    String homeDirDefault = "./..";
    if (devMode) {
        homeDirDefault = new File(applicationDefaultConfigPath).getPath();
    }
    String homeDir = System.getProperty(HOME_DIR_KEY, homeDirDefault);
    homeDir = new File(homeDir).getAbsolutePath();
    System.setProperty(HOME_DIR_KEY, homeDir);

    // pid
    recordPid(homeDir);

    Files.makeDirs(homeDir + File.separator + "logs");

    // custom logback.xml
    if (hasCustomLogbackXml(homeDir + File.separator + "config")) {
        System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, new File(homeDir + File.separator + "config/logback.xml").getAbsolutePath());
    } else if (hasCustomLogbackXml(homeDir)) {
        System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, new File(homeDir + File.separator + "logback.xml").getAbsolutePath());
    }
    logger = LoggerFactory.getLogger(CLI.class);

    // spring.profiles.active, spring.config.location
    String customConfigDir = FileResource.PREFIX + new File(homeDir).getPath() + "/config/";
    String configDirInJar = ClassPathResource.PREFIX + "./";
    configLocations.add(customConfigDir);
    configLocations.add(configDirInJar);

    final List<String> activeProfiles = Collects.emptyArrayList();
    activeProfiles.add("sqlhelper-cli");
    if (devMode) {
        activeProfiles.add("dev");
    }
    String specifiedProfiles = System.getProperty("spring.profiles.active");
    if (specifiedProfiles != null) {
        Pipeline.of(Strings.split(specifiedProfiles, ",")).forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                if (Strings.isNotBlank(s)) {
                    activeProfiles.add(s.trim());
                }
            }
        });
    }
    System.setProperty("spring.profiles.active", Strings.join(",", activeProfiles));
    System.setProperty("spring.config.location", Strings.join(",", configLocations));

    // startup ...
    final SpringApplication app = new SpringApplication(CLI.class);
    app.setBanner(new ProjectBanner());
    app.setBannerMode(Banner.Mode.LOG);
    final ApplicationContext context = app.run(args);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            SpringApplication.exit(context);
        }
    });
}
 
Example #15
Source File: LogbackLogManager.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public synchronized void configure(LoggingConfig loggingConfig) {
    if (context.isStarted()) {
        context.stop();
    }
    context.reset();
    context.start();

    boolean autoConfigurationFailed = false;
    try {
        new ContextInitializer(context).autoConfig();
    } catch (JoranException e) {
        autoConfigurationFailed = true;
    }

    if (autoConfigurationFailed || !isExplicitlyConfigured()) {
        context.reset();

        // Root logger level
        Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(convertLevel(loggingConfig.getLevel()));

        // Configure
        configureConsole(loggingConfig.console(), rootLogger);
        configureFile(loggingConfig.file(), rootLogger);

        // Nuun is quite verbose so it is set to WARN by default
        Logger nuunLogger = context.getLogger("io.nuun");
        nuunLogger.setLevel(Level.WARN);

        // When running under Tomcat with a LevelChangePropagator, DEBUG level and below lead to an exception
        // so we force INFO level
        if (underTomcat && (loggingConfig.getLevel() == LoggingConfig.Level.DEBUG || loggingConfig.getLevel() ==
                LoggingConfig.Level.TRACE)) {
            context.getLogger("org.apache.catalina").setLevel(Level.INFO);
            context.getLogger("org.apache.juli").setLevel(Level.INFO);
        }

        // Configure explicit loggers
        for (Map.Entry<String, LoggingConfig.LoggerConfig> loggerLevelEntry : loggingConfig.loggers()
                .entrySet()) {
            Logger logger = context.getLogger(loggerLevelEntry.getKey());
            LoggingConfig.LoggerConfig config = loggerLevelEntry.getValue();
            logger.setLevel(convertLevel(config.getLevel()));
            logger.setAdditive(config.isAdditive());
        }

        // Add level propagator for performance of JUL
        LevelChangePropagator levelChangePropagator = new LevelChangePropagator();
        levelChangePropagator.setContext(context);
        levelChangePropagator.setResetJUL(true);
        context.addListener(levelChangePropagator);
        levelChangePropagator.start();
    }
}