Java Code Examples for ch.qos.logback.classic.LoggerContext

The following examples show how to use ch.qos.logback.classic.LoggerContext. 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
Source Project: logging-java   Source File: LoggingConfigurator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add a sentry appender.
 * @param dsn the sentry dsn to use (as produced by the sentry webinterface).
 * @param logLevelThreshold the threshold for log events to be sent to sentry.
 * @return the configured sentry appender.
 */
public static SentryAppender addSentryAppender(final String dsn, Level logLevelThreshold) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

  final LoggerContext context = rootLogger.getLoggerContext();

  SentryAppender appender = new SentryAppender();
  appender.setDsn(dsn);

  appender.setContext(context);
  ThresholdFilter levelFilter = new ThresholdFilter();
  levelFilter.setLevel(logLevelThreshold.logbackLevel.toString());
  levelFilter.start();
  appender.addFilter(levelFilter);

  appender.start();

  rootLogger.addAppender(appender);

  return appender;
}
 
Example 2
private void setMetricsMarkerLogbackFilter(LoggerContext context) {
    log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME);
    OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator();
    onMarkerMetricsEvaluator.setContext(context);
    onMarkerMetricsEvaluator.addMarker("metrics");
    onMarkerMetricsEvaluator.start();
    EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>();
    metricsFilter.setContext(context);
    metricsFilter.setEvaluator(onMarkerMetricsEvaluator);
    metricsFilter.setOnMatch(FilterReply.DENY);
    metricsFilter.start();

    for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
        for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
            Appender<ILoggingEvent> appender = it.next();
            if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) {
                log.debug("Filter metrics logs from the {} appender", appender.getName());
                appender.setContext(context);
                appender.addFilter(metricsFilter);
                appender.start();
            }
        }
    }
}
 
Example 3
Source Project: Lavalink   Source File: SentryConfiguration.java    License: MIT License 6 votes vote down vote up
private static synchronized SentryAppender getSentryLogbackAppender() {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);

    SentryAppender sentryAppender = (SentryAppender) root.getAppender(SENTRY_APPENDER_NAME);
    if (sentryAppender == null) {
        sentryAppender = new SentryAppender();
        sentryAppender.setName(SENTRY_APPENDER_NAME);

        ThresholdFilter warningsOrAboveFilter = new ThresholdFilter();
        warningsOrAboveFilter.setLevel(Level.WARN.levelStr);
        warningsOrAboveFilter.start();
        sentryAppender.addFilter(warningsOrAboveFilter);

        sentryAppender.setContext(loggerContext);
        root.addAppender(sentryAppender);
    }
    return sentryAppender;
}
 
Example 4
@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 5
Source Project: tutorials   Source File: LoggingConfiguration.java    License: MIT License 6 votes vote down vote up
private void setMetricsMarkerLogbackFilter(LoggerContext context) {
    log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME);
    OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator();
    onMarkerMetricsEvaluator.setContext(context);
    onMarkerMetricsEvaluator.addMarker("metrics");
    onMarkerMetricsEvaluator.start();
    EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>();
    metricsFilter.setContext(context);
    metricsFilter.setEvaluator(onMarkerMetricsEvaluator);
    metricsFilter.setOnMatch(FilterReply.DENY);
    metricsFilter.start();

    for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
        for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
            Appender<ILoggingEvent> appender = it.next();
            if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) {
                log.debug("Filter metrics logs from the {} appender", appender.getName());
                appender.setContext(context);
                appender.addFilter(metricsFilter);
                appender.start();
            }
        }
    }
}
 
Example 6
Source Project: litchi   Source File: LogUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void loadFileConfig(String configFilePath) throws IOException, JoranException {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    File externalConfigFile = new File(configFilePath);

    if (!externalConfigFile.isFile()) {
        throw new IOException("logback config file not exists. configFilePath = " + configFilePath);
    }

    if (!externalConfigFile.canRead()) {
        throw new IOException("logback config file cannot be read. configFilePath = " + configFilePath);
    }

    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(configFilePath);
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

}
 
Example 7
Source Project: super-cloudops   Source File: LogbackLoggingSystem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, LogFile logFile) {
	super.loadConfiguration(initializationContext, location, logFile);
	LoggerContext loggerContext = getLoggerContext();
	stopAndReset(loggerContext);
	try {
		configureByResourceUrl(initializationContext, loggerContext, ResourceUtils.getURL(location));
	} catch (Exception ex) {
		throw new IllegalStateException("Could not initialize Logback logging from " + location, ex);
	}
	List<Status> statuses = loggerContext.getStatusManager().getCopyOfStatusList();
	StringBuilder errors = new StringBuilder();
	for (Status status : statuses) {
		if (status.getLevel() == Status.ERROR) {
			errors.append(errors.length() > 0 ? String.format("%n") : "");
			errors.append(status.toString());
		}
	}
	if (errors.length() > 0) {
		throw new IllegalStateException(String.format("Logback configuration error detected: %n%s", errors));
	}
}
 
Example 8
Source Project: otroslogviewer   Source File: LogbackUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTranslate() throws Exception {
  //Given
  LoggerContext context = new LoggerContext();
  Logger logger = context.getLogger("SomeLogger");
  LoggingEvent le = new LoggingEvent("a.b.C",logger, ch.qos.logback.classic.Level.INFO,"message",null,null);
  final Map<String, String> split = Splitter.on(",").withKeyValueSeparator("=").split("a=b,b=as");
  le.setMDCPropertyMap(split);
  le.setCallerData(new StackTraceElement[]{new StackTraceElement("a.b.C","someMethod","C.java",120)});

  //when
  final LogData logData = LogbackUtil.translate(le).build();

  //then
  assertEquals(logData.getMessage(),"message");
  assertEquals(logData.getLevel(),Level.INFO);
  assertEquals(logData.getLoggerName(),"SomeLogger");
  assertEquals(logData.getClazz(),"a.b.C");
  assertEquals(logData.getMethod(),"someMethod");
  assertEquals(logData.getLine(),"120");
  assertEquals(logData.getProperties(),split);
}
 
Example 9
Source Project: synopsys-detect   Source File: DiagnosticLogger.java    License: Apache License 2.0 6 votes vote down vote up
private FileAppender<ILoggingEvent> addAppender(final String file) {
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();

    final FileAppender<ILoggingEvent> appender;
    appender = new FileAppender<>();
    appender.setFile(file);
    appender.setEncoder(ple);
    appender.setContext(lc);
    final ThresholdFilter levelFilter = new ThresholdFilter();
    levelFilter.setLevel(this.level.levelStr);
    levelFilter.start();
    appender.addFilter(levelFilter);

    appender.start();

    final ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    logbackLogger.addAppender(appender);

    return appender;
}
 
Example 10
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 11
Source Project: alchemy   Source File: LoggingConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private void setMetricsMarkerLogbackFilter(LoggerContext context) {
    log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME);
    OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator();
    onMarkerMetricsEvaluator.setContext(context);
    onMarkerMetricsEvaluator.addMarker("metrics");
    onMarkerMetricsEvaluator.start();
    EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>();
    metricsFilter.setContext(context);
    metricsFilter.setEvaluator(onMarkerMetricsEvaluator);
    metricsFilter.setOnMatch(FilterReply.DENY);
    metricsFilter.start();

    context.getLoggerList().forEach((logger) -> {
        for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
            Appender<ILoggingEvent> appender = it.next();
            if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)
                    && !(appender.getName().equals(CONSOLE_APPENDER_NAME) && this.jHipsterProperties.getLogging().isUseJsonFormat())) {
                log.debug("Filter metrics logs from the {} appender", appender.getName());
                appender.setContext(context);
                appender.addFilter(metricsFilter);
                appender.start();
            }
        }
    });
}
 
Example 12
Source Project: tutorials   Source File: LoggingConfiguration.java    License: MIT License 6 votes vote down vote up
private void setMetricsMarkerLogbackFilter(LoggerContext context) {
    log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME);
    OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator();
    onMarkerMetricsEvaluator.setContext(context);
    onMarkerMetricsEvaluator.addMarker("metrics");
    onMarkerMetricsEvaluator.start();
    EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>();
    metricsFilter.setContext(context);
    metricsFilter.setEvaluator(onMarkerMetricsEvaluator);
    metricsFilter.setOnMatch(FilterReply.DENY);
    metricsFilter.start();

    for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
        for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
            Appender<ILoggingEvent> appender = it.next();
            if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) {
                log.debug("Filter metrics logs from the {} appender", appender.getName());
                appender.setContext(context);
                appender.addFilter(metricsFilter);
                appender.start();
            }
        }
    }
}
 
Example 13
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 14
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 15
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 16
@Test
public void simple() throws IOException {
    encoder.start();

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

    final String logMsg = encodeToStr(simpleLoggingEvent(logger, null));

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

    final LineReader msg =
        new LineReader(new StringReader(jsonNode.get("full_message").textValue()));
    assertEquals("message 1", msg.readLine());
}
 
Example 17
Source Project: logback-syslog4j   Source File: Syslog4jAppenderTest.java    License: MIT License 6 votes vote down vote up
public void testUdpSender() throws JoranException, InterruptedException {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);
    context.reset();
    configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-udp.xml"));

    Logger logger = context.getLogger("test-udp");
    logger.info("test message over udp");

    context.stop();
    Thread.sleep(100);

    final String serverData = serverStream.toString();
    assertTrue("Server received: " + serverData, serverData.contains("test message over udp"));
}
 
Example 18
Source Project: konker-platform   Source File: KonkerStaticLoggerBinder.java    License: Apache License 2.0 6 votes vote down vote up
void init() {
    try {
        try {
            (new KonkerContextInitializer(this.defaultLoggerContext)).autoConfig();
        } catch (JoranException var2) {
            Util.report("Failed to auto configure default logger context", var2);
        }

        if(!StatusUtil.contextHasStatusListener(this.defaultLoggerContext)) {
            StatusPrinter.printInCaseOfErrorsOrWarnings(this.defaultLoggerContext);
        }

        this.contextSelectorBinder.init(this.defaultLoggerContext, KEY);
        this.initialized = true;
    } catch (Throwable var3) {
        Util.report("Failed to instantiate [" + LoggerContext.class.getName() + ']', var3);
    }

}
 
Example 19
Source Project: cubeai   Source File: LogsResource.java    License: Apache License 2.0 5 votes vote down vote up
@PutMapping("/logs")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Timed
public void changeLevel(@RequestBody LoggerVM jsonLogger) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
}
 
Example 20
Source Project: Baragon   Source File: BaragonServiceTestModule.java    License: Apache License 2.0 5 votes vote down vote up
public BaragonServiceTestModule() throws Exception {
  this.ts = new TestingServer();

  this.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("baragon.test.log.level", "WARN")));

  Logger hsLogger = context.getLogger("com.hubspot");
  hsLogger.setLevel(Level.toLevel(System.getProperty("baragon.test.log.level.for.com.hubspot", "INFO")));
}
 
Example 21
Source Project: flair-registry   Source File: LogsResource.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/logs")
@Timed
public List<LoggerVM> getList() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    return context.getLoggerList()
        .stream()
        .map(LoggerVM::new)
        .collect(Collectors.toList());
}
 
Example 22
Source Project: cubeai   Source File: LogsResource.java    License: Apache License 2.0 5 votes vote down vote up
@PutMapping("/logs")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Timed
public void changeLevel(@RequestBody LoggerVM jsonLogger) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
}
 
Example 23
Source Project: flair-registry   Source File: LoggingConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private void addLogstashAppender(LoggerContext context) {
    log.info("Initializing Logstash logging");

    LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender();
    logstashAppender.setName(LOGSTASH_APPENDER_NAME);
    logstashAppender.setContext(context);
    String optionalFields = "";
    String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"," +
        optionalFields + "\"version\":\"" + version + "\"}";

    // More documentation is available at: https://github.com/logstash/logstash-logback-encoder
    LogstashEncoder logstashEncoder = new LogstashEncoder();
    // Set the Logstash appender config from JHipster properties
    logstashEncoder.setCustomFields(customFields);
    // Set the Logstash appender config from JHipster properties
    logstashAppender.addDestinations(new InetSocketAddress(jHipsterProperties.getLogging().getLogstash().getHost(), jHipsterProperties.getLogging().getLogstash().getPort()));

    ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter();
    throwableConverter.setRootCauseFirst(true);
    logstashEncoder.setThrowableConverter(throwableConverter);
    logstashEncoder.setCustomFields(customFields);

    logstashAppender.setEncoder(logstashEncoder);
    logstashAppender.start();

    // Wrap the appender in an Async appender for performance
    AsyncAppender asyncLogstashAppender = new AsyncAppender();
    asyncLogstashAppender.setContext(context);
    asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME);
    asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize());
    asyncLogstashAppender.addAppender(logstashAppender);
    asyncLogstashAppender.start();

    context.getLogger("ROOT").addAppender(asyncLogstashAppender);
}
 
Example 24
Source Project: stratio-cassandra   Source File: StorageService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return the runtime logging levels for all the configured loggers
 */
@Override
public Map<String,String>getLoggingLevels() {
    Map<String, String> logLevelMaps = Maps.newLinkedHashMap();
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    for (ch.qos.logback.classic.Logger logger : lc.getLoggerList())
    {
        if(logger.getLevel() != null || hasAppenders(logger))
            logLevelMaps.put(logger.getName(), logger.getLevel().toString());
    }
    return logLevelMaps;
}
 
Example 25
Source Project: tasmo   Source File: CombinatorialMaterializerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void logger() {

    Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    LoggerContext loggerContext = rootLogger.getLoggerContext();
    loggerContext.reset();

    if (verbose) {

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern("[%thread]: %message%n");
        encoder.start();

        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
        appender.setContext(loggerContext);
        appender.setEncoder(encoder);
        appender.start();

        rootLogger.addAppender(appender);

        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo")).setLevel(Level.TRACE);
        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo.lib.concur.ConcurrencyAndExistanceCommitChange")).setLevel(Level.TRACE);
        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo.reference.lib.ReferenceStore")).setLevel(Level.TRACE);
        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo.view.reader.service.writer.WriteToViewValueStore")).setLevel(Level.TRACE);
    } else {

        rootLogger.setLevel(Level.OFF);
    }
}
 
Example 26
Source Project: albedo   Source File: LogsResource.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@GetMapping("/logs")
public List<LoggerVo> getList() {
	LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
	return context.getLoggerList()
		.stream()
		.map(LoggerVo::new)
		.collect(Collectors.toList());
}
 
Example 27
Source Project: cuba   Source File: LogControlImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getLoggers() {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    List<String> list = new ArrayList<>();
    for (Logger log : lc.getLoggerList()) {
        if (log.getLevel() != null || hasAppenders(log)) {
            list.add(log.getName());
        }
    }
    return list;
}
 
Example 28
Source Project: DDMQ   Source File: LogbackTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws JoranException {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
 
Example 29
Source Project: amazon-kinesis-client   Source File: MultiLangDaemonTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulLoggingConfiguration() {
    LoggerContext loggerContext = spy((LoggerContext) LoggerFactory.getILoggerFactory());
    JoranConfigurator configurator = spy(new JoranConfigurator());

    String logConfiguration = this.getClass().getClassLoader().getResource("logback.xml").getPath();
    daemon.configureLogging(logConfiguration, loggerContext, configurator);

    verify(loggerContext).reset();
    verify(configurator).setContext(eq(loggerContext));
}
 
Example 30
@GetMapping("/logs")
@Timed
public List<LoggerVM> getList() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    return context.getLoggerList()
        .stream()
        .map(LoggerVM::new)
        .collect(Collectors.toList());
}