ch.qos.logback.core.Appender Java Examples

The following examples show how to use ch.qos.logback.core.Appender. 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: LoggingConfiguration.java    From okta-jhipster-microservices-oauth-example with 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();

    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 #2
Source File: LoggingConfiguration.java    From flair-registry with 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();

    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 File: LoggingConfiguration.java    From ehcache3-samples with 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();

    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 #4
Source File: LogBackHookProxy.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private void figureoutLogConfiguration(Logger Logger, LinkedList<LogProfileInfo> list, String appid) {

        Iterator<Appender<ILoggingEvent>> appenders = Logger.iteratorForAppenders();
        while (appenders != null && appenders.hasNext()) {
            Appender<ILoggingEvent> appender = appenders.next();
            if (appender instanceof FileAppender<?>) {
                getAppenderInfo((FileAppender<ILoggingEvent>)appender, list, appid);
            }
            else if(appender instanceof AsyncAppender) {
                Iterator<Appender<ILoggingEvent>> itAppenders = (Iterator<Appender<ILoggingEvent>>)((AsyncAppender) appender).iteratorForAppenders();
                while (itAppenders != null && itAppenders.hasNext()) {
                    Appender<ILoggingEvent> ap = itAppenders.next();
                    if (ap instanceof FileAppender<?>) {
                        getAppenderInfo((FileAppender<ILoggingEvent>)ap, list, appid);
                    }
                } 
            }
        }
    }
 
Example #5
Source File: WebClientLoggingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@BeforeEach
private void setup() throws Exception {

    post = new Post("Learn WebClient logging with Baeldung!", "", 1);
    sampleResponseBody = new ObjectMapper().writeValueAsString(post);

    ch.qos.logback.classic.Logger jetty = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.reactive.logging.jetty");
    jettyAppender = mock(Appender.class);
    when(jettyAppender.getName()).thenReturn("com.baeldung.reactive.logging.jetty");
    jetty.addAppender(jettyAppender);

    ch.qos.logback.classic.Logger netty = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("reactor.netty.http.client");
    nettyAppender = mock(Appender.class);
    when(nettyAppender.getName()).thenReturn("reactor.netty.http.client");
    netty.addAppender(nettyAppender);

    ch.qos.logback.classic.Logger test = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.reactive");
    mockAppender = mock(Appender.class);
    when(mockAppender.getName()).thenReturn("com.baeldung.reactive");
    test.addAppender(mockAppender);

}
 
Example #6
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 6 votes vote down vote up
/**
 * Create a syslog appender. The appender will use the facility local0. If host is null or an
 * empty string, default to "localhost". If port is less than 0, default to 514.
 *
 * @param context The logger context to use.
 * @param host The host running the syslog daemon.
 * @param port The port to connect to.
 * @return An appender that writes to syslog.
 */
static Appender<ILoggingEvent> getSyslogAppender(final LoggerContext context,
                                                 final String host,
                                                 final int port,
                                                 final ReplaceNewLines replaceNewLines) {
  final String h = isNullOrEmpty(host) ? "localhost" : host;
  final int p = port < 0 ? 514 : port;

  final MillisecondPrecisionSyslogAppender appender = new MillisecondPrecisionSyslogAppender();

  appender.setFacility("LOCAL0");
  appender.setSyslogHost(h);
  appender.setPort(p);
  appender.setName("syslog");
  appender.setCharset(Charsets.UTF_8);
  appender.setContext(context);
  appender.setSuffixPattern(
      "%property{ident}[%property{pid}]: " + ReplaceNewLines.getMsgPattern(replaceNewLines));
  appender.setStackTracePattern(
      "%property{ident}[%property{pid}]: " + CoreConstants.TAB);
  appender.start();

  return appender;
}
 
Example #7
Source File: LogbackController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 
 * @param name The name of the logger we want to manipulate the level of
 * @param level The new log level
 * @return The list of log levels configured and their settings
 */
@RequestMapping(value = "set/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> set(@PathVariable("name")
final String name, @PathVariable("level")
final String level) {
    final LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
    synchronized (ctx) {
        Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME);
        Logger logger = ctx.getLogger(name);
        if (logger != null) {
            logger.setLevel(Level.toLevel(level));
            logger.setAdditive(false);
            for (Iterator<Appender<ILoggingEvent>> it = root.iteratorForAppenders(); it.hasNext();) {
                logger.addAppender(it.next());
            }
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example #8
Source File: LogbackController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
private LogResponse listLoggers(final LoggerContext ctx) {
    LogResponse logResponse = new LogResponse();
    List<LogSpecification> result = new ArrayList<>();
    logResponse.setSpecs(result);
    synchronized (ctx) {
        ctx.getLoggerList().stream().filter(logger -> logger.getLevel() != null).forEach(logger -> {
            List<String> appenders = new ArrayList<>();
            for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
                appenders.add(it.next().getName());
            }
            result.add(new LogSpecification(logger.getName(), logger.getEffectiveLevel().toString(), appenders));
        });
    }
    return logResponse;

}
 
Example #9
Source File: AuditableLogbackThriftLoggerFactory.java    From singer with Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized ThriftLogger createLogger(ThriftLoggerConfig thriftLoggerConfig) {
  if (thriftLoggerConfig.getBaseDir() == null || thriftLoggerConfig.getLogRotationThresholdBytes() <= 0 ||
      thriftLoggerConfig.getKafkaTopic() == null ) {
    throw new IllegalArgumentException("The fields of thriftLoggerConfig are not properly set.");
  }

  Appender<LogMessage> appender = AppenderUtils.createFileRollingThriftAppender(
      thriftLoggerConfig.getBaseDir(),
      thriftLoggerConfig.getKafkaTopic(),
      thriftLoggerConfig.getLogRotationThresholdBytes()/ 1024, // convert to KB
      contextBase,
      thriftLoggerConfig.getMaxRetentionSecs() / (60 * 60));    // lowest granularity is hours

  if (loggingAuditClient != null && (thriftLoggerConfig.getThriftClazz()  != null || thriftLoggerConfig.isEnableLoggingAudit())){
    Map<String, String> properties = createProperties(thriftLoggerConfig.getAuditSamplingRate());
    AuditConfig auditConfig = loggingAuditClient.addAuditConfigFromMap(thriftLoggerConfig.getKafkaTopic(), properties);
    LOG.info("Add AuditConfig ({}) for {} ",  auditConfig, thriftLoggerConfig.getKafkaTopic());
  }

  return new AuditableLogbackThriftLogger(appender, thriftLoggerConfig.getKafkaTopic(),
      thriftLoggerConfig.getThriftClazz(), thriftLoggerConfig.isEnableLoggingAudit(),
      thriftLoggerConfig.getAuditSamplingRate());
}
 
Example #10
Source File: LoggingConfiguration.java    From alchemy with 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 #11
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 6 votes vote down vote up
/**
 * Create a stderr appender.
 *
 * @param context The logger context to use.
 * @return An appender writing to stderr.
 */
private static Appender<ILoggingEvent> getStdErrAppender(final LoggerContext context,
                                                         final ReplaceNewLines replaceNewLines) {

  // Setup format
  final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
  encoder.setContext(context);
  encoder.setPattern(
      "%date{HH:mm:ss.SSS} %property{ident}[%property{pid}]: %-5level [%thread] %logger{0}: "
          + ReplaceNewLines.getMsgPattern(replaceNewLines) + "%n");
  encoder.setCharset(Charsets.UTF_8);
  encoder.start();

  // Setup stderr appender
  final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
  appender.setTarget("System.err");
  appender.setName("stderr");
  appender.setEncoder(encoder);
  appender.setContext(context);
  appender.start();

  return appender;
}
 
Example #12
Source File: LoggingConfiguration.java    From cubeai with 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();

    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 File: BrokerFileLoggerImpl.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context loggerContext)
{
    SystemConfig<?> systemConfig = getAncestor(SystemConfig.class);
    _logbackStatusListener = new BrokerLoggerStatusListener(this,
                                                            systemConfig,
                                                            BROKER_FAIL_ON_LOGGER_IO_ERROR,
                                                            IOException.class,
                                                            IOError.class);
    _statusManager = loggerContext.getStatusManager();
    _statusManager.add(_logbackStatusListener);

    final RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(this, loggerContext, appender);
    return appender;
}
 
Example #14
Source File: LoggingConfiguration.java    From cubeai with 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();

    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 #15
Source File: LoggingConfiguration.java    From e-commerce-microservice with 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();

    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 #16
Source File: FileLocationProvider.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> asJson() {
    LinkedHashMap<String, Object> json = new LinkedHashMap<>();
    json.put("loc.config.dir", systemEnvironment.configDir().getAbsolutePath());

    List<Logger> loggers = LOGGER_CONTEXT.getLoggerList();

    Appender[] appenders = getAppenders(loggers);

    for (int i = 0; i < appenders.length; i++) {
        Appender appender = appenders[i];
        if (!isFileAppender(appender)) {
            continue;
        }
        FileAppender fileAppender = (FileAppender) appender;
        File logFile = new File(fileAppender.rawFileProperty());
        json.put("loc.log.root." + i, new File(logFile.getAbsolutePath()).getParent());
        json.put("loc.log.basename." + i, logFile.getName());
    }

    return json;
}
 
Example #17
Source File: DefaultPluginLoggingServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void assertPluginLogFile(String pluginId, String expectedPluginLogFileName) {
    SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);

    DefaultPluginLoggingService loggingService = new DefaultPluginLoggingService(systemEnvironment);
    loggingService.debug(pluginId, "some-logger-name", "message");

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("plugin." + pluginId);
    ArrayList<Appender<ILoggingEvent>> appenders = new ArrayList<>();
    logger.iteratorForAppenders().forEachRemaining(new Consumer<Appender<ILoggingEvent>>() {
        @Override
        public void accept(Appender<ILoggingEvent> iLoggingEventAppender) {
            appenders.add(iLoggingEventAppender);
        }
    });

    String loggingDirectory = loggingService.getCurrentLogDirectory();
    assertThat(appenders.size()).isEqualTo(1);
    assertThat(new File(((FileAppender) appenders.get(0)).rawFileProperty())).isEqualTo(new File(loggingDirectory, expectedPluginLogFileName));
}
 
Example #18
Source File: LoggingConfiguration.java    From cubeai with 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();

    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 #19
Source File: DynamicLogbackLogger.java    From tddl with Apache License 2.0 6 votes vote down vote up
private Appender buildAppender(String name, String fileName, String pattern) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setParent(appender);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd}");
    appender.setRollingPolicy(rolling);

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example #20
Source File: LoggingConfiguration.java    From cubeai with 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();

    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 #21
Source File: LoggingConfiguration.java    From e-commerce-microservice with 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();

    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 #22
Source File: GenerateAuthnRequestResourceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldLeaveMDCInPreviousStateAfterLogging() throws Exception {
    Logger logger = (Logger) LoggerFactory.getLogger(AuthnRequestAttributesHelper.class);
    Appender<ILoggingEvent> appender = mock(Appender.class);
    logger.addAppender(appender);

    // Log and then Check state of MDC before calling the resource
    MDC.put("testMDCKey", "testMDCValue");
    logger.info("Do some logging to see what's on the MDC beforehand...");

    ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    verify(appender).doAppend(loggingEventArgumentCaptor.capture());

    int mdcPropertyMapSizeBeforeCall = loggingEventArgumentCaptor.getValue().getMDCPropertyMap().size();

    when(authnRequestFactory.build(any())).thenReturn(authnRequest);
    RequestGenerationBody requestGenerationBody = new RequestGenerationBody(LevelOfAssurance.LEVEL_2, null);

    Response response =
            resources.target(GENERATE_REQUEST_RESOURCE_PATH).request().post(
                    Entity.entity(requestGenerationBody, MediaType.APPLICATION_JSON_TYPE)
            );

    assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
    verify(appender, Mockito.times(2)).doAppend(loggingEventArgumentCaptor.capture());

    // Resource should have added 4 items and then removed them from the MDC, leaving anything that was there previously
    assertThat(loggingEventArgumentCaptor.getValue().getMDCPropertyMap().size()).isEqualTo(mdcPropertyMapSizeBeforeCall + 4);
    assertThat(MDC.get("testMDCKey")).isEqualTo("testMDCValue");

}
 
Example #23
Source File: BrokerMemoryLoggerImpl.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context context)
{
    if (_logRecorder != null)
    {
        throw new IllegalStateException("RecordEventAppender is already created");
    }
    RecordEventAppender appender =  new RecordEventAppender(getMaxRecords());
    _logRecorder = new LogRecorder(appender);
    return appender;
}
 
Example #24
Source File: LogConfigurator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void end(InterpretationContext ec, String arg1) {
	Object o = ec.peekObject();
	if (o != className) {
		addWarn("The object on the top the of the stack is not the logreader classname pushed earlier.");
	} else {
		ec.popObject();
		Appender<?> appender = (Appender<?>) ec.peekObject();
		logReaderClassNames.put(appender.getName(), className);
		appenders.put(appender.getName(), appender);
		if (def) {
			defaultAppender = appender.getName();
		}
	}
}
 
Example #25
Source File: GenerateAuthnRequestResourceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldLogAuthnRequestAttributesToMDC() throws Exception {
    Logger logger = (Logger) LoggerFactory.getLogger(AuthnRequestAttributesHelper.class);
    Appender<ILoggingEvent> appender = mock(Appender.class);
    logger.addAppender(appender);

    when(authnRequestFactory.build(any())).thenReturn(authnRequest);
    RequestGenerationBody requestGenerationBody = new RequestGenerationBody(LevelOfAssurance.LEVEL_2, null);

    Response response =
            resources.target(GENERATE_REQUEST_RESOURCE_PATH).request().post(
                    Entity.entity(requestGenerationBody, MediaType.APPLICATION_JSON_TYPE)
            );
    assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());

    ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    verify(appender).doAppend(loggingEventArgumentCaptor.capture());

    ILoggingEvent loggingEvent = loggingEventArgumentCaptor.getValue();
    Map<String, String> mdcPropertyMap = loggingEvent.getMDCPropertyMap();


    assertThat(loggingEvent.getMessage()).contains(AUTHN_REQUEST_ATTRIBUTES_LOG_MESSAGE);

    assertThat(mdcPropertyMap.get(AuthnRequestAttibuteNames.REQUEST_ID)).isEqualTo(TEST_REQUEST_ID);
    assertThat(mdcPropertyMap.get(AuthnRequestAttibuteNames.DESTINATION)).isEqualTo(TEST_DESTINATION);
    assertThat(mdcPropertyMap.get(AuthnRequestAttibuteNames.ISSUE_INSTANT)).isEqualTo(TEST_ISSUE_INSTANT);
    assertThat(mdcPropertyMap.get(AuthnRequestAttibuteNames.ISSUER)).isEqualTo(TEST_ISSUER);
}
 
Example #26
Source File: KonkerLogger.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public synchronized void addAppender(Appender<ILoggingEvent> newAppender) {
    if(this.aai == null) {
        this.aai = new AppenderAttachableImpl();
    }

    this.aai.addAppender(newAppender);
}
 
Example #27
Source File: AsyncAppender.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private AsyncAppender(Appender<ILoggingEvent> delegate) {
    this.delegate = delegate;
    this.queue = Queues.newLinkedBlockingQueue();
    this.batch = Lists.newArrayListWithCapacity(BATCH_SIZE);
    this.dispatcher = THREAD_FACTORY.newThread(this);
    setContext(delegate.getContext());
}
 
Example #28
Source File: JDBCLoggerHelperTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void createAppenderInstance()
{
    final LoggerContext context = ROOT_LOGGER.getLoggerContext();
    final Appender<ILoggingEvent> appender =
            _jdbcLoggerHelper.createAppenderInstance(context, _broker, _jdbcSettings);
    assertTrue(appender instanceof DBAppender);
    assertTrue(appender.isStarted());
    assertEquals(context, appender.getContext());
    assertTrue(((DBAppender) appender).getConnectionSource() instanceof JDBCSettingsDrivenConnectionSource);
}
 
Example #29
Source File: FileLocationProvider.java    From gocd with Apache License 2.0 5 votes vote down vote up
private Appender[] getAppenders(List<Logger> loggers) {
    LinkedHashSet<Appender<ILoggingEvent>> appenders = new LinkedHashSet<>();

    for (Logger logger : loggers) {
        Iterator<Appender<ILoggingEvent>> appenderIterator = logger.iteratorForAppenders();
        while (appenderIterator.hasNext()) {
            Appender<ILoggingEvent> appender = appenderIterator.next();
            appenders.add(appender);
        }
    }
    return appenders.toArray(new Appender[0]);
}
 
Example #30
Source File: BaleenConsoleLoggerBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Build a new appender that will log to the console
 *
 * @param context The logger context (not used by this logger)
 * @param encoder The encoder to use (if that is possible for the specific appender)
 * @return The new console-based log appender
 */
@Override
protected Appender<ILoggingEvent> createAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
  appender.setEncoder(encoder);
  return appender;
}