public static void main(String[] arg) { try { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.resizable = false; DesktopConfigEditor editor = new DesktopConfigEditor(); Config cfg = DesktopConfigUtil.buildConfig(editor); DesktopConfigUtil.setupLwjglConfig(config, cfg); LwjglApplication application = new LwjglApplication(new ArcadeLegendsGame(cfg), config); //application.postRunnable(() -> application.getGraphics().setUndecorated(true)); DesktopConfigUtil.registerStandardListeners(editor, cfg, config, application); } catch (Exception ex) { log.error(MarkerFactory.getMarker("ERROR"), "Error loading config", ex); System.exit(0); } }
@Test public void testMarker() throws Exception { String token = "markerToken"; String type = "markerType"; String loggerName = "markerTesting"; String markerKey = "marker"; String markerTestValue = "MyMarker"; int drainTimeout = 1; String message1 = "Simple log line - "+random(5); Marker marker = MarkerFactory.getMarker(markerTestValue); Logger testLogger = createLogger(token, type, loggerName, drainTimeout, false, false, null); testLogger.info(marker, message1); sleepSeconds(2 * drainTimeout); mockListener.assertNumberOfReceivedMsgs(1); MockLogzioBulkListener.LogRequest logRequest = mockListener.assertLogReceivedByMessage(message1); mockListener.assertLogReceivedIs(logRequest, token, type, loggerName, Level.INFO.levelStr); assertThat(logRequest.getStringFieldOrNull(markerKey)).isEqualTo(markerTestValue); }
@Test public void testCategorties() { logMsg = "Running testCategories()"; Marker cat0 = MarkerFactory.getMarker("cat0"); LOGGER.info(cat0, logMsg); assertThat(getMessage(), is(logMsg)); assertThat(getField(Fields.COMPONENT_ID), is("-")); assertThat(getField(Fields.COMPONENT_NAME), is("-")); assertThat(getField(Fields.COMPONENT_INSTANCE), is("0")); assertThat(getField(Fields.WRITTEN_TS), is(notNullValue())); assertThat(getList(Fields.CATEGORIES), contains(cat0.getName())); Marker cat1 = MarkerFactory.getMarker("cat1"); cat1.add(cat0); LOGGER.info(cat1, logMsg); assertThat(getMessage(), is(logMsg)); assertThat(getField(Fields.COMPONENT_ID), is("-")); assertThat(getField(Fields.COMPONENT_NAME), is("-")); assertThat(getField(Fields.COMPONENT_INSTANCE), is("0")); assertThat(getField(Fields.WRITTEN_TS), is(notNullValue())); assertThat(getList(Fields.CATEGORIES), contains(cat1.getName(), cat0.getName())); }
@PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet()); if (jHipsterProperties.getMetrics().getJmx().isEnabled()) { log.debug("Initializing Metrics JMX reporting"); JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build(); jmxReporter.start(); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { log.info("Initializing Metrics Log reporting"); Marker metricsMarker = MarkerFactory.getMarker("metrics"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LoggerFactory.getLogger("metrics")) .markWith(metricsMarker) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS); } }
protected void mapSupportLevel(String message, Throwable t) { Marker supportMarker = MarkerFactory.getMarker(SUPPORT); switch (getSupportLevel()) { case LOG_LEVEL_ERROR: LOGGER.error(supportMarker, message, t); break; case LOG_LEVEL_INFO: LOGGER.info(supportMarker, message, t); break; case LOG_LEVEL_DEBUG: LOGGER.debug(supportMarker, message, t); break; case LOG_LEVEL_TRACE: LOGGER.trace(supportMarker, message, t); break; default: LOGGER.warn(supportMarker, message, t); } }
@Test public void testComposite() { String compositeMarkerName = COMPOSITE; Marker compositeMarker = MarkerFactory.getMarker(compositeMarkerName); compositeMarker.add(totoMarker); MarkerFilter mkt = new MarkerFilter(); mkt.setMarker(TOTO); mkt.setOnMatch("ACCEPT"); mkt.setOnMismatch("DENY"); mkt.start(); assertTrue(mkt.isStarted()); assertEquals(FilterReply.DENY, mkt.decide(null, null, null, null, null, null)); assertEquals(FilterReply.ACCEPT, mkt.decide(totoMarker, null, null, null, null, null)); assertEquals(FilterReply.ACCEPT, mkt.decide(compositeMarker, null, null, null, null, null)); }
@Test public void testIgnoreMarker() throws NullPointerException, EvaluationException, JoranException { JoranConfigurator jc = new JoranConfigurator(); LoggerContext loggerContext = new LoggerContext(); jc.setContext(loggerContext); jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "ignore.xml"); Map evalMap = (Map) loggerContext.getObject(CoreConstants.EVALUATOR_MAP); assertNotNull(evalMap); Logger logger = loggerContext.getLogger("xx"); JaninoEventEvaluator evaluator = (JaninoEventEvaluator) evalMap.get("IGNORE_EVAL"); LoggingEvent event = new LoggingEvent("foo", logger, Level.DEBUG, "Hello world",null, null); Marker ignoreMarker = MarkerFactory.getMarker("IGNORE"); event.setMarker(ignoreMarker); assertTrue(evaluator.evaluate(event)); logger.debug("hello", new Exception("test")); logger.debug(ignoreMarker, "hello ignore", new Exception("test")); //logger.debug("hello", new Exception("test")); //StatusPrinter.print(loggerContext.getStatusManager()); }
/** * Logs a message. */ @Override public void log(final int priority, final String tag, final String message) { final Marker marker = MarkerFactory.getMarker(tag); switch (priority) { case AxolotlLogger.VERBOSE: case AxolotlLogger.DEBUG: LOGGER.debug(marker, message); break; case AxolotlLogger.INFO: LOGGER.info(marker, message); break; case AxolotlLogger.WARN: LOGGER.warn(marker, message); break; case AxolotlLogger.ERROR: LOGGER.error(marker, message); break; case AxolotlLogger.ASSERT: LOGGER.trace(marker, message); break; default: LOGGER.error(marker, "## Unknown Loglevel Message: ##" + message); } }
@Test public void testConvert() { final IndentConverter converter = new IndentConverter(); assertEquals("Unexpected convertion", " ", converter.convert(new MockILoggingEvent())); assertEquals("Unexpected convertion", " ", converter.convert(new MockILoggingEvent(null, MarkerFactory.getMarker("unknown"), "message"))); assertEquals("Unexpected convertion", "{", converter.convert(new MockILoggingEvent(null, LogMarker.ENTRY.getValue(), "message"))); assertEquals("Unexpected convertion", "}", converter.convert(new MockILoggingEvent(null, LogMarker.EXIT.getValue(), "message"))); assertEquals("Unexpected convertion", "d", converter.convert(new MockILoggingEvent(null, LogMarker.DATA.getValue(), "message"))); assertEquals("Unexpected convertion", "!", converter.convert(new MockILoggingEvent(null, LogMarker.THROWING.getValue(), "message"))); assertEquals("Unexpected convertion", "i", converter.convert(new MockILoggingEvent(null, LogMarker.INFO.getValue(), "message"))); assertEquals("Unexpected convertion", "w", converter.convert(new MockILoggingEvent(null, LogMarker.WARNING.getValue(), "message"))); assertEquals("Unexpected convertion", "e", converter.convert(new MockILoggingEvent(null, LogMarker.ERROR.getValue(), "message"))); assertEquals("Unexpected convertion", "f", converter.convert(new MockILoggingEvent(null, LogMarker.FFDC.getValue(), "message"))); }
@Test public void testDecide() { final LogFilter filter = new LogFilter(); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent())); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.ENTRY.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.EXIT.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.DATA.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.THROWING.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.INFO.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.WARNING.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.ERROR.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.FFDC.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, MarkerFactory.getMarker("unknown"), "message", new Object[] { null }))); }
@Test public void testDecide() { final TraceFilter filter = new TraceFilter(); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent())); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.ENTRY.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.EXIT.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.DATA.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.ACCEPT, filter.decide(new MockILoggingEvent(null, LogMarker.THROWING.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.INFO.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.WARNING.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.ERROR.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, LogMarker.FFDC.getValue(), "message", new Object[] { null }))); assertEquals("Unexpected filter response", FilterReply.DENY, filter.decide(new MockILoggingEvent(null, MarkerFactory.getMarker("unknown"), "message", new Object[] { null }))); }
@Test public void test() { Map<String, String> contextMap = new HashMap<String, String>(); contextMap.put("authenticationToken", null); contextMap.put("ipAddress", "192.168.254.254"); contextMap.put("method", "GET"); contextMap.put("request", "/users"); MDC.setContextMap(contextMap); Marker securityAlertMarker = MarkerFactory.getDetachedMarker("SECURITY_ALERT"); logger.error(securityAlertMarker, "Usuer not currently logged in"); assertThat(logger, hasAtLeastOneEntry(that(allOf( haveLevel(LoggingLevel.ERROR), containMDC("authenticationToken", nullValue()), containMDC("request", anything()), containMarker("SECURITY_ALERT"), haveMessage(allOf( containsString("not"), containsString("logged") ))) ))); }
/** * Computes a mapping between a source and a target. * * @param source * Source cache * @param target * Target cache * @param sourceVar * Variable for the source dataset * @param targetVar * Variable for the target dataset * @param expression * Expression to process. * @param threshold * Similarity threshold * @return A mapping which contains links between the source instances and * the target instances */ @Override public AMapping getMapping(ACache source, ACache target, String sourceVar, String targetVar, String expression, double threshold) { if (threshold <= 0) { throw new InvalidThresholdException(threshold); } List<String> properties = PropertyFetcher.getProperties(expression, threshold); // if no properties then terminate if (properties.get(0) == null || properties.get(1) == null) { logger.error(MarkerFactory.getMarker("FATAL"), "Property values could not be read. Exiting"); throw new RuntimeException(); } Map<String, Set<String>> sourceIndex = getValueToUriMap(source, properties.get(0)); Map<String, Set<String>> targetIndex = getValueToUriMap(target, properties.get(1)); AMapping m = MappingFactory.createDefaultMapping(); boolean swapped = sourceIndex.keySet().size() > targetIndex.keySet().size(); (swapped ? sourceIndex : targetIndex).keySet().stream().filter(targetIndex::containsKey).forEach(value -> { for (String sourceUri : (swapped ? sourceIndex : targetIndex).get(value)) { for (String targetUri : (swapped ? targetIndex : sourceIndex).get(value)) { m.add(sourceUri, targetUri, 1d); } } }); return m; }
@Override public void run() { try { int totalLoops = 10; Thread.sleep( 0 ); int i = 0; do { tune( service, path, stbModel, "25" ); Thread.sleep( 3000 ); tune( service, path, stbModel, "37" ); i++; } while ( i < totalLoops ); } catch ( InterruptedException ex ) { LoggerFactory.getLogger(SimpleIRThread.class.getName()).error(MarkerFactory.getMarker("SEVERE"), null, ex); } }
/** * Logs the exception; on ERROR level when status is 5xx, otherwise on INFO level without stack * trace, or DEBUG level with stack trace. The logger name is * {@code cz.jirutka.spring.exhandler.handlers.RestExceptionHandler}. * * @param ex The exception to log. * @param req The current web request. */ protected void logException(E ex, HttpServletRequest req) { if (LOG.isErrorEnabled() && getStatus().value() >= 500 || LOG.isInfoEnabled()) { Marker marker = MarkerFactory.getMarker(ex.getClass().getName()); String uri = req.getRequestURI(); if (req.getQueryString() != null) { uri += '?' + req.getQueryString(); } String msg = String.format("%s %s ~> %s", req.getMethod(), uri, getStatus()); if (getStatus().value() >= 500) { LOG.error(marker, msg, ex); } else if (LOG.isDebugEnabled()) { LOG.debug(marker, msg, ex); } else { LOG.info(marker, msg); } } }
@Override public void resourceOffers(final SchedulerDriver driver, final List<Offer> offers) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("> resourceOffers(driver : {}, offers : {})", driver, protoToString(offers)); } for (final Offer offer : offers) { final Marker marker = MarkerFactory.getMarker("offerId:" + offer.getId().getValue() + ",hostname:" + offer.getHostname()); final boolean offerUsed = evaluateOffer(driver, marker, offer); if (!offerUsed) { LOGGER.trace(marker, "Declining Offer: {}", offer.getId().getValue()); driver.declineOffer(offer.getId()); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("< resourceOffers(driver : {}, offers : {})", driver, protoToString(offers)); } }
@Test public void allResourcesAvailableBeforeLaunchingExecutor() throws Exception { cleanState(); final String role = "*"; final Protos.Offer offer = Protos.Offer.newBuilder() .setFrameworkId(frameworkId) .setHostname("localhost") .setId(Protos.OfferID.newBuilder().setValue(randomID())) .setSlaveId(Protos.SlaveID.newBuilder().setValue("slave_1")) .addResources(cpu(0.1, role)) .addResources(mem(0.1, role)) .addResources(disk(0.1, role)) .addResources(ports(Lists.<Long>emptyList(), role)) .build(); final Marker marker = MarkerFactory.getMarker("offerId:" + offer.getId().getValue() + ",hostname:" + offer.getHostname()); assertThat(cluster._getTasksForOffer(marker, offer)).isNull(); }
public GoConfigHolder migrate() throws Exception { try { return upgrade(); } catch (Exception e) { e.printStackTrace(); System.err.println( "There are errors in the Cruise config file. Please read the error message and correct the errors.\n" + "Once fixed, please restart Cruise.\nError: " + e.getMessage()); LOGGER.error(MarkerFactory.getMarker("FATAL"), "There are errors in the Cruise config file. Please read the error message and correct the errors.\n" + "Once fixed, please restart Cruise.\nError: " + e.getMessage()); // Send exit signal in a separate thread otherwise it will deadlock jetty new Thread(new Runnable() { public void run() { System.exit(1); } }).start(); } return null; }
protected void logExecution(OpenOrder openOrder, int quantity) { Object[] params = new Object[] { openOrder.getFillDate(), "EXEC", openOrder.getAction(), openOrder.getType(), quantity, openOrder.getSymbol(), openOrder.getSymbol().getCurrency(), Util.round(openOrder.getLastFillPrice(), 4), "", "", "", "", "", openOrder.getReference() != null ? openOrder.getReference() : "", "DU000000" }; blotter.info(MarkerFactory.getMarker("EXECUTION"), "{},{},{},{},{},{},{},{},{},{},{},{},{},{}", params); }
protected void logTrade(OpenOrder openOrder, int position, double costBasis, double realized, double unrealized) { Object[] params = new Object[] { openOrder.getFillDate(), "TRADE", openOrder.getAction(), openOrder.getType(), openOrder.getQuantityFilled(), openOrder.getSymbol(), openOrder.getSymbol().getCurrency(), Util.round(openOrder.getAvgFillPrice(), 4), position, Util.round(costBasis, 4), Util.round(realized, 4), Util.round(unrealized, 4), Util.round(openOrder.getCommission(), 4), openOrder.getReference() != null ? openOrder.getReference() : "", "DU000000" }; blotter.info(MarkerFactory.getMarker("TRADE"), "{},{},{},{},{},{},{},{},{},{},{},{},{},{}", params); }
@Test public void testMarker() throws Exception { Logger logger = lc.getLogger(getClass()); logger.info(MarkerFactory.getMarker("basic"), LOG_MESSAGE); assertThat(GelfTestSender.getMessages()).hasSize(1); GelfMessage gelfMessage = GelfTestSender.getMessages().get(0); assertThat(gelfMessage.getFullMessage()).isEqualTo(EXPECTED_LOG_MESSAGE); assertThat(gelfMessage.getShortMessage()).isEqualTo(EXPECTED_LOG_MESSAGE); assertThat(gelfMessage.getAdditonalFields().get("Marker")).isEqualTo("basic"); assertThat(gelfMessage.getLevel()).isEqualTo("6"); assertThat(gelfMessage.getMaximumMessageSize()).isEqualTo(8192); }
private org.slf4j.Marker getMarker(final Marker marker) { if (marker == null) { return null; } final org.slf4j.Marker slf4jMarker = MarkerFactory.getMarker(marker.getName()); final Marker[] parents = marker.getParents(); if (parents != null) { for (final Marker parent : parents) { final org.slf4j.Marker slf4jParent = getMarker(parent); if (!slf4jMarker.contains(slf4jParent)) { slf4jMarker.add(slf4jParent); } } } return slf4jMarker; }
@PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet()); if (hikariDataSource != null) { log.debug("Monitoring the datasource"); hikariDataSource.setMetricRegistry(metricRegistry); } if (jHipsterProperties.getMetrics().getJmx().isEnabled()) { log.debug("Initializing Metrics JMX reporting"); JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build(); jmxReporter.start(); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { log.info("Initializing Metrics Log reporting"); Marker metricsMarker = MarkerFactory.getMarker("metrics"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LoggerFactory.getLogger("metrics")) .markWith(metricsMarker) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS); } }
@PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JCACHE_STATISTICS, new JCacheGaugeSet()); if (hikariDataSource != null) { log.debug("Monitoring the datasource"); hikariDataSource.setMetricRegistry(metricRegistry); } if (jHipsterProperties.getMetrics().getJmx().isEnabled()) { log.debug("Initializing Metrics JMX reporting"); JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build(); jmxReporter.start(); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { log.info("Initializing Metrics Log reporting"); Marker metricsMarker = MarkerFactory.getMarker("metrics"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LoggerFactory.getLogger("metrics")) .markWith(metricsMarker) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS); } }
@Test public void verify_captured_events_with_marker() { captureLogEvents(() -> log.info(MarkerFactory.getMarker("a_marker"), "a message")) .logged(aLog() .withLevel(equalTo(INFO)) .withMarker("a_marker") .withMessage(equalTo("a message"))); }
@Test public void match_for_expected_marker() { LoggingEvent logEvent = aLoggingEventWith(INFO, "message"); logEvent.setMarker(MarkerFactory.getMarker("A_MARKER")); ExpectedLoggingMessage expectedLoggingMessage = aLog() .withMarker(MarkerFactory.getMarker("A_MARKER")); boolean matches = expectedLoggingMessage.matches(logEvent); assertThat(matches).isTrue(); }
@Test public void match_for_expected_marker_label() { LoggingEvent logEvent = aLoggingEventWith(INFO, "message"); logEvent.setMarker(MarkerFactory.getMarker("A_MARKER")); ExpectedLoggingMessage expectedLoggingMessage = aLog() .withMarker("A_MARKER"); boolean matches = expectedLoggingMessage.matches(logEvent); assertThat(matches).isTrue(); }
@Test public void no_match_for_unexpected_marker() { LoggingEvent logEvent = aLoggingEventWith(INFO, "message"); logEvent.setMarker(MarkerFactory.getMarker("A_MARKER")); ExpectedLoggingMessage expectedLoggingMessage = aLog() .withMarker("ANOTHER_MARKER"); boolean matches = expectedLoggingMessage.matches(logEvent); assertThat(matches).isFalse(); }
@Test public void testBlocksNonMetricMarker() { LoggingEvent event = new LoggingEvent(); event.setMarker(MarkerFactory.getMarker("FOO")); MetricPassFilter filter = new MetricPassFilter(); filter.start(); assertEquals(FilterReply.DENY, filter.decide(event)); }
@Test public void testMetricLogger() { PrintStream original = System.out; try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(outputStream, true)); MDC.put("AWSRequestId", "AWS-REQUEST-ID"); Logger logger = LoggerFactory.getLogger("TEST-LOGGER"); MetricRegistry registry = new MetricRegistry(); registry.registerAll(new TestMetricSet()); Slf4jReporter reporter = Slf4jReporter.forRegistry(registry) .markWith(MarkerFactory.getMarker("METRIC")) .outputTo(logger) .build(); reporter.report(); assertThat(outputStream.toString(), matchesPattern("^\\[[0-9\\-:\\. ]{23}\\] AWS-REQUEST-ID METRIC TEST-LOGGER type COUNTER name " + TestMetricSet.class.getCanonicalName() + "/testCounter count 0\\n$")); } finally { System.setOut(original); } }
@Test public void testPassesNonMetricMarker() { LoggingEvent event = new LoggingEvent(); event.setMarker(MarkerFactory.getMarker("FOO")); MetricBlockFilter filter = new MetricBlockFilter(); filter.start(); assertEquals(FilterReply.NEUTRAL, filter.decide(event)); }
public static void write(Class clazz, LogLevel logLevel, String message) { Logger logger = LoggerFactory.getLogger(clazz); switch (logLevel) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: logger.error(message); break; case FATAL: Marker marker = MarkerFactory.getMarker("FATAL"); logger.error(marker, message); break; default: logger.warn("No suitable log level found"); break; } }
@Override public void log(Class<?> clazz, String method, Level level, String message, Throwable ex) { Trace LOGGER = TraceManager.getTrace(clazz); //Mark all messages from ICF as ICF Marker m = MarkerFactory.getMarker("ICF"); //Translate ICF logging into slf4j // OK -> trace // INFO -> debug // WARN -> warn // ERROR -> error if (Level.OK.equals(level)) { if (null == ex) { LOGGER.trace(m, "method: {} msg:{}", method, message); } else { LOGGER.trace(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } else if (Level.INFO.equals(level)) { if (null == ex) { LOGGER.debug(m, "method: {} msg:{}", method, message); } else { LOGGER.debug(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } else if (Level.WARN.equals(level)) { if (null == ex) { LOGGER.warn(m, "method: {} msg:{}", method, message); } else { LOGGER.warn(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } else if (Level.ERROR.equals(level)) { if (null == ex) { LOGGER.error(m, "method: {} msg:{}", method, message); } else { LOGGER.error(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } }
@Test void testMarker() { Logger logger = LoggerFactory.getLogger("test"); final Marker marker = MarkerFactory.getMarker("TEST"); logger.info(marker, "hello"); }