Java 类ch.qos.logback.classic.spi.ILoggingEvent 实例源码

项目:kafka-logback    文件:CustomJsonLayout.java   
@Override
protected void addCustomDataToJsonMap(Map<String, Object> map, ILoggingEvent event) {
    add(HOST, includeHost, HOST_NAME, map);
    if (event.hasCallerData()) {
        StackTraceElement callerData = event.getCallerData()[0];
        addLine(LINE_NUMBER, includeLineNumber, callerData.getLineNumber(), map);
        add(CLASS_NAME, includeClassName, callerData.getClassName(), map);
        add(METHOD_NAME, includeMethodName, callerData.getMethodName(), map);
        add(FILE_NAME, includeFileName, callerData.getFileName(), map);
    }

    if (additionalFields != null) {
        additionalFields.forEach(field -> {
            String[] p = field.split("\\|");
            if (p.length == 2) {
                add(p[0], true, p[1], map);
            } else {
                addWarn("Unable to parse property string: " + field);
            }
        });
    }
}
项目:TOSCAna    文件:MemoryAppender.java   
private void appendThrowable(IThrowableProxy proxy, ILoggingEvent loggingEvent) {
    //Append Exception Message
    appendToLog(loggingEvent, String.format("%s: %s", proxy.getClassName(), proxy.getMessage()));
    //Append Exception Stack Trace
    for (StackTraceElementProxy element : loggingEvent.getThrowableProxy().getStackTraceElementProxyArray()) {
        appendToLog(loggingEvent, "\t" + element.getSTEAsString());
    }
    if (proxy.getSuppressed().length > 0) {
        appendToLog(loggingEvent, "Suppressed Exceptions:");
        for (IThrowableProxy p : proxy.getSuppressed()) {
            appendThrowable(p, loggingEvent);
        }
    }
    if (proxy.getCause() != null) {
        appendToLog(loggingEvent, "Cause:");
        appendThrowable(proxy.getCause(), loggingEvent);
    }
}
项目:escalog    文件:LogFmtLayoutTest.java   
@Test
public void fieldsConfigTest()
{
    LogFmtLayout logFmtLayout = new LogFmtLayout();
    logFmtLayout.setFields("time, mdc, custom, level, msg");
    logFmtLayout.setTimeFormat("YYYY");

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, Calendar.NOVEMBER, 30, 15, 10, 25);

    Map<String, String> mdc = new HashMap<>();
    mdc.put("mdckey", "mdc value");

    ILoggingEvent loggingEvent = createLoggingEvent("thread0", Level.DEBUG, calendar.getTime(),
        with("key1", "value1").and("key2", "val ue2"), "message with \"double quotes\"", mdc);

    assertEquals(
        "time=2017 mdckey=\"mdc value\" key1=value1 key2=\"val ue2\" level=debug msg=\"message with \\\"double quotes\\\"\"\n",
        logFmtLayout.doLayout(loggingEvent)
    );
}
项目:mongo-trek    文件:MongoTrekIntegrationTest.java   
@Test
public void shouldReportOnMigrations() throws MongoTrekFailureException {
    MongoTrek migrations = new MongoTrek("fixtures/last-failure-migrations.yml", this.database);
    migrations.setSchemaVersionCollection(SCHEMA_VERSION_COLLECTION);
    migrations.status();

    verify(appender, atLeastOnce()).doAppend(captor.capture());
    List<ILoggingEvent> events = captor.getAllValues();
    assertThat(events).areAtLeastOne(loggedMessage("DATABASE MIGRATIONS"))
            .areAtLeastOne(loggedMessage("       Database : [ migration_test ]"))
            .areAtLeastOne(loggedMessage(" Schema Version : [ _schema_version ]"))
            .areAtLeastOne(loggedMessage("         Action : [ status ]"))
            .areAtLeastOne(loggedMessage("Current Version : [ 1.0.1 ]"))
            .areAtLeastOne(loggedMessage("     Migrations :"))
            .areAtLeastOne(loggedMessage("       1.0.0 : Applied migration"))
            .areAtLeastOne(loggedMessage(String.format("          Tags: [ Successful ] [ %s ] [ 2 seconds ]", toTimeStamp("2014-12-05T09:00:00+1100"))))
            .areAtLeastOne(loggedMessage("       1.0.1 : Another applied migration"))
            .areAtLeastOne(loggedMessage(String.format("          Tags: [ Successful ] [ %s ] [ 60 seconds ]", toTimeStamp("2014-12-05T09:10:00+1100"))))
            .areAtLeastOne(loggedMessage("       1.0.2 : Failed last time migration"))
            .areAtLeastOne(loggedMessage(String.format("          Tags: [ Failed ] [ %s ] [ ERROR: Something went horribly wrong! ]", toTimeStamp("2014-12-05T09:11:01+1100"))))
            .areAtLeastOne(loggedMessage("       2.0.0 : Brand new migration"))
            .areAtLeastOne(loggedMessage("          Tags: [ Pending ]"))
            .areAtLeastOne(loggedMessage("       2.0.0.1 : I will always fail"))
            .areAtLeastOne(loggedMessage("          Tags: [ Pending ]"));
}
项目:cdp4j    文件:TestAll.java   
@BeforeClass
@SuppressWarnings("unchecked")
public static void init() {
    loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    appender = new CdpAppender();
    appender.setContext(loggerContext);
    appender.start();
    appender.setName(CdpAppender.class.getName());

    Logger logger = loggerContext.getLogger("cdp4j.flow");
    logger.addAppender((Appender<ILoggingEvent>) appender);

    factory = new Launcher().launch();

    session = factory.create();

    session.enableConsoleLog();

    URL url = TestAll.class.getResource("/session-test.html");
    session.navigate(url.toString());
}
项目:escalog    文件:LogFmtTest.java   
@Before
public void init()
{
    LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();

    ctx.reset();

    this.layoutProducer = new LayoutProducer();
    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
    appender.setLayout(layoutProducer);
    appender.setContext(ctx);
    appender.start();

    Logger basicLogger = ctx.getLogger(LogFmtTest.class);
    basicLogger.addAppender(appender);
    this.logger = LogFmt.from(basicLogger);

    ctx.start();
}
项目:rocketmq-rocketmq-all-4.1.0-incubating    文件:RocketmqLogbackAppender.java   
/**
 * Info,error,warn,callback method implementation
 *
 * @param event
 */
@Override
protected void append(ILoggingEvent event) {
    if (!isStarted()) {
        return;
    }
    String logStr = this.layout.doLayout(event);
    try {
        Message msg = new Message(topic, tag, logStr.getBytes());
        msg.getProperties().put(ProducerInstance.APPENDER_TYPE, ProducerInstance.LOGBACK_APPENDER);

        //Send message and do not wait for the ack from the message broker.
        producer.sendOneway(msg);
    } catch (Exception e) {
        addError("Could not send message in RocketmqLogbackAppender [" + name + "]. Message is : " + logStr, e);
    }
}
项目:qualitoast    文件:LoggingConfiguration.java   
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();
            }
        }
    }
}
项目:minijax    文件:CloudWatchAppenderTest.java   
@Test
public void testGettersSetters() {
    @SuppressWarnings("unchecked")
    final Layout<ILoggingEvent> layout = mock(Layout.class);
    final AWSLogs awsLogs = mock(AWSLogs.class);
    final String logGroupName = "myGroup";
    final String logStreamName = "myStream";

    final CloudWatchAppender appender = new CloudWatchAppender();
    appender.setLayout(layout);
    appender.setAwsLogs(awsLogs);
    appender.setLogGroupName(logGroupName);
    appender.setLogStreamName(logStreamName);

    assertEquals(layout, appender.getLayout());
    assertEquals(awsLogs, appender.getAwsLogs());
    assertEquals(logGroupName, appender.getLogGroupName());
    assertEquals(logStreamName, appender.getLogStreamName());
}
项目:ja-micro    文件:SixtJsonEncoderTest.java   
@Test
public void overrideLogLevelProvider() {
    SixtJsonEncoder encoder = new SixtJsonEncoder();
    JsonProviders<ILoggingEvent> providers = encoder.getProviders();
    int defaultCount = 0;
    int overrideCount = 0;

    for (JsonProvider<ILoggingEvent> provider : providers.getProviders()) {
        if (provider instanceof LogLevelJsonProvider &&
                !(provider instanceof CustomLogLevelJsonProvider)) {
            defaultCount++;
        } else if (provider instanceof CustomLogLevelJsonProvider) {
            overrideCount++;
        }
    }
    assertThat(defaultCount).isEqualTo(0);
    assertThat(overrideCount).isEqualTo(1);
}
项目:codemotion-2017-taller-de-jhipster    文件:LoggingConfiguration.java   
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();
            }
        }
    }
}
项目:logcapture    文件:VerificationExceptionShould.java   
@Test
public void containLogsEventsNotMatchingExpected() {
  ExpectedLoggingMessage expectedLogMessage = aLog().info().withMessage("a log message");
  List<ILoggingEvent> logEvents = Arrays.asList(
    aLoggingEventWith(Level.INFO, "a different message"),
    aLoggingEventWith(Level.INFO, "another different message")
  );

  VerificationException verificationException = VerificationException.forUnmatchedLog(expectedLogMessage, logEvents);

  assertThat(verificationException.toString()).isEqualTo("com.logcapture.assertion.VerificationException: Expected at least one log matching: \n" +
    "ExpectedLoggingMessage{logLevelMatcher=<INFO>, expectedMessageMatcher=[\"a log message\"], expectedMdc={}}\n" +
    "Logs received: \n" +
    "level: INFO marker: null mdc: {} message: a different message\n" +
    "level: INFO marker: null mdc: {} message: another different message");
}
项目:logcapture    文件:VerificationExceptionShould.java   
@Test
public void containLogsEventsNotMatchingExpectedWithMdcKeys() {
  Map<String, String> mdcKeys = new HashMap<String, String>() {{
    put("aKey", "aValue");
    put("anotherKey", "anotherValue");
  }};

  ExpectedLoggingMessage expectedLogMessage = aLog().info()
    .withMessage("a log message")
    .withMdc("aKey", equalTo("aValue"))
    .withMdc("anotherKey", equalTo("anotherValue"));

  List<ILoggingEvent> logEvents = Arrays.asList(
    aLoggingEventWith(Level.INFO, "a different message", mdcKeys),
    aLoggingEventWith(Level.INFO, "another different message", mdcKeys)
  );

  VerificationException verificationException = VerificationException.forUnmatchedLog(expectedLogMessage, logEvents);

  assertThat(verificationException.toString()).isEqualTo("com.logcapture.assertion.VerificationException: Expected at least one log matching: \n" +
    "ExpectedLoggingMessage{logLevelMatcher=<INFO>, expectedMessageMatcher=[\"a log message\"], expectedMdc={anotherKey=\"anotherValue\", aKey=\"aValue\"}}\n" +
    "Logs received: \n" +
    "level: INFO marker: null mdc: {anotherKey=anotherValue, aKey=aValue} message: a different message\n" +
    "level: INFO marker: null mdc: {anotherKey=anotherValue, aKey=aValue} message: another different message");
}
项目:qpp-conversion-tool    文件:AttachmentHashPartConverter.java   
@Override
public String convert(ILoggingEvent event) {
    String hashPart = "";

    try {
        hashPart = getHashPart();
    } catch (Exception e) {
        DEV_LOG.trace("No part to associate with log output.", e);
    }

    return hashPart;
}
项目:escalog    文件:LogFmtLayout.java   
private void errorAppender(StringBuilder sb, ILoggingEvent iLoggingEvent)
{
    if ( iLoggingEvent.getThrowableProxy() != null )
    {
        appendKeyValueAndEscape(sb, ERROR.toString(), ThrowableProxyUtil.asString(iLoggingEvent.getThrowableProxy()));
    }
}
项目:secondbase    文件:SecondBaseLoggerTest.java   
@Test
public void customFieldsShouldBeLogged() throws IOException {
    final ArgumentCaptor<LoggingEvent> captorLoggingEvent = ArgumentCaptor.forClass(
            LoggingEvent.class);

    final LoggerContext loggerContext = SecondBaseLogger.getLoggerContext(
            new String[] {"environment", "service", "datacenter"},
            new String[] {"environment", "service", "datacenter"}
    );
    final Appender<ILoggingEvent> mockAppender = spy(
            SecondBaseLogger.createJsonConsoleAppender(
                    SecondBaseLogger.SERVICE_CONSOLE_APPENDER, loggerContext, true));
    final Logger rootLogger = (Logger) LoggerFactory.getLogger(
            org.slf4j.Logger.ROOT_LOGGER_NAME);
    rootLogger.addAppender(mockAppender);
    final org.slf4j.Logger logger = LoggerFactory.getLogger(SecondBaseLoggerTest.class);
    logger.info("log message");

    verify(mockAppender).doAppend(captorLoggingEvent.capture());

    final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
    final LoggingEventCompositeJsonEncoder encoder = SecondBaseLogger.getEncoder(
            loggerContext, true);
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    encoder.start();
    outputStream.write(encoder.encode(loggingEvent));
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = mapper.readTree(outputStream.toByteArray());

    assertThat(node.get("message").asText(), is("log message"));
    assertThat(node.get("environment").asText(), is("environment"));
    assertThat(node.get("datacenter").asText(), is("datacenter"));
    assertThat(node.get("service").asText(), is("service"));
    assertThat(node.get("level").asText(), is("INFO"));
    assertThat(node.has("timestamp"), is(true));
    assertThat(node.get("type").asText(), is("servicelog"));
    encoder.stop();
    outputStream.close();
}
项目:cloudwatch-logback-appender    文件:CloudWatchAppender.java   
@Override
protected void append(ILoggingEvent loggingEvent) {

    // check wiring
    if (loggingEventQueue == null) {
        if (!warningMessagePrinted) {
            System.err.println(getClass().getSimpleName() + " not wired correctly, ignoring all log messages");
            warningMessagePrinted = true;
        }
        return;
    }

    // skip it if we just went recursive
    Boolean stopped = stopMessagesThreadLocal.get();
    if (stopped == null || !stopped) {
        try {
            if (loggingEvent instanceof LoggingEvent && ((LoggingEvent) loggingEvent).getThreadName() == null) {
                // we need to do this so that the right thread gets set in the event
                ((LoggingEvent) loggingEvent).setThreadName(Thread.currentThread().getName());
            }
            if (!loggingEventQueue.offer(loggingEvent, maxQueueWaitTimeMillis, TimeUnit.MILLISECONDS)) {
                if (emergencyAppender != null) {
                    emergencyAppender.doAppend(loggingEvent);
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
项目:java-logging    文件:ReformLoggingLayout.java   
@Override
public String doLayout(ILoggingEvent event) {
    Instant instant = Instant.ofEpochMilli(event.getTimeStamp());
    ZonedDateTime dateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
    StringBuilder log = new StringBuilder(dateTime.format(dateFormat));

    log.append(String.format(" %-5s", event.getLevel().levelStr));

    if (requireThread) {
        log.append(String.format(" [%s]", event.getThreadName()));
    }

    int lineNumber = event.getCallerData().length > 0 ? event.getCallerData()[0].getLineNumber() : 0;

    log.append(String.format(" %s:%d: ", event.getLoggerName(), lineNumber));

    ThrowableProxy proxy = (ThrowableProxy) event.getThrowableProxy();

    if (requireAlertLevel || requireErrorCode) {
        appendExtraExceptionFlags(log, AbstractLoggingException.getFromThrowableProxy(proxy));
    }

    log.append(event.getFormattedMessage()).append(CoreConstants.LINE_SEPARATOR);

    appendStackTrace(log, proxy);

    if (proxy != null) {
        loopCauses(log, proxy, 0);
    }

    return log.toString();
}
项目:cloudwatch-logback-appender    文件:CloudWatchAppender.java   
@Override
public Appender<ILoggingEvent> getAppender(String name) {
    if (emergencyAppender != null && name != null && name.equals(emergencyAppender.getName())) {
        return emergencyAppender;
    } else {
        return null;
    }
}
项目:cloudwatch-logback-appender    文件:CloudWatchAppender.java   
private void appendToEmergencyAppender(List<ILoggingEvent> events) {
    if (emergencyAppender != null) {
        try {
            for (ILoggingEvent event : events) {
                emergencyAppender.doAppend(event);
            }
        } catch (Exception e) {
            // oh well, we tried
        }
    }
}
项目:secondbase    文件:SecondBaseLoggerTest.java   
@Test
public void shouldSetConsoleAndServiceLayoutAppenders() {
    final boolean json = false;
    SecondBaseLogger.setupLoggingStdoutOnly(KEYS, VALUES, null, json);
    final ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    final Appender<ILoggingEvent> consoleAppender = rootLogger
            .getAppender("SERVICECONSOLEAPPENDER");

    assertThat(consoleAppender, notNullValue());
}
项目:TOSCAna    文件:MemoryAppender.java   
private void appendToLog(ILoggingEvent loggingEvent, String message) {
    log.addLogEntry(
        new LogEntry(
            loggingEvent.getTimeStamp(),
            message,
            loggingEvent.getLevel()
        )
    );
}
项目:json-log-domain    文件:AbstractMatcher.java   
@SuppressWarnings("unchecked")
public boolean matches(Object actual) {
    if (actual instanceof LogbackJUnitRule) {
        LogbackJUnitRule rule = (LogbackJUnitRule) actual;
        if (matches(rule.capture())) {
            return true;
        }
    }

    if (actual instanceof ListAppender) {
        ListAppender<ILoggingEvent> appender = (ListAppender<ILoggingEvent>) actual;

        if (matches(appender.list)) {
            return true;
        }
    }

    if (actual instanceof List) {
        return matches((List<ILoggingEvent>) actual);
    }

    if (actual instanceof ILoggingEvent) {
        return matches((ILoggingEvent) actual);
    }

    return false;
}
项目:json-log-domain    文件:GenericMarkerMatcher.java   
@SuppressWarnings("unchecked")
public boolean matches(Object actual) {
    if(!initalized) {
        init();
        initalized = true;
    }
    if (actual instanceof LogbackJUnitRule) {
        LogbackJUnitRule rule = (LogbackJUnitRule) actual;
        if (matches(rule.capture())) {
            return true;
        }
    }

    if (actual instanceof ListAppender) {
        ListAppender<ILoggingEvent> appender = (ListAppender<ILoggingEvent>) actual;

        if (matches(appender.list)) {
            return true;
        }
    }

    if (actual instanceof List) {
        return matches((List<ILoggingEvent>) actual);
    }

    if (actual instanceof ILoggingEvent) {
        return matches((ILoggingEvent) actual);
    }

    return false;
}
项目:secondbase    文件:SecondBaseLoggerTest.java   
@Test
public void shouldSetConsoleAndServiceAppenders() {
    SecondBaseLogger.setupLoggingStdoutOnly(KEYS, VALUES, null);
    final ch.qos.logback.classic.Logger rootLogger
            = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(
                        org.slf4j.Logger.ROOT_LOGGER_NAME);
    final Appender<ILoggingEvent> consoleAppender = rootLogger.getAppender(
            "SERVICECONSOLEAPPENDER");

    assertThat(consoleAppender, notNullValue());
}
项目:lambda-monitoring    文件:MetricBlockFilter.java   
@Override
public FilterReply decide(ILoggingEvent event) {
    Marker eventMarker = event.getMarker();
    if (isStarted() && eventMarker != null && eventMarker.contains(MetricPassFilter.METRIC_MARKER)) {
        return FilterReply.DENY;
    }
    return FilterReply.NEUTRAL;
}
项目:json-log-domain    文件:MdcMatcher.java   
protected boolean matches(List<ILoggingEvent> appender) {
    for(ILoggingEvent event : appender) {
        if(matches(event)) {
            return true;
        }
    }
    return false;
}
项目:kafka-logback    文件:KafkaAppender.java   
@Override
protected void append(ILoggingEvent event) {
    if (producer != null) {
        try {
            producer.send(new ProducerRecord<>(topic, String.valueOf(Math.random()), layout.doLayout(event))).get();
        } catch (Exception e) {
            addWarn("Unable to send message to Kafka", e);
        }
    }
}
项目:json-log-domain    文件:AbstractMarkerMatcher.java   
public boolean matches(ILoggingEvent event) {
    Marker marker = event.getMarker();
    if(marker != null) {
        return matches(marker);
    }

    return false;
}
项目:json-log-domain    文件:AbstractMarkerMatcher.java   
public boolean matches(Object actual) {
    if (actual instanceof ILoggingEvent) {
        return matches((ILoggingEvent) actual);
    }

    return false;
}
项目:esup-sgc    文件:UserConverter.java   
@Override
public String convert(ILoggingEvent event) {
   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
   if (auth != null) {
        return auth.getName();
   }
   return "NO_USER";
}
项目:json-log-domain    文件:LogbackJUnitRule.java   
public List<ILoggingEvent> capture() {
    if(entries.size() == 1) {
        return entries.get(0).appender.list;
    }
    List<ILoggingEvent> result = new ArrayList<ILoggingEvent>();
    for(Entry entry : entries) {
        result.addAll(entry.appender.list);
    }
    Collections.sort(result, comparator);
    return result;
}
项目:MCBot    文件:StatusChangeFilter.java   
@Override
public FilterReply decide(ILoggingEvent event) {
    if (event.getMessage().contains("changed presence") && event.getLoggerName().equals("sx.blah.discord.Discord4J")) {
        return FilterReply.DENY;
    }
    return FilterReply.NEUTRAL;
}
项目:json-log-domain    文件:LogbackJUnitRule.java   
private  List<ILoggingEvent> filterLevel(List<ILoggingEvent> capture, Level level) {
    List<ILoggingEvent> result = new ArrayList<ILoggingEvent>(capture.size());
    for(int i = 0; i < capture.size(); i++) {
        if(capture.get(i).getLevel().isGreaterOrEqual(level)) {
            result.add(capture.get(i));
        }
    }
    return result;
}
项目:json-log-domain    文件:LogbackJUnitRule.java   
public List<ILoggingEvent> capture(String name) {
    Logger logger = (Logger) LoggerFactory.getLogger(name);

    for(Entry entry : entries) {
        if(entry.logger == logger) {
            return entry.appender.list;
        }
    }

    throw new IllegalArgumentException("Unable to find logger for " + name);
}
项目:NoraUi    文件:OutputConsoleDataProviderUT.java   
@Test
public void testWriteXxxxxResult() throws TechnicalException {
    final OutputConsoleDataProvider outputConsoleDataProvider = new OutputConsoleDataProvider();
    outputConsoleDataProvider.prepare("hello");
    Assert.assertTrue(true);

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

    final TestAppender<ILoggingEvent> appender = new TestAppender<>();
    appender.start();
    logger.addAppender(appender);
    outputConsoleDataProvider.writeFailedResult(1, "UT Failed Message");
    List<ILoggingEvent> log = appender.getLog();
    Assert.assertEquals(Level.ERROR, log.get(0).getLevel());
    Assert.assertTrue(log.get(0).getMessage().toString().endsWith(String.format(Messages.getMessage("OUTPUT_CONSOLE_DATA_PROVIDER_FAILED_AT_LINE"), 1, "UT Failed Message")));

    outputConsoleDataProvider.writeSuccessResult(2);
    log = appender.getLog();
    Assert.assertEquals(Level.INFO, log.get(1).getLevel());
    Assert.assertTrue(log.get(1).getMessage().toString().endsWith(String.format(Messages.getMessage("OUTPUT_CONSOLE_DATA_PROVIDER_SUCCESS_AT_LINE"), 2)));

    outputConsoleDataProvider.writeWarningResult(3, "UT Warning Message");
    log = appender.getLog();
    Assert.assertEquals(Level.WARN, log.get(2).getLevel());
    Assert.assertTrue(log.get(2).getMessage().toString().endsWith(String.format(Messages.getMessage("OUTPUT_CONSOLE_DATA_PROVIDER_WARNING_AT_LINE"), 3, "UT Warning Message")));

    outputConsoleDataProvider.writeDataResult("title", 4, "UT title");
    log = appender.getLog();
    Assert.assertEquals(Level.INFO, log.get(3).getLevel());
    Assert.assertTrue(log.get(3).getMessage().toString().endsWith(String.format(Messages.getMessage("OUTPUT_CONSOLE_DATA_PROVIDER_RESULT_AT_LINE"), 4, "title", "UT title")));
}
项目:centraldogma    文件:ExpectedExceptionAppender.java   
@Override
protected void append(ILoggingEvent eventObject) {
    final IThrowableProxy exception = getException(eventObject);
    for (String exceptionName : exceptionAndMessage.keySet()) {
        if (exception != null && exception.getClassName().endsWith(exceptionName) &&
            containsMessage(exception, exceptionName)) {
            aai.appendLoopOnAppenders(new ExpectedExceptionEventWrapper(eventObject));
            return;
        }
    }
    aai.appendLoopOnAppenders(eventObject);
}
项目:escalog    文件:LogFmtLayout.java   
private void packageAppender(StringBuilder sb, ILoggingEvent iLoggingEvent)
{
    String className = getLastClassName(iLoggingEvent.getCallerData());
    if ( className != null )
    {
        int lastPointPosition = className.lastIndexOf('.');
        String pkg = lastPointPosition >= 0 ? className.substring(0, lastPointPosition) : "";
        appendKeyValueAndEscape(sb, PACKAGE.toString(), pkg);
    }

}
项目:instalint    文件:LogCallbackAppenderTest.java   
private void testMessage(String msg, Level level, LogOutput.Level translatedLevel) {
  reset(listener);
  event = mock(ILoggingEvent.class);
  when(event.getFormattedMessage()).thenReturn(msg);
  when(event.getLevel()).thenReturn(level);

  appender.append(event);

  verify(event).getFormattedMessage();
  verify(event).getLevel();
  verify(event).getThrowableProxy();
  verify(listener).log(msg, translatedLevel);
  verifyNoMoreInteractions(event, listener);
}
项目:dubbo2    文件:LogbackContainer.java   
/**
 * Initializer logback
 * 
 * @param file
 * @param level
 * @param maxHistory
 */
private void doInitializer(String file, String level, int maxHistory) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    // appender
    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(loggerContext);
    fileAppender.setName("application");
    fileAppender.setFile(file);
    fileAppender.setAppend(true);

    // policy
    TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>();
    policy.setContext(loggerContext);
    policy.setMaxHistory(maxHistory);
    policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
    policy.setParent(fileAppender);
    policy.start();
    fileAppender.setRollingPolicy(policy);

    // encoder
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
    encoder.start();
    fileAppender.setEncoder(encoder);

    fileAppender.start();

    rootLogger.addAppender(fileAppender);
    rootLogger.setLevel(Level.toLevel(level));
    rootLogger.setAdditive(false);
}