Java Code Examples for ch.qos.logback.classic.LoggerContext#putProperty()

The following examples show how to use ch.qos.logback.classic.LoggerContext#putProperty() . 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: 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 2
Source File: Application.java    From acme_client with MIT License 6 votes vote down vote up
private static void configureLogger(String logDir, String logLevel, String logbackConf) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        if (!logDir.endsWith(File.separator))
            logDir+= File.separator;
        context.putProperty("LOG_DIR", logDir);
        context.putProperty("LOG_LEVEL", logLevel);

        InputStream is = classloader.getResourceAsStream(logbackConf);
        configurator.doConfigure(is);
    } catch (JoranException je) {
        LOG.warn("Cannot configure logger. Continue to execute the command.", je);
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
 
Example 3
Source File: App.java    From PeerWasp with MIT License 6 votes vote down vote up
/**
 * Initializes the logging framework.
 * The automatic configuration is reset and the logger is configured dynamically:
 * - The log folder is set
 * - The log configuration is loaded (not from resources, but from the working directory).
 *
 * This allows switching the folder and the configuration during development and at deployment.
 */
private void initializeLogging() {
	LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
	try {
		JoranConfigurator jc = new JoranConfigurator();
		jc.setContext(context);
		// override default configuration
		context.reset();
		// inject the location of the appdata log folder as "LOG_FOLDER"
		// property of the LoggerContext
		context.putProperty("LOG_FOLDER", AppData.getLogFolder().toString());
		jc.doConfigure(LOG_CONFIGURATION);
	} catch (JoranException je) {
		// status printer will handle printing of error
	}
	StatusPrinter.printInCaseOfErrorsOrWarnings(context);
	logger.debug("Initialized logging (LOG_FOLDER={})", context.getProperty("LOG_FOLDER"));
}
 
Example 4
Source File: PluginLoggerFactory.java    From stash-codesearch-plugin with Apache License 2.0 6 votes vote down vote up
private void init() {
    // Assumes LSF4J is bound to logback
    context = (LoggerContext) LoggerFactory.getILoggerFactory();

    // store the home dir to use for relative paths
    context.putProperty("stash.home", homeDir);

    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);

    InputStream is;
    is = this.getClass().getClassLoader().getResourceAsStream("logback-test.xml");
    if (is != null) {
        stashRootLogger.info("Using logback-test.xml for logger settings");
    } else {
        stashRootLogger.info("Using logback.xml for logger settings");
        is = this.getClass().getClassLoader().getResourceAsStream("logback.xml");
    }

    try {
        configurator.doConfigure(is);
    } catch (JoranException e) {
        System.err.println("Error configuring logging framework" + e);
    }
    stashRootLogger.info("Logger using stash.home of " + homeDir);
}
 
Example 5
Source File: MillisecondPrecisionSyslogStartConverterTest.java    From logging-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLogContextPropertyHostname() {
  LoggerContext context = new LoggerContext();
  context.putProperty("hostname", HOSTNAME);

  MillisecondPrecisionSyslogStartConverter millisecondPrecisionSyslogStartConverter =
      new MillisecondPrecisionSyslogStartConverter();
  millisecondPrecisionSyslogStartConverter.setContext(context);
  millisecondPrecisionSyslogStartConverter.setOptionList(ImmutableList.of("LOCAL0"));
  millisecondPrecisionSyslogStartConverter.start();

  LoggingEvent event = new LoggingEvent();
  event.setLevel(Level.INFO);
  String message = millisecondPrecisionSyslogStartConverter.convert(event);

  assertTrue(message.contains(HOSTNAME));
}
 
Example 6
Source File: DefaultLogbackReInitializer.java    From sofa-common-tools with Apache License 2.0 5 votes vote down vote up
private void initProperties(LoggerContext loggerContext, Properties properties) {
    for (Map.Entry entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        String originValue = (String) entry.getValue();
        String value = System.getProperty(key, originValue);
        loggerContext.putProperty(key, value);
    }
}
 
Example 7
Source File: LogbackLoggingSystem.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) {
	LoggerContext context = getLoggerContext();
	stopAndReset(context);
	LogbackConfigurator configurator = new LogbackConfigurator(context);
	context.putProperty("LOG_LEVEL_PATTERN",
			initializationContext.getEnvironment().resolvePlaceholders("${logging.pattern.level:${LOG_LEVEL_PATTERN:%5p}}"));
	new EnhancedLogbackConfiguration(initializationContext, logFile).apply(configurator);
	context.setPackagingDataEnabled(true);
}
 
Example 8
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 5 votes vote down vote up
/**
 * Configure logging using a logback configuration file.
 *
 * @param file         A logback configuration file.
 * @param defaultIdent Fallback logging identity, used if not specified in config file.
 */
public static void configure(final File file, final String defaultIdent) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

  // Setup context
  final LoggerContext context = rootLogger.getLoggerContext();
  context.reset();

  // Log uncaught exceptions
  UncaughtExceptionLogger.setDefaultUncaughtExceptionHandler();

  // Load logging configuration from file
  try {
    final JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);
    configurator.doConfigure(file);
  } catch (JoranException je) {
    // StatusPrinter will handle this
  }

  context.putProperty("pid", getMyPid());
  final String hostname = getSpotifyHostname();
  if (hostname != null) {
    context.putProperty("hostname", hostname);
  }

  final String ident = context.getProperty("ident");
  if (ident == null) {
    context.putProperty("ident", defaultIdent);
  }

  StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
 
Example 9
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 5 votes vote down vote up
private static LoggerContext setupLoggerContext(Logger rootLogger, String ident) {
  final LoggerContext context = rootLogger.getLoggerContext();
  context.reset();
  context.putProperty("ident", ident);
  context.putProperty("pid", getMyPid());
  context.putProperty("hostname", getSpotifyHostname());
  return context;
}
 
Example 10
Source File: QpidUnitTestRunner.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private void setClassQualifiedTestName(final String name)
{
    final LoggerContext loggerContext = ((ch.qos.logback.classic.Logger) LOGGER).getLoggerContext();
    loggerContext.putProperty(LogbackPropertyValueDiscriminator.CLASS_QUALIFIED_TEST_NAME, name);
}
 
Example 11
Source File: LoggingBrokerAdminDecorator.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private void setClassQualifiedTestName(final String name)
{
    final LoggerContext loggerContext = ((ch.qos.logback.classic.Logger) LOGGER).getLoggerContext();
    loggerContext.putProperty(LogbackPropertyValueDiscriminator.CLASS_QUALIFIED_TEST_NAME, name);
}
 
Example 12
Source File: KafkaAppenderIT.java    From logback-kafka-appender with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeLogSystemInit() throws IOException, InterruptedException {

    kafka = TestKafka.createTestKafka(1,1,1);

    loggerContext = new LoggerContext();
    loggerContext.putProperty("brokers.list", kafka.getBrokerList());
    loggerContext.getStatusManager().add(new StatusListener() {
        @Override
        public void addStatusEvent(Status status) {
            if (status.getEffectiveLevel() > Status.INFO) {
                System.err.println(status.toString());
                if (status.getThrowable() != null) {
                    collector.addError(status.getThrowable());
                } else {
                    collector.addError(new RuntimeException("StatusManager reported warning: "+status.toString()));
                }
            } else {
                System.out.println(status.toString());
            }
        }
    });
    loggerContext.putProperty("HOSTNAME","localhost");

    unit = new KafkaAppender<>();
    final PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
    patternLayoutEncoder.setPattern("%msg");
    patternLayoutEncoder.setContext(loggerContext);
    patternLayoutEncoder.setCharset(Charset.forName("UTF-8"));
    patternLayoutEncoder.start();
    unit.setEncoder(patternLayoutEncoder);
    unit.setTopic("logs");
    unit.setName("TestKafkaAppender");
    unit.setContext(loggerContext);
    unit.setKeyingStrategy(new NoKeyKeyingStrategy());
    unit.setDeliveryStrategy(new AsynchronousDeliveryStrategy());
    unit.addAppender(fallbackAppender);
    unit.addProducerConfigValue(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBrokerList());
    unit.addProducerConfigValue(ProducerConfig.ACKS_CONFIG, "1");
    unit.addProducerConfigValue(ProducerConfig.MAX_BLOCK_MS_CONFIG, "2000");
    unit.addProducerConfigValue(ProducerConfig.LINGER_MS_CONFIG, "100");
    unit.setPartition(0);
    unit.setDeliveryStrategy(new AsynchronousDeliveryStrategy());
    unit.addAppender(new AppenderBase<ILoggingEvent>() {
        @Override
        protected void append(ILoggingEvent eventObject) {
            fallbackLoggingEvents.add(eventObject);
        }
    });
}