ch.qos.logback.classic.Level Java Examples

The following examples show how to use ch.qos.logback.classic.Level. 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: SLF4JLoggerIT.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * Converts log levels in {@link LogLevel} to appropriate levels in
 * {@link Level}.
 */
private Level toLogBackLevel(LogLevel level)
{
  switch (level)
  {
    case ERROR:
      return Level.ERROR;
    case WARNING:
      return Level.WARN;
    case INFO:
      return Level.INFO;
    case DEBUG:
      return Level.DEBUG;
    case TRACE:
      return Level.TRACE;
  }

  return Level.TRACE;
}
 
Example #2
Source File: AgentServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldThrowExceptionWhenAgentWithNoCookieTriesToUpdateRuntimeInfo() {
    AgentRuntimeInfo runtimeInfo = new AgentRuntimeInfo(agentIdentifier, Idle, currentWorkingDirectory(), null);

    try (LogFixture logFixture = logFixtureFor(AgentService.class, Level.DEBUG)) {
        try {
            agentService.updateRuntimeInfo(runtimeInfo);
            fail("should throw exception when no cookie is set");
        } catch (Exception e) {
            assertThat(e, instanceOf(AgentNoCookieSetException.class));
            assertThat(e.getMessage(), is(format("Agent [%s] has no cookie set", runtimeInfo.agentInfoDebugString())));
            assertThat(logFixture.getRawMessages(), hasItem(format("Agent [%s] has no cookie set", runtimeInfo.agentInfoDebugString())));
        }
    }

}
 
Example #3
Source File: LoggerThresholdFilterTest.java    From logging-java with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyFilteringAllAtWarn() {
    final LoggerThresholdFilter filter = new LoggerThresholdFilter();
    filter.setLevel(WARN);
    filter.start();

    for(Level level : allLevels) {
        final LoggingEvent evt = new LoggingEvent();
        evt.setLevel(level);
        for(String logger : variousLoggers) {
            evt.setLoggerName(logger);
            if(level.isGreaterOrEqual(WARN))
                assertEquals(FilterReply.NEUTRAL, filter.decide(evt));
            else
                assertEquals(FilterReply.DENY, filter.decide(evt));
        }
    }
}
 
Example #4
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doConfigure(LogLevel logLevel) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);

    if (currentLevel == null) {
        context.reset();
        context.addTurboFilter(new GradleFilter());
        context.getLogger("org.apache.http.wire").setLevel(Level.OFF);
        GradleAppender appender = new GradleAppender();
        appender.setContext(context);
        appender.start();
        rootLogger.addAppender(appender);
    }

    currentLevel = logLevel;
    rootLogger.setLevel(LogLevelConverter.toLogbackLevel(logLevel));
}
 
Example #5
Source File: UserRestServiceInteractionTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadOnlyPutUserCredentialsFails() {
  String exceptionMessage = "Identity service implementation is read-only.";
  User userUdpdate = MockProvider.createMockUser();
  when(identityServiceMock.isReadOnly()).thenReturn(true);

  given()
      .pathParam("id", MockProvider.EXAMPLE_USER_ID)
      .body(UserCredentialsDto.fromUser(userUdpdate)).contentType(ContentType.JSON)
  .then().expect()
      .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON)
      .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message", equalTo(exceptionMessage))
  .when().put(USER_CREDENTIALS_URL);

  verify(identityServiceMock, never()).saveUser(userUdpdate);
  verifyLogs(Level.DEBUG, exceptionMessage);
}
 
Example #6
Source File: CollectorLogbackAppender.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    if (inFlush.get()) {
        return;
    }
    if (event.getLevel() == Level.DEBUG && event.getLoggerName().startsWith("io.grpc.")) {
        return;
    }
    if (event.getLoggerName().startsWith("org.glowroot.central.")
            || event.getLoggerName().startsWith("org.glowroot.ui.")) {
        // this can happen during integration tests when agent and the central collector are
        // running in the same JVM (using LocalContainer for agent)
        return;
    }
    LogEvent.Builder builder = LogEvent.newBuilder()
            .setTimestamp(event.getTimeStamp())
            .setLevel(toProto(event.getLevel()))
            .setLoggerName(event.getLoggerName())
            .setMessage(event.getFormattedMessage());
    IThrowableProxy throwable = event.getThrowableProxy();
    if (throwable != null) {
        builder.setThrowable(toProto(throwable));
    }
    flush(builder.build());
}
 
Example #7
Source File: OptimizelyTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Verify {@link Optimizely#getFeatureVariableInteger(String, String, String)}
 * calls through to {@link Optimizely#getFeatureVariableInteger(String, String, String, Map)}
 * and returns null
 * when called with a null value for the feature Key parameter.
 */
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION")
@Test
public void getFeatureVariableIntegerReturnsNullWhenFeatureKeyIsNull() throws Exception {
    String variableKey = "";

    Optimizely spyOptimizely = spy(optimizelyBuilder.build());
    assertNull(spyOptimizely.getFeatureVariableInteger(null, variableKey, genericUserId));
    logbackVerifier.expectMessage(Level.WARN, "The featureKey parameter must be nonnull.");

    verify(spyOptimizely, times(1)).getFeatureVariableInteger(
        isNull(String.class),
        any(String.class),
        any(String.class),
        anyMapOf(String.class, String.class)
    );
}
 
Example #8
Source File: GatewayEventFilter.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
	if (params != null && logger.getName().startsWith("discord4j.gateway.inbound")) {
		for (Object param : params) {
			if (param instanceof GatewayPayload) {
				GatewayPayload<?> payload = (GatewayPayload) param;
				if (Opcode.DISPATCH.equals(payload.getOp())) {
					if (excludedEvents != null) {
						if (excludedEvents.contains(payload.getType())) {
							return FilterReply.DENY;
						}
					} else if (includedEvents != null) {
						if (!includedEvents.contains(payload.getType())) {
							return FilterReply.DENY;
						}
					}
				}
			}
		}
	}
	return FilterReply.NEUTRAL;
}
 
Example #9
Source File: KillAppAssaultTest.java    From chaos-monkey-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
void killsSpringBootApplication() {
  KillAppAssault killAppAssault = new KillAppAssault(null, metricsMock);
  killAppAssault.attack();

  verify(mockAppender, times(2)).doAppend(captorLoggingEvent.capture());

  assertEquals(Level.INFO, captorLoggingEvent.getAllValues().get(0).getLevel());
  assertEquals(Level.INFO, captorLoggingEvent.getAllValues().get(1).getLevel());
  assertEquals(
      "Chaos Monkey - I am killing your Application!",
      captorLoggingEvent.getAllValues().get(0).getMessage());
  assertEquals(
      "Chaos Monkey - Unable to kill the App, I am not the BOSS!",
      captorLoggingEvent.getAllValues().get(1).getMessage());
}
 
Example #10
Source File: Utils.java    From jlineup with Apache License 2.0 6 votes vote down vote up
public static void logToFile(String workingDir) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setName(JLINEUP_FILE_APPENDER);
    fileAppender.setFile(workingDir + "/jlineup.log");
    fileAppender.setEncoder(ple);
    fileAppender.setContext(lc);
    fileAppender.start();

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    logger.addAppender(fileAppender);
    logger.setLevel(Level.DEBUG);
}
 
Example #11
Source File: LogLevelConverter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static Level toLogbackLevel(LogLevel level) {
    switch (level) {
        case DEBUG:
            return Level.DEBUG;
        case INFO:
        case LIFECYCLE:
        case QUIET:
            return Level.INFO;
        case WARN:
            return Level.WARN;
        case ERROR:
            return Level.ERROR;
        default:
            throw new IllegalArgumentException("Don't know how to map Gradle log level '" + level + "' to a Logback log level");
    }
}
 
Example #12
Source File: Emissary.java    From emissary with Apache License 2.0 6 votes vote down vote up
static void setupLogbackForConsole() {
    // So it looks better when commands are run
    ch.qos.logback.classic.Logger root =
            (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    root.detachAndStopAllAppenders();
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setPattern("%msg%n");
    ple.setContext(lc);
    ple.start();

    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setEncoder(ple);
    consoleAppender.setContext(lc);
    consoleAppender.start();

    root.addAppender(consoleAppender);
    root.setLevel(Level.INFO);
    root.setAdditive(false);
}
 
Example #13
Source File: JobMessageLogAppender.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(final ILoggingEvent eventObject) {
    Map<String, String> mdcMap = eventObject.getMDCPropertyMap();
    // TODO: check for JOB marker:
    if (mdcMap.containsKey("job_id") && eventObject.getMarker() != null && JobMarker.JOB.contains(eventObject.getMarker())) {
        String jobId = mdcMap.get("job_id");
        Level level = eventObject.getLevel();
        de.otto.edison.jobs.domain.Level edisonLevel = logLevelToEdisonLevel(level);

        String message = eventObject.getFormattedMessage();

        try {
            final JobMessage jobMessage = jobMessage(edisonLevel, message, OffsetDateTime.now());
            jobService.appendMessage(jobId, jobMessage);
        }
        catch(final RuntimeException e) {
            addError("Failed to persist job message (jobId=" + jobId + "): " + message, e);
        }
    }
}
 
Example #14
Source File: SpanLogsAppender.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * This is called only for configured levels.
 * It will not be executed for DEBUG level if root logger is INFO.
 */
@Override
protected void append(ILoggingEvent event) {
  Span span = tracer.activeSpan();
  if (span != null) {
    Map<String, Object> logs = new HashMap<>(6);
    logs.put("logger", event.getLoggerName());
    logs.put("level", event.getLevel().toString());
    logs.put("thread", event.getThreadName());
    logs.put("message", event.getFormattedMessage());

    if (Level.ERROR.equals(event.getLevel())) {
      logs.put("event", Tags.ERROR);
    }

    IThrowableProxy throwableProxy = event.getThrowableProxy();
    if (throwableProxy instanceof ThrowableProxy) {
      Throwable throwable = ((ThrowableProxy)throwableProxy).getThrowable();
      // String stackTrace = ThrowableProxyUtil.asString(throwableProxy);
      if (throwable != null) {
        logs.put("error.object", throwable);
      }
    }
    span.log(TimeUnit.MICROSECONDS.convert(event.getTimeStamp(), TimeUnit.MILLISECONDS), logs);
  }
}
 
Example #15
Source File: LogzioLogbackAppenderTest.java    From logzio-logback-appender with Apache License 2.0 6 votes vote down vote up
@Test
public void existingLine() throws Exception {
    String token = "checkingLine";
    String type = "withLineType" + random(8);
    String loggerName = "test" + random(8);
    int drainTimeout = 1;
    String message1 = "Hostname log - " +  random(5);

    Logger testLogger = createLogger(logzioLogbackAppender, token, type, loggerName, drainTimeout, false, true, null, false);
    testLogger.info(message1);

    // Sleep double time the drain timeout
    sleepSeconds(2 * drainTimeout);

    mockListener.assertNumberOfReceivedMsgs(1);
    MockLogzioBulkListener.LogRequest logRequest = mockListener.assertLogReceivedByMessage(message1);
    mockListener.assertLogReceivedIs(logRequest, token, type, loggerName, Level.INFO.levelStr);
    assertThat(logRequest.getStringFieldOrNull("line")).isNotNull();
}
 
Example #16
Source File: LoggerOutputStream.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
@Override
public synchronized void flush() throws IOException {
	super.flush();
	String record = this.toString();
	super.reset();

	if (record.length() > 0 && !record.equals(separator) && level != Level.OFF) {
		if (level == Level.TRACE)
			log.trace(record);
		else if (level == Level.DEBUG)
			log.debug(record);
		else if (level == Level.INFO)
			log.info(record);
		else if (level == Level.WARN)
			log.warn(record);
		else if (level == Level.ERROR)
			log.error(record);
	}
}
 
Example #17
Source File: LogUtil.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Level toLevel (final String str)
{
    switch (str.toUpperCase()) {
    case "ALL":
        return Level.ALL;

    case "TRACE":
        return Level.TRACE;

    case "DEBUG":
        return Level.DEBUG;

    case "INFO":
        return Level.INFO;

    case "WARN":
        return Level.WARN;

    case "ERROR":
        return Level.ERROR;

    default:
    case "OFF":
        return Level.OFF;
    }
}
 
Example #18
Source File: LogbackConfigurator.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(LoggerContext loggerContext) {
    printInfo("Setting up CUBA default logging configuration");

    try {
        URL url = findURLOfConfigurationFile(true);
        if (url != null) {
            configureByResource(url);
        } else {
            printInfo("Configuring console output with WARN threshold");
            BasicConfigurator basicConfigurator = new BasicConfigurator();
            basicConfigurator.setContext(loggerContext);
            basicConfigurator.configure(loggerContext);
            Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
            rootLogger.setLevel(Level.WARN);
        }
    } catch (Exception e) {
        printError("Failed to configure CUBA default logging: " + e);
    }
}
 
Example #19
Source File: LoggerNameAndLevelFilterTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecideForNonWildCardLoggerName() throws Exception
{
    LoggerNameAndLevelFilter filter = new LoggerNameAndLevelFilter("org.apache.qpid", Level.INFO);

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

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

    when(event.getLevel()).thenReturn(Level.DEBUG);
    when(event.getLoggerName()).thenReturn("org.apache.qpid");
    assertEquals("Unexpected reply for non matching log leve and same logger namel",
                        FilterReply.DENY,
                        filter.decide(event));
}
 
Example #20
Source File: OptimizelyTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that {@link Optimizely#getVariation(String, String)} gives precedence to experiment status over forced
 * variation bucketing.
 */
@Test
public void getVariationExperimentStatusPrecedesForcedVariation() throws Exception {
    Experiment experiment;
    if (datafileVersion >= 4) {
        experiment = validProjectConfig.getExperimentKeyMapping().get(EXPERIMENT_PAUSED_EXPERIMENT_KEY);
    } else {
        experiment = validProjectConfig.getExperiments().get(1);
    }

    Optimizely optimizely = optimizelyBuilder.build();

    logbackVerifier.expectMessage(Level.INFO, "Experiment \"" + experiment.getKey() + "\" is not running.");
    // testUser3 has a corresponding forced variation, but experiment status should be checked first
    assertNull(optimizely.getVariation(experiment.getKey(), "testUser3"));
}
 
Example #21
Source File: DecisionServiceTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that {@link DecisionService#getVariationForFeatureInRollout(FeatureFlag, String, Map, ProjectConfig)}
 * returns null when trying to bucket a user into a {@link FeatureFlag}
 * that does not have a {@link Rollout} attached.
 */
@Test
public void getVariationForFeatureInRolloutReturnsNullWhenFeatureIsNotAttachedToRollout() {
    FeatureFlag mockFeatureFlag = mock(FeatureFlag.class);
    when(mockFeatureFlag.getRolloutId()).thenReturn("");
    String featureKey = "featureKey";
    when(mockFeatureFlag.getKey()).thenReturn(featureKey);

    FeatureDecision featureDecision = decisionService.getVariationForFeatureInRollout(
        mockFeatureFlag,
        genericUserId,
        Collections.<String, String>emptyMap(),
        validProjectConfig
    );
    assertNull(featureDecision.variation);
    assertNull(featureDecision.decisionSource);

    logbackVerifier.expectMessage(
        Level.INFO,
        "The feature flag \"" + featureKey + "\" is not used in a rollout."
    );
}
 
Example #22
Source File: LoggerExtension.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Changes the log level of the specified logger.
 *
 * @param loggerName the name of the logger
 * @param level      the new level
 * @return the updated list of logger (as json), or not found if the given logger cannot be found
 */
@Route(method = HttpMethod.PUT, uri = "/monitor/logs/{name}")
public Result setLevel(@Parameter("name") String loggerName, @Parameter("level") String level) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger logger = context.getLogger(loggerName);
    if (logger != null) {
        logger().info("Setting the log level of {} to {}", loggerName, level);
        ((ch.qos.logback.classic.Logger) logger).setLevel(Level.toLevel(level));
        return loggers();
    } else {
        logger().warn("Cannot set the level of logger {} - the logger does not exist", loggerName);
        return notFound();
    }
}
 
Example #23
Source File: HttpResponseWriterTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void logsSentAndAcknowledgedBytes() {
    EmbeddedChannel ch = new EmbeddedChannel(
            new SimpleChannelInboundHandler<LiveHttpResponse>() {
                @Override
                protected void channelRead0(ChannelHandlerContext ctx, LiveHttpResponse response) throws Exception {
                    HttpResponseWriter writer = new HttpResponseWriter(ctx);
                    CompletableFuture<Void> future = writer.write(response);
                    assertThat(future.isDone(), is(false));

                    contentObservable.onNext(new Buffer("aaa", UTF_8));
                    assertThat(future.isDone(), is(false));

                    contentObservable.onNext(new Buffer("bbbb", UTF_8));
                    assertThat(future.isDone(), is(false));

                    contentObservable.onError(new TransportLostException(
                            new InetSocketAddress(getLoopbackAddress(), 5050),
                            newOriginBuilder("localhost", 5050).build()));
                    assertThat(future.isDone(), is(true));

                    channelRead.set(true);
                }
            }
    );

    ch.writeInbound(response(OK).body(new ByteStream(contentObservable)).build());

    assertThat(LOGGER.lastMessage(), is(
            loggingEvent(
                    Level.WARN,
                    "Content observable error. Written content bytes 7/7 \\(ackd/sent\\). Write events 3/3 \\(ackd/writes\\).*",
                    TransportLostException.class,
                    "Connection to origin lost. origin=\"generic-app:anonymous-origin:localhost:5050\", remoteAddress=\"localhost/127.0.0.1:5050.*")));
}
 
Example #24
Source File: LoggingLogStreamFollowerTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterleavedStreams() throws Exception {
  final Iterator<LogMessage> stream =
      stream(stdout("abc"), stderr("123"), stdout("123"), stderr("abc"));

  final LoggingLogStreamFollower sut = LoggingLogStreamFollower.create(log);
  sut.followLog(JobId.fromString("a:b:c"), "d", stream);

  assertThat(appender.events(),
      contains(event(Level.INFO, "[a] [d] 1 abc"),
          event(Level.INFO, "[a] [d] 2 123"),
          event(Level.INFO, "[a] [d] 1 123"),
          event(Level.INFO, "[a] [d] 2 abc")));
}
 
Example #25
Source File: LoggingConfig.java    From mirror with Apache License 2.0 5 votes vote down vote up
public synchronized static void init() {
  if (started) {
    return;
  }
  started = true;

  // setup java.util.logging (which grpc-java uses) to go to slf4j
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

  LevelChangePropagator p = new LevelChangePropagator();
  p.setContext(context);
  p.start();
  context.addListener(p);

  PatternLayoutEncoder encoder = new PatternLayoutEncoder();
  encoder.setContext(context);
  encoder.setPattern(pattern);
  encoder.start();

  ConsoleAppender<ILoggingEvent> console = new ConsoleAppender<>();
  console.setContext(context);
  console.setEncoder(encoder);
  console.start();

  Logger root = getLogger(Logger.ROOT_LOGGER_NAME);
  root.detachAndStopAllAppenders();
  root.addAppender(console);
  root.setLevel(Level.INFO);

  getLogger("io.grpc").setLevel(Level.INFO);
  // silence a noisy DNS warning when we cannot resolve the other host
  getLogger("io.grpc.internal.ManagedChannelImpl").setLevel(Level.ERROR);
  // silence "ConnectivityStateManager is already disabled" warning
  getLogger("io.grpc.internal.ChannelExecutor").setLevel(Level.ERROR);
  getLogger("mirror").setLevel(Level.INFO);
}
 
Example #26
Source File: UseridFilter.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
    if (MDC.get("userid") == null) {
        MDC.put("userid", System.getProperty("user.name"));
    }

    return FilterReply.NEUTRAL;
}
 
Example #27
Source File: SimpleControllerIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenMarkerRequestMade_thenMessagesWithMarkerLogged() throws Exception {
    String output = controller.clientMarkerRequest();

    SoftAssertions errorCollector = new SoftAssertions();
    errorCollector.assertThat(ListAppender.getEvents())
        .haveAtLeastOne(eventContains("client has made a request", Level.INFO))
        .haveAtLeastOne(eventContains("Starting request", Level.INFO, "MYMARKER"))
        .haveAtLeastOne(eventContains("Finished request", Level.DEBUG, "MYMARKER"))
        .haveExactly(2, eventContains(null, null, "MYMARKER"));
    errorCollector.assertThat(output)
        .isEqualTo("finished");
    errorCollector.assertAll();
}
 
Example #28
Source File: GatewayEventFilter.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public FilterReply decide(Marker marker, Logger log, Level level, String format, Object[] params, Throwable t) {
    String logName = log.getName();
    if (loggers.contains(logName)) {
        if (format != null) {
            if (!excludedEvents.isEmpty() && excludedEvents.stream().anyMatch(format::contains)) {
                return FilterReply.DENY;
            }
            if (!includedEvents.isEmpty() && includedEvents.stream().noneMatch(format::contains)) {
                return FilterReply.DENY;
            }
        }
    }
    return FilterReply.NEUTRAL;
}
 
Example #29
Source File: LogsResource.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
@PutMapping("/logs")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Timed
public void changeLevel(@RequestBody LoggerVM jsonLogger) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
}
 
Example #30
Source File: ProgressImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
Config() {
  Logger logger = LoggerFactory.getLogger(JobExecution.class);
  if (!(logger instanceof ch.qos.logback.classic.Logger)) {
    throw new RuntimeException("Expected logback als SLF4J implementation");
  }
  ch.qos.logback.classic.Logger jobExecutionLog = (ch.qos.logback.classic.Logger) logger;
  jobExecutionLog.setLevel(Level.ALL);
  JobExecutionLogAppender appender = new JobExecutionLogAppender();
  LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
  appender.setContext(lc);
  appender.start();
  jobExecutionLog.addAppender(appender);
}