Java Code Examples for ch.qos.logback.core.Appender

The following examples show how to use ch.qos.logback.core.Appender. 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
@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 2
Source Project: tutorials   Source File: WebClientLoggingIntegrationTest.java    License: 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 3
Source Project: uavstack   Source File: LogBackHookProxy.java    License: 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 4
Source Project: flair-registry   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();

    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 5
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 6
Source Project: logging-java   Source File: LoggingConfigurator.java    License: 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 7
Source Project: qpid-broker-j   Source File: BrokerFileLoggerImpl.java    License: 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 8
Source Project: gocd   Source File: FileLocationProvider.java    License: 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 9
Source Project: cubeai   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();

    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 10
Source Project: cubeai   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();

    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 11
Source Project: gocd   Source File: DefaultPluginLoggingServiceTest.java    License: 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 12
Source Project: cubeai   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();

    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: cubeai   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();

    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 14
Source Project: logging-java   Source File: LoggingConfigurator.java    License: 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 15
/**
 * 
 * @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 16
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 17
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 18
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
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 20
Source Project: ehcache3-samples   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();

    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 Project: tddl   Source File: DynamicLogbackLogger.java    License: 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 22
@Override
public Appender build(LoggerContext context, String s, LayoutFactory layoutFactory,
                      LevelFilterFactory levelFilterFactory,
                      AsyncAppenderFactory asyncAppenderFactory) {
  final LogstashTcpSocketAppender appender = new LogstashTcpSocketAppender();
  final LogstashEncoder encoder = new LogstashEncoder();

  appender.setName("logstash-tcp-appender");
  appender.setContext(context);
  appender.addDestinations(new InetSocketAddress(host, port));
  appender.setIncludeCallerData(includeCallerData);
  appender.setQueueSize(queueSize);

  encoder.setIncludeContext(includeContext);
  encoder.setIncludeMdc(includeMdc);
  encoder.setIncludeCallerData(includeCallerData);

  if (customFields != null) {
    LogstashAppenderFactoryHelper
        .getCustomFieldsFromHashMap(customFields)
        .ifPresent(encoder::setCustomFields);
  }

  if (fieldNames != null) {
    encoder.setFieldNames(LogstashAppenderFactoryHelper.getFieldNamesFromHashMap(fieldNames));
  }

  appender.setEncoder(encoder);
  appender.addFilter(levelFilterFactory.build(threshold));
  encoder.start();
  appender.start();

  return wrapAsync(appender, asyncAppenderFactory);
}
 
Example 23
Source Project: qpid-broker-j   Source File: JDBCLoggerHelper.java    License: Apache License 2.0 5 votes vote down vote up
void restartConnectionSourceIfExists(final Appender appender)
{
    if (appender instanceof DBAppender)
    {
        final ConnectionSource connectionSource = ((DBAppender) appender).getConnectionSource();
        if (connectionSource != null)
        {
            connectionSource.stop();
            connectionSource.start();
        }
    }
}
 
Example 24
Source Project: synopsys-detect   Source File: DiagnosticLogSystem.java    License: Apache License 2.0 5 votes vote down vote up
private void restrictConsoleToDebug() {
    for (final Iterator<Appender<ILoggingEvent>> it = DiagnosticLogUtil.getRootLogger().iteratorForAppenders(); it.hasNext(); ) {
        final Appender appender = it.next();
        if (appender.getName() != null && appender.getName().equals("CONSOLE")) {
            final ThresholdFilter levelFilter = new ThresholdFilter();
            levelFilter.setLevel(Level.DEBUG.levelStr);
            levelFilter.start();
            appender.addFilter(levelFilter);
        }
    }
}
 
Example 25
@Test(timeout = 5000)
public void test_first_time_gets_modified_to_debug() throws Exception {
    final String msg = "Can't open directory channel. Log directory fsync won't be performed.";

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final Iterator<Appender<ILoggingEvent>> appenderIterator = rootLogger.iteratorForAppenders();

    while (appenderIterator.hasNext()) {

        appenderIterator.next().addFilter(createFilter(countDownLatch, msg));
    }
    XodusFileDataWriterLogLevelModificator.fileDataWriterLogger.warn(msg);

    assertEquals(true, countDownLatch.await(5, TimeUnit.SECONDS));
}
 
Example 26
Source Project: qpid-broker-j   Source File: JDBCBrokerLoggerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(final Context context)
{
    final SystemConfig<?> systemConfig = getAncestor(SystemConfig.class);
    _logbackStatusListener = new BrokerLoggerStatusListener(this,
                                                            systemConfig,
                                                            BROKER_FAIL_ON_JDBC_LOGGER_ERROR,
                                                            SQLException.class);
    _statusManager = context.getStatusManager();
    _statusManager.add(_logbackStatusListener);

    return _jdbcLoggerHelper.createAppenderInstance(context, this, this);
}
 
Example 27
Source Project: spring-boot-data-geode   Source File: CompositeAppender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Composes an array of {@link Appender Appenders} into a {@link CompositeAppender}.
 *
 * This operation is null-safe.
 *
 * @param <T> {@link Class type} of the logging events processed by the {@link Appender Appenders}.
 * @param appenders array of {@link Appender Appenders} to compose; may be {@literal null}.
 * @return a composition of the array of {@link Appender Appenders}; returns {@literal null} if the array is empty.
 * @see #compose(Iterable)
 */
@SuppressWarnings("unchecked")
public static <T> Appender<T> compose(Appender<T>... appenders) {

	List<Appender<T>> resolvedAppenders = appenders != null
		? Arrays.asList(appenders)
		: Collections.emptyList();

	return compose(resolvedAppenders);

}
 
Example 28
Source Project: spring-cloud-task   Source File: TestVerifierUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a mock {@link Appender} to be added to the root logger.
 * @return reference to the mock appender.
 */
public static Appender getMockAppender() {
	ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
			.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
	final Appender mockAppender = mock(Appender.class);
	when(mockAppender.getName()).thenReturn("MOCK");
	root.addAppender(mockAppender);
	return mockAppender;
}
 
Example 29
Source Project: netty-4.1.22   Source File: LoggingHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    for (Iterator<Appender<ILoggingEvent>> i = rootLogger.iteratorForAppenders(); i.hasNext();) {
        Appender<ILoggingEvent> a = i.next();
        oldAppenders.add(a);
        rootLogger.detachAppender(a);
    }

    Unpooled.buffer();
}
 
Example 30
@Test
public void buildAndStartStringAppender() {

	Context mockContext = mock(Context.class);

	DelegatingAppender delegate = spy(new DelegatingAppender());

	Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

	StringAppender stringAppender = new StringAppender.Builder()
		.applyTo(delegate)
		.applyTo(rootLogger)
		.setContext(mockContext)
		.setName("TestStringAppender")
		.useSynchronization()
		.buildAndStart();

	assertThat(stringAppender).isNotNull();
	assertThat(stringAppender.isStarted()).isTrue();
	assertThat(stringAppender.getContext()).isEqualTo(mockContext);
	assertThat(stringAppender.getName()).isEqualTo("TestStringAppender");
	assertThat(stringAppender.getStringAppenderWrapper())
		.isInstanceOf(StringAppender.StringBufferAppenderWrapper.class);
	assertThat(rootLogger.getAppender("TestStringAppender")).isEqualTo(stringAppender);

	verify(delegate, times(1)).setAppender(isA(CompositeAppender.class));

	Appender compositeAppender = delegate.getAppender();

	assertThat(compositeAppender).isInstanceOf(CompositeAppender.class);
	assertThat(((CompositeAppender) compositeAppender).getAppenderOne()).isEqualTo(DelegatingAppender.DEFAULT_APPENDER);
	assertThat(((CompositeAppender) compositeAppender).getAppenderTwo()).isEqualTo(stringAppender);
}