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

The following examples show how to use ch.qos.logback.classic.LoggerContext#getLogger() . 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: GelfEncoderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void customThreadNameKey() throws IOException {
    encoder.setThreadNameKey("Thread");
    encoder.start();

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final LoggingEvent event = simpleLoggingEvent(logger, null);

    final String logMsg = encodeToStr(event);

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    coreValidation(jsonNode);
    assertNotNull(jsonNode.get("_Thread").textValue());
    assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue());
    assertNull(jsonNode.get("_exception"));
}
 
Example 2
Source File: LogbackController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Frees the given logger from the appender used to be displayed directly by
 * this controller.
 *
 * @param name The name of the logger we want to free from being captured
 * @return The list of log levels configured and their settings
 */
@RequestMapping(value = "free/{name}/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> free(@PathVariable("name")
final String name) {
    final LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
    synchronized (ctx) {
        Logger logger = ctx.getLogger(name);
        if (logger != null) {
            logger.setLevel(null);
            logger.detachAppender(logbackMemoryAppenderImpl.getName());
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 3
Source File: GelfEncoderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void numericValueAsNumber() throws IOException {
    encoder.start();

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final LoggingEvent event = simpleLoggingEvent(logger, null);

    event.setMDCPropertyMap(ImmutableMap.of("int", "200", "float", "0.00001"));

    final String logMsg = encodeToStr(event);

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    basicValidation(jsonNode);

    assertTrue(logMsg.contains("\"_int\":200"));
    assertTrue(logMsg.contains("\"_float\":0.00001"));
}
 
Example 4
Source File: AionLoggerFactory.java    From aion_api with MIT License 6 votes vote down vote up
public static void init(final Map<String, String> _logModules) {

        _logModules
                .entrySet()
                .stream()
                .forEach(
                        e -> {
                            logModules.put(e.getKey(), e.getValue());
                        });

        loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

        encoder.setContext(loggerContext);
        encoder.setPattern("%date{yy-MM-dd HH:mm:ss.SSS} %-5level %-4c [%thread]: %message%n");
        encoder.start();

        appender.setContext(loggerContext);
        appender.setEncoder(encoder);
        appender.start();

        ch.qos.logback.classic.Logger rootlogger = loggerContext.getLogger("ROOT");
        rootlogger.detachAndStopAllAppenders();
    }
 
Example 5
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doFailSafeConfiguration() {
    // Not really fail-safe, just less likely to fail
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);

    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    rootLogger.addAppender(appender);
    appender.setContext(context);
    appender.setTarget("System.err");

    PatternLayout layout = new PatternLayout();
    appender.setLayout(layout);
    layout.setPattern("%msg%n%ex");
    layout.setContext(context);

    layout.start();
    appender.start();
}
 
Example 6
Source File: SingularityTestModule.java    From Singularity with Apache License 2.0 6 votes vote down vote up
public SingularityTestModule(
  boolean useDbTests,
  Function<SingularityConfiguration, Void> customConfigSetup
)
  throws Exception {
  this.useDBTests = useDbTests;
  this.customConfigSetup = customConfigSetup;

  dropwizardModule = new DropwizardModule(environment);

  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger rootLogger = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
  rootLogger.setLevel(
    Level.toLevel(System.getProperty("singularity.test.log.level", "WARN"))
  );

  Logger hsLogger = context.getLogger("com.hubspot");
  hsLogger.setLevel(
    Level.toLevel(
      System.getProperty("singularity.test.log.level.for.com.hubspot", "WARN")
    )
  );

  this.ts = new TestingServer();
}
 
Example 7
Source File: GelfEncoderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void multipleMarker() throws IOException {
    encoder.setLoggerNameKey("Logger");
    encoder.start();

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final LoggingEvent event = simpleLoggingEvent(logger, null);
    final Marker marker = MarkerFactory.getMarker("FIRST");
    marker.add(MarkerFactory.getMarker("SECOND"));
    event.setMarker(marker);

    final String logMsg = encodeToStr(event);

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    coreValidation(jsonNode);
    assertEquals("FIRST, SECOND", jsonNode.get("_marker").textValue());
}
 
Example 8
Source File: LogbackUtil.java    From summerframework with Apache License 2.0 6 votes vote down vote up
private static Logger build(String name, Level logLevel, String fileName) {
    LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
    Logger logger = context.getLogger(name);
    if (Level.ALL.equals(logLevel)) {
        RollingFileAppender errorAppender = new AppenderBuild().getAppender(name, Level.ERROR, fileName);
        RollingFileAppender infoAppender = new AppenderBuild().getAppender(name, Level.INFO, fileName);
        RollingFileAppender warnAppender = new AppenderBuild().getAppender(name, Level.WARN, fileName);
        RollingFileAppender debugAppender = new AppenderBuild().getAppender(name, Level.DEBUG, fileName);

        logger.setAdditive(false);
        logger.addAppender(errorAppender);
        logger.addAppender(infoAppender);
        logger.addAppender(warnAppender);
        logger.addAppender(debugAppender);

    } else {
        logger = buildInfoByLevel(name, logLevel, fileName);
    }
    return logger;
}
 
Example 9
Source File: AccountImpl.java    From java-trader with Apache License 2.0 5 votes vote down vote up
/**
 * 创建Account Logger
 * @param separateLogger true 会为每个Account创建一个日志文件: TRADER_HOME/work/<TRADING_DAY>/accountId.log
 */
private void createAccountLogger() {
    if ( !simMode ) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

        FileAppender fileAppender = new FileAppender();
        fileAppender.setContext(loggerContext);
        fileAppender.setName("timestamp");
        // set the file name
        File logFile = new File(tradingWorkDir, id+".log");
        fileAppender.setFile(logFile.getAbsolutePath());

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern("%d [%thread] %-5level %logger{35} - %msg %n");
        encoder.start();

        fileAppender.setEncoder(encoder);
        fileAppender.start();

        // attach the rolling file appender to the logger of your choice
        loggerCategory = AccountImpl.class.getName()+"."+id;
        ch.qos.logback.classic.Logger packageLogger = loggerContext.getLogger(loggerCategory);
        packageLogger.addAppender(fileAppender);
        packageLogger.setAdditive(true); //保证每个Account数据, 在主的日志中也有一份

        logger = loggerContext.getLogger(loggerCategory+"."+AccountImpl.class.getSimpleName());
    } else {
        loggerCategory = AccountImpl.class.getName();
        logger = LoggerFactory.getLogger(AccountImpl.class);
    }
}
 
Example 10
Source File: FlumeLoggerLoader.java    From chassis with Apache License 2.0 5 votes vote down vote up
public synchronized void installFlumeAppender() {
	LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	appender.setContext(logContext);
	appender.start();

	Logger logger = logContext.getLogger(Logger.ROOT_LOGGER_NAME);

	if (logger.getAppender(appender.getName()) == null) {
		logger.addAppender(appender);
	}
}
 
Example 11
Source File: Logback1027WorkaroundTurboFilterTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    LoggerContext context = new LoggerContext();
    _logger = context.getLogger(Logback1027WorkaroundTurboFilterTest.class);
    _snoopingAppender = new SnoopingAppender();
    _logger.addAppender(_snoopingAppender);
}
 
Example 12
Source File: LogUtil.java    From chaosblade-exec-jvm with 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 13
Source File: LogbackConfiguration.java    From milkman with MIT License 4 votes vote down vote up
private void setupFileAppender(LoggerContext loggerContext) {
	RollingFileAppender<ILoggingEvent> fa = new RollingFileAppender<ILoggingEvent>();
	fa.setFile(PlatformUtil.getWritableLocationForFile("errors.log"));
	
	SizeBasedTriggeringPolicy<ILoggingEvent> sizePolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>();
	sizePolicy.setContext(loggerContext);
	sizePolicy.setMaxFileSize(FileSize.valueOf("10mb"));
	sizePolicy.start();
	fa.setTriggeringPolicy(sizePolicy);
	var policy = new FixedWindowRollingPolicy();
	policy.setMaxIndex(3);
	policy.setMinIndex(1);
	policy.setFileNamePattern("errors.%i.log.zip");
	policy.setParent(fa);
	policy.setContext(loggerContext);
	policy.start();
	fa.setRollingPolicy(policy);
	
	
	fa.setContext(loggerContext);
	fa.setName("FILE");
	
	var filter = new ThresholdFilter();
	filter.setLevel("ERROR");
	filter.start();
	fa.addFilter(filter);

	LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<ILoggingEvent>();
	encoder.setContext(loggerContext);

	// same as
	// PatternLayout layout = new PatternLayout();
	// layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
	PatternLayout layout = new PatternLayout();
	layout.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");

	layout.setContext(loggerContext);
	layout.start();
	encoder.setLayout(layout);
	fa.setEncoder(encoder);

	
	fa.start();

	Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.addAppender(fa);
}
 
Example 14
Source File: OfframpConsole.java    From data-highway with Apache License 2.0 4 votes vote down vote up
/**
 * Helper function to configure where message and CLI output is directed as well as configure logging
 * This should be called first to ensure correct output of message and cli logging into the desired stream.
 */
private void configureOutput() {
  try {
    if (flipOutput) {
      PrintStream tmp = msgout;
      msgout = cliout;
      cliout = tmp;
    }

    // change output format from json to yaml
    if (format == Format.YAML) {
      mapper = new YAMLMapper();
    }

    // retrieve the ch.qos.logback.classic.LoggerContext
    LoggerContext logCtx = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

    PatternLayoutEncoder logEncoder = new PatternLayoutEncoder();
    logEncoder.setContext(logCtx);
    logEncoder.setPattern("%d{HH:mm:ss.SSS} - %-5level %logger{35} - %msg%n");
    logEncoder.start();

    OutputStreamAppender logConsoleAppender = new OutputStreamAppender();
    logConsoleAppender.setContext(logCtx);
    logConsoleAppender.setOutputStream(cliout);
    logConsoleAppender.setName("console");
    logConsoleAppender.setEncoder(logEncoder);
    logConsoleAppender.start();

    Logger rootLogger = logCtx.getLogger("root");
    rootLogger.detachAndStopAllAppenders();
    rootLogger.setLevel(Level.WARN);
    rootLogger.addAppender(logConsoleAppender);

    Logger roadLogger = logCtx.getLogger("com.hotels.road");
    roadLogger.setLevel(Level.WARN);

    Logger clientLogger = logCtx.getLogger("com.hotels.road.offramp.client");
    clientLogger.setLevel(debug ? Level.DEBUG : Level.INFO);

    Logger cliLogger = logCtx.getLogger("com.hotels.road.tool.cli");
    cliLogger.setLevel(debug ? Level.DEBUG : Level.INFO);
  } catch (Exception e) {
    System.err.println("Error configuring the message and cli output:");
    e.printStackTrace();
    System.exit(Error.OUTPUT_CONFIGURATION.code);
  }
}
 
Example 15
Source File: SingularityExecutorLogging.java    From Singularity with Apache License 2.0 4 votes vote down vote up
public Logger buildTaskLogger(
  String taskId,
  String executorId,
  String executorPid,
  String taskLogFile
) {
  LOG.info("Building a task logger for {} pointing to {}", taskId, taskLogFile);

  LoggerContext context = new LoggerContext();

  context.setName(executorPid);

  baseLogging.prepareRootLogger(context);

  String loggerId = taskId;

  try {
    SingularityTaskId singularityTaskId = SingularityTaskId.valueOf(taskId);

    loggerId =
      String.format(
        "%s.%s.%s.%s.%s",
        singularityTaskId.getRequestId(),
        singularityTaskId.getDeployId(),
        singularityTaskId.getStartedAt(),
        singularityTaskId.getInstanceNo(),
        executorId
      );
  } catch (InvalidSingularityTaskIdException e) {
    LOG.info("Handling non-SingularityTaskId %s", taskId);
  }

  Logger taskLogger = context.getLogger(loggerId);
  taskLogger.detachAndStopAllAppenders();

  if (baseLogging.getRootLogPath().isPresent()) {
    taskLogger.addAppender(
      baseLogging.buildFileAppender(context, baseLogging.getRootLogPath().get())
    );
  }
  taskLogger.addAppender(baseLogging.buildFileAppender(context, taskLogFile));

  context.start();

  return taskLogger;
}
 
Example 16
Source File: FlickrUploader.java    From flickr-uploader with GNU General Public License v2.0 4 votes vote down vote up
private static void initLogs() {
    Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    LoggerContext lc = logbackLogger.getLoggerContext();

    Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setMaxHistory(3);
    SizeAndTimeBasedFNATP<ILoggingEvent> sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP<ILoggingEvent>();
    sizeAndTimeBasedFNATP.setMaxFileSize("2MB");
    rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP);
    rollingPolicy.setFileNamePattern(context.getFilesDir().getPath() + "/logs/old/flickruploader.%d{yyyy-MM-dd}.%i.log");
    rollingPolicy.setContext(lc);

    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(lc);
    fileAppender.setFile(getLogFilePath());
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.setTriggeringPolicy(rollingPolicy);
    rollingPolicy.setParent(fileAppender);

    PatternLayoutEncoder pl = new PatternLayoutEncoder();
    pl.setContext(lc);
    pl.setCharset(Charset.defaultCharset());
    pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %class{0}.%method:%L > %msg%n");
    pl.setImmediateFlush(false);
    pl.start();

    fileAppender.setEncoder(pl);
    fileAppender.setName("file");

    rollingPolicy.start();
    fileAppender.start();

    if (Config.isDebug()) {
        final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
        logcatTagPattern.setContext(lc);
        logcatTagPattern.setPattern("%class{0}");
        logcatTagPattern.start();

        final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
        logcatPattern.setContext(lc);
        logcatPattern.setPattern("[%thread] %method:%L > %msg%n");
        logcatPattern.start();

        final LogcatAppender logcatAppender = new LogcatAppender();
        logcatAppender.setContext(lc);
        logcatAppender.setTagEncoder(logcatTagPattern);
        logcatAppender.setEncoder(logcatPattern);
        logcatAppender.start();

        rootLogger.addAppender(logcatAppender);
    }

    rootLogger.addAppender(fileAppender);

}
 
Example 17
Source File: LoggingAutoConfiguration.java    From java-spring-cloud with Apache License 2.0 4 votes vote down vote up
private Logger getRootLogger() {
  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  return context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
}
 
Example 18
Source File: BitherApplication.java    From bither-android with Apache License 2.0 4 votes vote down vote up
private void initLogging() {
    final File logDir = getLogDir();
    final File logFile = new File(logDir, "bitherj.log");
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder filePattern = new PatternLayoutEncoder();
    filePattern.setContext(context);
    filePattern.setPattern("%d{HH:mm:ss.SSS} [%thread] %logger{0} - %msg%n");
    filePattern.start();

    final RollingFileAppender<ILoggingEvent> fileAppender = new
            RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(context);
    fileAppender.setFile(logFile.getAbsolutePath());

    final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new
            TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setContext(context);
    rollingPolicy.setParent(fileAppender);
    rollingPolicy.setFileNamePattern(logDir.getAbsolutePath() + "/bitherj.%d.log.gz");
    rollingPolicy.setMaxHistory(7);
    rollingPolicy.start();

    fileAppender.setEncoder(filePattern);
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.start();

    final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
    logcatTagPattern.setContext(context);
    logcatTagPattern.setPattern("%logger{0}");
    logcatTagPattern.start();

    final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
    logcatPattern.setContext(context);
    logcatPattern.setPattern("[%thread] %msg%n");
    logcatPattern.start();

    final LogcatAppender logcatAppender = new LogcatAppender();
    logcatAppender.setContext(context);
    logcatAppender.setTagEncoder(logcatTagPattern);
    logcatAppender.setEncoder(logcatPattern);
    logcatAppender.start();

    final ch.qos.logback.classic.Logger log = context.getLogger(Logger.ROOT_LOGGER_NAME);
    log.addAppender(fileAppender);
    log.addAppender(logcatAppender);
    log.setLevel(Level.INFO);
}
 
Example 19
Source File: LoggingUtil.java    From ha-bridge with Apache License 2.0 3 votes vote down vote up
/**
 * Get a single logger. 
 * 
 * @return Logger
 */
public static ch.qos.logback.classic.Logger getLogger(final String loggerName) {

	final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

	return lc.getLogger(loggerName);
	
}
 
Example 20
Source File: LoggingUtil.java    From ha-bridge with Apache License 2.0 3 votes vote down vote up
/**
 * Get the log file.
 * 
 * @param logFileName The name of the log file 
 * @return The actual file
 */
public static File getLogFile(final String logFileName) {

	if (logFileName == null) {
		throw new IllegalArgumentException("logFileName cannot be null.");
	}

	final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

	final Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME);

	final Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders();

	while (it.hasNext()) {

		final Appender<ILoggingEvent> appender = it.next();

		if (appender instanceof FileAppender) {

			final FileAppender<ILoggingEvent> fileAppender = (FileAppender<ILoggingEvent>) appender;

			final File logFile = new File(fileAppender.getFile());

			if (logFile.getName().equalsIgnoreCase(logFileName)) {
				return logFile;
			}

		}

	}

	return null;
}