ch.qos.logback.classic.Logger Java Examples

The following examples show how to use ch.qos.logback.classic.Logger. 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: LoggingFactory.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
private Logger configureLevels() {

        final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
        root.getLoggerContext().reset();

        final LevelChangePropagator propagator = new LevelChangePropagator();
        propagator.setContext(root.getLoggerContext());
        propagator.setResetJUL(true);

        root.getLoggerContext().addListener(propagator);

        root.setLevel(config.getLevel());

        // Decode the packages and levels
        for (Map.Entry<String, Level> entry : config.getLoggers().entrySet()) {
            ((Logger) LoggerFactory.getLogger(entry.getKey())).setLevel(entry.getValue());
        }

        return root;
    }
 
Example #2
Source File: GelfEncoderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void customLoggerNameKey() throws IOException {
    encoder.setLoggerNameKey("Logger");
    encoder.start();

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final LoggingEvent event = simpleLoggingEvent(logger, null);

    final String logMsg = encodeToStr(event);

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    coreValidation(jsonNode);
    assertNotNull(jsonNode.get("_thread_name").textValue());
    assertEquals(LOGGER_NAME, jsonNode.get("_Logger").textValue());
    assertNull(jsonNode.get("_exception"));
}
 
Example #3
Source File: DatatypeBenchmarkSerializableEmpty.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup(Level.Iteration)
public void setUp() {
	Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName());
	root.setLevel(ch.qos.logback.classic.Level.INFO);

	SimpleValueFactory vf = SimpleValueFactory.getInstance();

	allStatements = BenchmarkConfigs.generateStatements(((statements, i, j) -> {
		IRI iri = vf.createIRI("http://example.com/" + i + "_" + j);
		statements.add(vf.createStatement(iri, RDF.TYPE, RDFS.RESOURCE));
		statements.add(vf.createStatement(iri, FOAF.AGE, vf.createLiteral(i)));
	}));

	System.gc();

}
 
Example #4
Source File: DatatypeBenchmarkEmpty.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup(Level.Iteration)
public void setUp() {
	Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName());
	root.setLevel(ch.qos.logback.classic.Level.INFO);

	SimpleValueFactory vf = SimpleValueFactory.getInstance();

	allStatements = BenchmarkConfigs.generateStatements(((statements, i, j) -> {
		IRI iri = vf.createIRI("http://example.com/" + i + "_" + j);
		statements.add(vf.createStatement(iri, RDF.TYPE, RDFS.RESOURCE));
		statements.add(vf.createStatement(iri, FOAF.AGE, vf.createLiteral(i)));
	}));

	System.gc();

}
 
Example #5
Source File: UimaLoggingTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
  BaleenLogging logging = new BaleenLogging();
  InMemoryLoggingBuilder builder = new InMemoryLoggingBuilder();
  logging.configure(Collections.singletonList(builder));

  InMemoryAppender<ILoggingEvent> appender = builder.getAppender();
  appender.clear();

  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger rootLogger = context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);

  if (rootLogger.isInfoEnabled()) {
    UIMAFramework.getLogger(DummyAnnotator1.class).log(Level.INFO, "Logging from uima");

    assertTrue(
        appender.getAll().stream()
                .filter(l -> l.getMessage().contains("Logging from uima"))
                .count()
            > 0);
  }
}
 
Example #6
Source File: LoggerOverrideConfigChangeHandler.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void validate(NodeContext nodeContext, Configuration change) throws InvalidConfigChangeException {
  String logger = change.getKey();
  String level = change.getValue();

  // verify enum
  if (level != null) {
    try {
      Level.valueOf(level);
    } catch (RuntimeException e) {
      throw new InvalidConfigChangeException("Illegal level: " + level, e);
    }
  }

  // verify we can access the logger
  LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger logbackLogger = loggerContext.getLogger(logger);

  // verify illegal op
  if (Logger.ROOT_LOGGER_NAME.equals(logbackLogger.getName()) && level == null) {
    throw new InvalidConfigChangeException("Cannot remove the root logger");
  }
}
 
Example #7
Source File: LogbackRootLoggerCheckerTest.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheck() {
	checker.check();
	 Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
	 Level actualLevel = root.getLevel();
	assertThat(actualLevel, is(Level.INFO));
	
	checker.setCorrectLevelStr("DEBUG");
	checker.check();
	actualLevel = root.getLevel();
	assertThat(actualLevel, is(Level.DEBUG));
	
	checker.setActive(false);
	checker.setCorrectLevelStr("WARN");
	checker.check();
	actualLevel = root.getLevel();
	assertThat(actualLevel, is(Level.DEBUG));
}
 
Example #8
Source File: CertificateGeneratorTest.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void constructCert() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    ((Logger)LoggerFactory.getLogger(CertificateGenerator.class)).setLevel(Level.DEBUG);
    File file = new File("/tmp/dm-agent.jks");//Files.createTempFile("dm-agent", ".jks");

    KeyPair keypair = createKeypair();
    JcaX509v3CertificateBuilder cb = createRootCert(keypair);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keypair.getPrivate());
    X509CertificateHolder rootCert = cb.build(signer);
    KeystoreConfig cert = CertificateGenerator.constructCert(rootCert,
      keypair.getPrivate(),
      file,
      ImmutableSet.of("test1", "test2"));
    assertNotNull(cert);
}
 
Example #9
Source File: LogbackController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Frees the given logger from the appender used to be displayed directly by
 * this controller.
 *
 * @param name The name of the logger we want to free from being captured
 * @return The list of log levels configured and their settings
 */
@RequestMapping(value = "free/{name}/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> free(@PathVariable("name")
final String name) {
    final LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
    synchronized (ctx) {
        Logger logger = ctx.getLogger(name);
        if (logger != null) {
            logger.setLevel(null);
            logger.detachAppender(logbackMemoryAppenderImpl.getName());
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example #10
Source File: LogBackHookProxy.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private void figureoutLogConfiguration(Logger Logger, LinkedList<LogProfileInfo> list, String appid) {

        Iterator<Appender<ILoggingEvent>> appenders = Logger.iteratorForAppenders();
        while (appenders != null && appenders.hasNext()) {
            Appender<ILoggingEvent> appender = appenders.next();
            if (appender instanceof FileAppender<?>) {
                getAppenderInfo((FileAppender<ILoggingEvent>)appender, list, appid);
            }
            else if(appender instanceof AsyncAppender) {
                Iterator<Appender<ILoggingEvent>> itAppenders = (Iterator<Appender<ILoggingEvent>>)((AsyncAppender) appender).iteratorForAppenders();
                while (itAppenders != null && itAppenders.hasNext()) {
                    Appender<ILoggingEvent> ap = itAppenders.next();
                    if (ap instanceof FileAppender<?>) {
                        getAppenderInfo((FileAppender<ILoggingEvent>)ap, list, appid);
                    }
                } 
            }
        }
    }
 
Example #11
Source File: LogBackConfiguration.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
    if (loggerContext == null)
        return;
    List<Logger> loggerList = loggerContext.getLoggerList();
    ch.qos.logback.classic.Logger loggerKafka =
        loggerContext.getLogger("org.apache.kafka.clients.producer.ProducerConfig");
    if (loggerKafka != null) {
        loggerKafka.setLevel(ch.qos.logback.classic.Level.ERROR);
    }
    createBizLogger();
    for (Logger logger : loggerList) {
        AppenderAttachable appenderAttachable = logger;
        setLayout(loggerContext,appenderAttachable.iteratorForAppenders());
    }
}
 
Example #12
Source File: MinCountBenchmarkEmpty.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup(Level.Invocation)
public void setUp() {
	Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName());
	root.setLevel(ch.qos.logback.classic.Level.INFO);

	SimpleValueFactory vf = SimpleValueFactory.getInstance();

	allStatements = BenchmarkConfigs.generateStatements(((statements, i, j) -> {
		IRI iri = vf.createIRI("http://example.com/" + i + "_" + j);
		statements.add(vf.createStatement(iri, RDF.TYPE, RDFS.RESOURCE));
		statements.add(vf.createStatement(iri, RDFS.LABEL, vf.createLiteral("label" + i)));
	}));

	System.gc();

}
 
Example #13
Source File: AddRemoveBenchmarkEmpty.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup(Level.Iteration)
public void setUp() {
	Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName());
	root.setLevel(ch.qos.logback.classic.Level.INFO);

	allStatements = new ArrayList<>(BenchmarkConfigs.NUMBER_OF_TRANSACTIONS);

	SimpleValueFactory vf = SimpleValueFactory.getInstance();

	for (int j = 0; j < BenchmarkConfigs.NUMBER_OF_TRANSACTIONS; j++) {
		List<Statement> statements = new ArrayList<>(BenchmarkConfigs.STATEMENTS_PER_TRANSACTION);
		allStatements.add(statements);
		for (int i = 0; i < BenchmarkConfigs.STATEMENTS_PER_TRANSACTION; i++) {
			statements.add(
					vf.createStatement(vf.createIRI("http://example.com/" + i + "_" + j), RDF.TYPE, RDFS.RESOURCE));
			statements.add(vf.createStatement(vf.createIRI("http://example.com/" + i + "_" + j), FOAF.AGE,
					vf.createLiteral(i)));
		}
	}
	System.gc();

}
 
Example #14
Source File: MaxCountBenchmarkEmpty.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Setup(Level.Invocation)
public void setUp() {
	Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName());
	root.setLevel(ch.qos.logback.classic.Level.INFO);

	SimpleValueFactory vf = SimpleValueFactory.getInstance();

	allStatements = BenchmarkConfigs.generateStatements(((statements, i, j) -> {
		IRI iri = vf.createIRI("http://example.com/" + i + "_" + j);
		statements.add(vf.createStatement(iri, RDF.TYPE, RDFS.RESOURCE));
		statements.add(vf.createStatement(iri, RDFS.LABEL, vf.createLiteral("label" + i)));
	}));

	System.gc();

}
 
Example #15
Source File: MongoJobRepositoryTest.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTruncateTooBigJobMessagesArray() throws Exception {
    // given
    final String jobId = "idOfTooBigJob";
    final JobInfo jobInfo = jobInfo(jobId, "BIG_JOB");
    repo.createOrUpdate(jobInfo);

    ch.qos.logback.classic.Level oldLevel = ((Logger) (LoggerFactory.getLogger("org.mongodb.driver"))).getLevel();
    ((Logger)(LoggerFactory.getLogger("org.mongodb.driver"))).setLevel(ch.qos.logback.classic.Level.ERROR);
    // when
    char[] chars = new char[1024 * 1024 * 15 / 1500];
    Arrays.fill(chars, 't');
    for (int i = 0; i < 1500; i++) {
        final JobMessage jobMessage = jobMessage(Level.INFO, new String(chars), now());
        repo.appendMessage(jobId, jobMessage);
    }
    ((Logger)(LoggerFactory.getLogger("org.mongodb.driver"))).setLevel(oldLevel);

    // when
    repo.keepJobMessagesWithinMaximumSize(jobId);

    // then
    final JobInfo jobInfoFromDB = repo.findOne(jobId).orElse(null);
    assertThat(jobInfoFromDB.getMessages(), hasSize(1000));
    assertThat(jobInfoFromDB.getMessages().get(999).getMessage(), containsString("The messages array for this job is growing towards MongoDBs limit for single documents, so I'll drop all messages but the last 1000."));
    assertThat(jobInfoFromDB.getStatus(), is(OK));
}
 
Example #16
Source File: GelfTcpTlsAppenderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Logger setupLogger() {
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    final GelfEncoder gelfEncoder = new GelfEncoder();
    gelfEncoder.setContext(lc);
    gelfEncoder.setOriginHost("localhost");
    gelfEncoder.start();

    final Logger logger = (Logger) LoggerFactory.getLogger(LOGGER_NAME);
    logger.addAppender(buildAppender(lc, gelfEncoder));
    logger.setAdditive(false);

    return logger;
}
 
Example #17
Source File: GelfTcpAppenderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Logger setupLogger() {
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    final GelfEncoder gelfEncoder = new GelfEncoder();
    gelfEncoder.setContext(lc);
    gelfEncoder.setOriginHost("localhost");
    gelfEncoder.start();

    final Logger logger = (Logger) LoggerFactory.getLogger(LOGGER_NAME);
    logger.addAppender(buildAppender(lc, gelfEncoder));
    logger.setAdditive(false);

    return logger;
}
 
Example #18
Source File: LogbackLoggerResource.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/change/to/error/{loggerName}")
public String changeToError(@PathParam("loggerName") final String loggerName) {
	Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
	changeLevel(logger, Level.ERROR);
	return getLevel(loggerName);
}
 
Example #19
Source File: DockerTestModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  final int baragonPort = Integer.parseInt(System.getProperty("baragon.service.port"));
  install(new BaragonClientModule(Arrays.asList(String.format("%s:%d", getDockerAddress().or("localhost"), baragonPort))));
  BaragonClientModule.bindAuthkey(binder()).toInstance(Optional.fromNullable(Strings.emptyToNull(System.getProperty("baragon.service.auth.key"))));
  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger rootLogger = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
  rootLogger.setLevel(Level.INFO);
}
 
Example #20
Source File: LoggerVMTest.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
@Test
public void setLevelTest() throws Exception {
    LoggerVM vm = new LoggerVM();
    vm.setLevel(null);
    assertNull(vm.getLevel());

    vm = new LoggerVM();
    vm.setLevel("fakeLevel");
    assertEquals("fakeLevel", vm.getLevel());

    Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    vm = new LoggerVM(logger);
    vm.setLevel(Level.OFF.toString());
    assertEquals(Level.OFF.toString(), vm.getLevel());
}
 
Example #21
Source File: Configuration.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
public void setDebugMode(boolean debugMode) {
	this.debugMode = debugMode;

	if (debugMode) {
		// Ignore first run operations if we are running in debug mode
		setFirstRun(false);
	}

	final Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

	if (debugMode) {
		final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
		setLogConsoleAppender(rootLogger, loggerContext);

		if (rootLogger.getLevel().equals(Level.TRACE)) {
			return;
		}

		rootLogger.setLevel(Level.DEBUG);

		// Ensure webcam-capture logger stays at info because it is quite
		// noisy and doesn't output information we care about.
		final Logger webcamCaptureLogger = loggerContext.getLogger("com.github.sarxos");
		webcamCaptureLogger.setLevel(Level.INFO);

		// Drop WebcamDiscoveryService even lower because it is extremely
		// noisy
		final Logger webcamDiscoveryLogger = loggerContext
				.getLogger("com.github.sarxos.webcam.WebcamDiscoveryService");
		webcamDiscoveryLogger.setLevel(Level.WARN);
	} else {
		rootLogger.setLevel(Level.WARN);
	}
}
 
Example #22
Source File: LogLevelTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testNoValueShowsCurrentLevel() {
	Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
	logger.setLevel(Level.INFO);

	setParameters.execute("set", "log");

	verify(mockConsoleIO).writeln("log: info");
	verifyNoMoreInteractions(mockConsoleIO);
}
 
Example #23
Source File: LogControlImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Map<String, Appender> getAllAppenders() {
    Map<String, Appender> map = new HashMap<>();
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    for (Logger logger : context.getLoggerList()) {
        for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext();) {
            Appender<ILoggingEvent> appender = index.next();
            if (appender.getName() != null) {
                map.put(appender.getName(), appender);
            }
        }
    }
    return map;
}
 
Example #24
Source File: TestFileSystemRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinimalArchiveCleanupIntervalHonoredAndLogged() throws Exception {
    // We are going to construct our own repository using different properties, so
    // we need to shutdown the existing one.
    shutdown();

    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    ListAppender<ILoggingEvent> testAppender = new ListAppender<>();
    testAppender.setName("Test");
    testAppender.start();
    root.addAppender(testAppender);
    final Map<String, String> addProps = new HashMap<>();
    addProps.put(NiFiProperties.CONTENT_ARCHIVE_CLEANUP_FREQUENCY, "1 millis");
    final NiFiProperties localProps = NiFiProperties.createBasicNiFiProperties(TestFileSystemRepository.class.getResource("/conf/nifi.properties").getFile(), addProps);
    repository = new FileSystemRepository(localProps);
    repository.initialize(new StandardResourceClaimManager());
    repository.purge();

    boolean messageFound = false;
    String message = "The value of nifi.content.repository.archive.cleanup.frequency property "
            + "is set to '1 millis' which is below the allowed minimum of 1 second (1000 milliseconds). "
            + "Minimum value of 1 sec will be used as scheduling interval for archive cleanup task.";

    // Must synchronize on testAppender, because the call to append() is synchronized and this synchronize
    // keyword guards testAppender.list. Since we are accessing testAppender.list, we must do so in a thread-safe manner.
    synchronized (testAppender) {
        for (ILoggingEvent event : testAppender.list) {
            String actualMessage = event.getFormattedMessage();
            if (actualMessage.equals(message)) {
                assertEquals(event.getLevel(), Level.WARN);
                messageFound = true;
                break;
            }
        }
    }

    assertTrue(messageFound);
}
 
Example #25
Source File: NativeStoreBenchmark.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Setup(Level.Iteration)
public void setUp() {
	System.gc();
	((Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()))
			.setLevel(ch.qos.logback.classic.Level.ERROR);
	((Logger) LoggerFactory.getLogger(ShaclSail.class.getName())).setLevel(ch.qos.logback.classic.Level.ERROR);
}
 
Example #26
Source File: SaeControllerTest.java    From SmartApplianceEnabler with GNU General Public License v2.0 5 votes vote down vote up
@BeforeEach
public void setup() throws Exception {
    System.setProperty(FileHandler.SAE_HOME, System.getProperty("java.io.tmpdir"));
    this.mockMvc = webAppContextSetup(webApplicationContext).build();
    this.now = LocalDateTime.now();

    Logger root = (Logger) LoggerFactory.getLogger("de.avanux");
    root.setLevel(Level.DEBUG);
}
 
Example #27
Source File: LoggerNameAndLevelFilter.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public Level getEffectiveLevel(final Logger logger)
{
    if((_loggerName == null || "".equals(_loggerName) || Logger.ROOT_LOGGER_NAME.equals(_loggerName))
      || (_loggerName.endsWith(".*") && logger.getName().startsWith(_loggerName.substring(0,_loggerName.length()-2)))
      || _loggerName.equals(logger.getName()))
    {
        return _level;
    }
    else
    {
        return Level.OFF;
    }
}
 
Example #28
Source File: LogbackLoggingFacade.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@Nonnull
public List<LoggerConfig> getLoggerConfig() {
    final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    final List<Logger> loggerList = rootLogger.getLoggerContext().getLoggerList();

    return loggerConfigsFor(loggerList);
}
 
Example #29
Source File: OutputConsoleDataProviderUT.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
@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")));
}
 
Example #30
Source File: LoggerService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets a logger, if checkLevel is true and if logger has no level defined it will return a
 * NameNotFound exception
 */
protected Logger getLogger(String name, boolean checkLevel) throws NotFoundException {
  LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

  Logger log = loggerContext.getLogger(name);
  if (checkLevel && log.getLevel() == null) {
    throw new NotFoundException("The logger with name " + name + " is not existing.");
  }
  return log;
}