ch.qos.logback.classic.spi.ILoggingEvent Java Examples

The following examples show how to use ch.qos.logback.classic.spi.ILoggingEvent. 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: DiagnosticLogger.java    From synopsys-detect with Apache License 2.0 7 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 #2
Source File: JDBCLoggerHelper.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
Appender<ILoggingEvent> createAppenderInstance(final Context context,
                                               final ConfiguredObject<?> logger,
                                               final JDBCSettings settings)
{
    try
    {
        final JDBCSettingsDBNameResolver dbNameResolver = new JDBCSettingsDBNameResolver(settings);
        final ConnectionSource connectionSource = createConnectionSource(context, logger, settings);
        final DBAppender appender = new DBAppender();
        appender.setDbNameResolver(dbNameResolver);
        appender.setConnectionSource(connectionSource);
        appender.setContext(context);
        appender.start();
        return appender;
    }
    catch (Exception e)
    {
        LOGGER.error("Failed to create appender", e);
        throw new IllegalConfigurationException("Cannot create appender");
    }
}
 
Example #3
Source File: LogbackLoggingConfigurer.java    From pushfish-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 #4
Source File: PeriodicalHealthChecksTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void startShouldLogPeriodicallyWhenDegraded() {
    ListAppender<ILoggingEvent> loggingEvents = getListAppenderForClass(PeriodicalHealthChecks.class);

    TestingHealthCheck degraded = () -> Mono.just(Result.degraded(TestingHealthCheck.COMPONENT_NAME, "cause"));
    testee = new PeriodicalHealthChecks(ImmutableSet.of(degraded),
        scheduler,
        new PeriodicalHealthChecksConfiguration(PERIOD));
    testee.start();

    scheduler.advanceTimeBy(PERIOD);
    assertThat(loggingEvents.list).hasSize(1)
        .allSatisfy(loggingEvent -> {
            assertThat(loggingEvent.getLevel()).isEqualTo(Level.WARN);
            assertThat(loggingEvent.getFormattedMessage()).contains("DEGRADED", "testing", "cause");
        });
}
 
Example #5
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 #6
Source File: ErrorStatisticsAppender.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    if (event == null) {
        return;
    }
    if (event.getLevel() == Level.ERROR || event.getLevel() == Level.WARN) {
        IThrowableProxy throwableProxy = event.getThrowableProxy();
        if (throwableProxy != null) {
        	//接口名
            String errorClassName = throwableProxy.getClassName();
            if (errorClassName != null && !"".equals(errorClassName.trim())) {
            	//写入AtomicLongMap并计数
                ERROR_NAME_VALUE_MAP.getAndIncrement(errorClassName);
            }
        }
    }
}
 
Example #7
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 #8
Source File: Minister.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 初始化日志
 */
private Logger initLog(Integer id) {
    // 实例化log,每个实例存放地方不一致
    ch.qos.logback.classic.Logger logger = ((ch.qos.logback.classic.Logger)
            LoggerFactory.getLogger(this.secretary.strategyName + "-" + id));

    LoggerContext context = logger.getLoggerContext();

    TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>();
    policy.setFileNamePattern(OptionHelper.substVars(
            "logs/past/" + id + "/%d{yyyy-MM-dd}.log.gz", context));
    policy.setMaxHistory(31);
    policy.setContext(context);

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(context);
    encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %5level - [%thread] %logger : %msg%n");

    RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    appender.setContext(context);
    appender.setName(this.secretary.strategyName + "-" + id);
    appender.setFile(OptionHelper.substVars("logs/" + id + "/log.log", context));
    appender.setAppend(true);
    // 同一文件多输入完整检查
    appender.setPrudent(false);
    appender.setRollingPolicy(policy);
    appender.setEncoder(encoder);
    policy.setParent(appender);

    policy.start();
    encoder.start();
    appender.start();

    logger.setLevel(Level.INFO);
    // 终端输出
    logger.setAdditive(true);
    logger.addAppender(appender);

    return logger;
}
 
Example #9
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 #10
Source File: LogbackFactory.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public static ConsoleAppender<ILoggingEvent> buildConsoleAppender(LoggingConfiguration.ConsoleConfiguration console,
                                                                  LoggerContext context,
                                                                  String logFormat) {
    final LogFormatter formatter = new LogFormatter(context, console.getTimeZone());
    if (logFormat != null) {
        formatter.setPattern(logFormat);
    }
    formatter.start();

    final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    appender.setContext(context);
    appender.setLayout(formatter);
    addThresholdFilter(appender, console.getThreshold());
    appender.start();

    return appender;
}
 
Example #11
Source File: DiagnosticLogger.java    From hub-detect with 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();
    FileAppender<ILoggingEvent> appender;
    appender = new FileAppender<>();
    appender.setFile(file);
    appender.setEncoder(ple);
    appender.setContext(lc);
    appender.start();

    final ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LOGBACK_LOGGER_NAME);
    logbackLogger.addAppender(appender);
    logbackLogger.setLevel(Level.ALL);

    return appender;
}
 
Example #12
Source File: FlumeLogstashV1Appender.java    From logback-flume-appender with MIT License 6 votes vote down vote up
@Override
protected void append(ILoggingEvent eventObject) {

  if (flumeManager != null) {
    try {
      String body = layout != null ? layout.doLayout(eventObject) : eventObject.getFormattedMessage();
      Map<String, String> headers = new HashMap<String, String>();
      if(additionalAvroHeaders != null) {
        headers.putAll(additionalAvroHeaders);
      }
      headers.putAll(extractHeaders(eventObject));

      Event event = EventBuilder.withBody(StringUtils.strip(body), UTF_8, headers);

      flumeManager.send(event);
    } catch (Exception e) {
      addError(e.getLocalizedMessage(), e);
    }
  }

}
 
Example #13
Source File: LoggerThresholdFilter.java    From logging-java with Apache License 2.0 6 votes vote down vote up
@Override
public FilterReply decide(ILoggingEvent event) {
    if(!isStarted())
        return FilterReply.NEUTRAL;

    if(logger != null && !event.getLoggerName().startsWith(logger))
        return FilterReply.NEUTRAL;

    if(exceptLogger != null && event.getLoggerName().startsWith(exceptLogger))
        return FilterReply.NEUTRAL;

    if(level != null && !event.getLevel().isGreaterOrEqual(level))
        return FilterReply.DENY;

    return FilterReply.NEUTRAL;
}
 
Example #14
Source File: AbstractLogger.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected void postResolveChildren()
{
    super.postResolveChildren();

    LoggerContext loggerContext = ROOT_LOGGER.getLoggerContext();
    Appender<ILoggingEvent> appender = createAppenderInstance(loggerContext);
    appender.setName(getName());
    appender.setContext(loggerContext);

    for(LogInclusionRule logInclusionRule : getLogInclusionRules())
    {
        _compositeFilter.addLogInclusionRule((LogBackLogInclusionRule)logInclusionRule);
    }
    appender.addFilter(_compositeFilter);

    ROOT_LOGGER.addAppender(appender);
    appender.start();

    // TODO generalise for virtualhost too
    StartupAppender startupAppender = (StartupAppender) ROOT_LOGGER.getAppender(StartupAppender.class.getName());
    if (startupAppender != null)
    {
        startupAppender.replayAccumulatedEvents(appender);
    }
}
 
Example #15
Source File: LoggingFilter.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
@Override
public FilterReply decide(ILoggingEvent event) {
	final IThrowableProxy throwableProxy = event.getThrowableProxy();
	if (throwableProxy == null) {
		return FilterReply.NEUTRAL;
	}

	if (!(throwableProxy instanceof ThrowableProxy)) {
		return FilterReply.NEUTRAL;
	}

	final ThrowableProxy throwableProxyImpl = (ThrowableProxy) throwableProxy;
	final Throwable throwable = throwableProxyImpl.getThrowable();
	if (java.nio.channels.ClosedChannelException.class.isInstance(throwable)) {
		return FilterReply.DENY;
	}

	return FilterReply.NEUTRAL;
}
 
Example #16
Source File: XodusFileDataWriterLogLevelModificatorSingularityTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void test_get_only_logged_once() throws Exception {
    final String msg = "Can't open directory channel. Log directory fsync won't be performed.";

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

    final Appender<ILoggingEvent> next = appenderIterator.next();
    next.addFilter(createFilter(countDownLatch, msg));

    XodusFileDataWriterLogLevelModificator.fileDataWriterLogger.warn(msg);
    XodusFileDataWriterLogLevelModificator.fileDataWriterLogger.warn(msg);
    XodusFileDataWriterLogLevelModificator.fileDataWriterLogger.warn(msg);
    XodusFileDataWriterLogLevelModificator.fileDataWriterLogger.warn(msg);
    XodusFileDataWriterLogLevelModificator.fileDataWriterLogger.warn(msg);

    assertEquals(false, countDownLatch.await(3, TimeUnit.SECONDS));
}
 
Example #17
Source File: RequestContextExportingAppender.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(ILoggingEvent eventObject) {
    if (exporter == null) {
        exporter = builder.build();
    }
    final Map<String, String> contextMap = exporter.export();
    if (!contextMap.isEmpty()) {
        final Map<String, String> originalMdcMap = eventObject.getMDCPropertyMap();
        final Map<String, String> mdcMap;

        if (!originalMdcMap.isEmpty()) {
            mdcMap = new UnionMap<>(contextMap, originalMdcMap);
        } else {
            mdcMap = contextMap;
        }
        eventObject = new LoggingEventWrapper(eventObject, mdcMap);
    }
    aai.appendLoopOnAppenders(eventObject);
}
 
Example #18
Source File: LoggerNameAndLevelFilterTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecideForWildcardLoggerName() throws Exception
{
    LoggerNameAndLevelFilter filter = new LoggerNameAndLevelFilter("org.apache.qpid.server.*", Level.INFO);

    ILoggingEvent event = mock(ILoggingEvent.class);
    when(event.getLevel()).thenReturn(Level.INFO);
    when(event.getLoggerName()).thenReturn("org.apache.qpid.server.foo");
    assertEquals("Unexpected reply for matching logger name and log level",
                        FilterReply.ACCEPT,
                        filter.decide(event));

    when(event.getLoggerName()).thenReturn("org.apache.qpid.foo");
    assertEquals("Unexpected reply for non matching logger name but matching log level",
                        FilterReply.NEUTRAL,
                        filter.decide(event));

    when(event.getLoggerName()).thenReturn("org.apache.qpid.server.foo");
    when(event.getLevel()).thenReturn(Level.DEBUG);
    assertEquals("Unexpected reply for matching logger name but non matching log level",
                        FilterReply.NEUTRAL,
                        filter.decide(event));
}
 
Example #19
Source File: DingTalkAppender.java    From jframework with Apache License 2.0 6 votes vote down vote up
private String transformStackTrace(ILoggingEvent event) {
    String exception = "";
    IThrowableProxy throwableProxy =  event.getThrowableProxy();
    if (throwableProxy != null) {
        exception = ThrowableProxyUtil.asString(throwableProxy);
    }

    StackTraceElement[] callerData = event.getCallerData();
    StackTraceElement stackTraceElement = callerData[0];

    String time = DEFAULT_DATE_FORMAT.format(new Date(event.getTimeStamp()));
    String threadName = event.getThreadName();
    String level = event.getLevel().toString();
    String logger = event.getLoggerName();
    String msg = event.getFormattedMessage();
    String className = stackTraceElement.getClassName();
    String method = stackTraceElement.getMethodName();
    int lineNumber = stackTraceElement.getLineNumber();

    return String.format(FORMAT_MESSAGE, time, threadName, level, logger, className, method, lineNumber, exception, msg);
}
 
Example #20
Source File: ContainerLogger.java    From skywalking with Apache License 2.0 6 votes vote down vote up
public ContainerLogger(final Path logDirectory, final String container) {

        final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        final PatternLayoutEncoder encoder = new PatternLayoutEncoder();

        encoder.setPattern("%d{HH:mm:ss.SSS} %-5level %logger{36}.%M - %msg%n");
        encoder.setContext(context);
        encoder.start();

        final FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
        fileAppender.setFile(logDirectory.resolve(container).toAbsolutePath().toString());
        fileAppender.setEncoder(encoder);
        fileAppender.setContext(context);
        fileAppender.start();

        final ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(container);
        logger.addAppender(fileAppender);
        logger.setLevel(Level.DEBUG);
        logger.setAdditive(false);

        this.delegate = logger;
    }
 
Example #21
Source File: ViewAppender.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void append (ILoggingEvent event)
{
    if (!isReady()) {
        backlog.add(event);
    } else {
        if (!backlog.isEmpty()) {
            for (ILoggingEvent evt : backlog) {
                publish(evt);
            }

            backlog.clear();
        }

        publish(event);
    }
}
 
Example #22
Source File: LogService.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public List<FileAppender<ILoggingEvent>> getFileAppenders() {
	List<FileAppender<ILoggingEvent>> fileAppenders = new LinkedList<FileAppender<ILoggingEvent>>();

	for (Logger logger : getLoggers()) {
		for (Iterator<Appender<ILoggingEvent>> index = logger
				.iteratorForAppenders(); index.hasNext();) {

			Appender<ILoggingEvent> appender = index.next();
			if (appender instanceof FileAppender)
				fileAppenders.add((FileAppender<ILoggingEvent>) appender);
		}
	}

	return fileAppenders;
}
 
Example #23
Source File: LogWatcher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public List<ILoggingEvent> assertHasEvent(final Predicate<? super ILoggingEvent> filter) {
    synchronized (events) {
        Iterable<ILoggingEvent> filtered = Iterables.filter(events, filter);
        assertFalse(Iterables.isEmpty(filtered), "events="+events);
        return ImmutableList.copyOf(filtered);
    }
}
 
Example #24
Source File: ConfigKeyDeprecationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogsWarningIfMultipleDeprecatedNamesUsed() throws Exception {
    String loggerName = ConfigUtilsInternal.class.getName();
    ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.WARN;
    Predicate<ILoggingEvent> filter = EventPredicates.containsMessages(
            "Using deprecated config value on MyBaseEntity",
            "should use 'superKey1', but used 'oldSuperKey1b' and ignored values present for other deprecated name(s) [oldSuperKey1b]");

    try (LogWatcher watcher = new LogWatcher(loggerName, logLevel, filter)) {
        testPrefersFirstDeprecatedNameIfMultiple();
        watcher.assertHasEvent();
    }
}
 
Example #25
Source File: PredicateAndLoggerNameAndLevelFilter.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
protected Filter<ILoggingEvent> createFilter(final String loggerName)
{
    final Filter<ILoggingEvent> filter = super.createFilter(loggerName);
    return new Filter<ILoggingEvent>()
    {
        @Override
        public FilterReply decide(final ILoggingEvent event)
        {
            final FilterReply result = filter.decide(event);
            if (result == FilterReply.ACCEPT)
            {
                if (_predicate.evaluate(event))
                {
                    return FilterReply.ACCEPT;
                }
                else
                {
                    return FilterReply.NEUTRAL;
                }
            }
            else
            {
                return result;
            }
        }
    };
}
 
Example #26
Source File: LoggerUtil.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static void setLogLevel(final ConsoleAppender<ILoggingEvent> consoleAppender,
        final Level level, final String clazz) {
    final ch.qos.logback.classic.Logger protocolLogger
            = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(clazz);
    protocolLogger.addAppender(consoleAppender);
    protocolLogger.setLevel(level);
    protocolLogger.setAdditive(false);
}
 
Example #27
Source File: GtfsLoggingAppender.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Logs WARN and ERROR level messages
 * @see ch.qos.logback.core.AppenderBase#append(java.lang.Object)
 */
@Override
protected void append(ILoggingEvent event) {
	Level level = event.getLevel();
	if (level == Level.WARN) {
		warnings.add(event.getFormattedMessage());
	} else if (level == Level.ERROR) {
		errors.add(event.getFormattedMessage());
	}
}
 
Example #28
Source File: ConnectionAndUserPredicateTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvaluateConnectionNameForAmqp()
{
    AMQPConnection connection = mock(AMQPConnection.class);
    when(connection.getRemoteAddressString()).thenReturn("foo:1234");
    when(connection.getRemoteContainerName()).thenReturn(null);
    _subject.getPrincipals().add(new ConnectionPrincipal(connection));
    _predicate.setConnectionNamePattern(".*:1234");
    Subject.doAs(_subject, new PrivilegedAction<Void>()
    {
        @Override
        public Void run()
        {
            assertTrue("predicate unexpectedly did not match",
                              _predicate.evaluate(mock(ILoggingEvent.class)));
            return null;
        }
    });
    _predicate.setConnectionNamePattern(".*:4321");
    Subject.doAs(_subject, new PrivilegedAction<Void>()
    {
        @Override
        public Void run()
        {
            assertFalse("predicate unexpectedly matched", _predicate.evaluate(mock(ILoggingEvent.class)));
            return null;
        }
    });
}
 
Example #29
Source File: BugsnagAppender.java    From bugsnag-java with MIT License 5 votes vote down vote up
/**
 * Adds logging context values to the given report meta data
 *
 * @param report The report being sent to Bugsnag
 * @param event The logging event
 */
private void populateContextData(Report report, ILoggingEvent event) {
    Map<String, String> propertyMap = event.getMDCPropertyMap();

    if (propertyMap != null) {
        // Loop through all the keys and put them in the correct tabs

        for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
            report.addToTab("Context", entry.getKey(), entry.getValue());
        }
    }
}
 
Example #30
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    try {
        ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
        Throwable throwable = throwableProxy == null ? null : throwableProxy.getThrowable();
        String message = event.getFormattedMessage();
        LogLevel level = LogLevelConverter.toGradleLogLevel(event.getLevel(), event.getMarker());
        outputEventListener.onOutput(new LogEvent(event.getTimeStamp(), event.getLoggerName(), level, message, throwable));
    } catch (Throwable t) {
        // fall back to standard out
        t.printStackTrace(defaultStandardOut);
    }
}