public void sometimesFails() { log.warn("This is a warning."); log.info("This is purely informational."); List<LoggingEvent> logs = (List<LoggingEvent>) TestNGLogCollector.getRawLogs(); assertThat(logs) .hasSize(2) .anySatisfy(e -> assertThat(e.getLevel()).isEqualTo(Level.WARN)) .anySatisfy(e -> assertThat(e.getLevel()).isEqualTo(Level.INFO)); invocationCount++; if (invocationCount > 8) { Assert.fail(); } }
@Test public void testDefaultValues() { final Context mockContext = mock(Context.class); final PutLogEventsResult mockResult = mock(PutLogEventsResult.class); when(mockResult.getNextSequenceToken()).thenReturn("2"); final AWSLogs mockAwsLogs = mock(AWSLogs.class); when(mockAwsLogs.putLogEvents(any())).thenReturn(mockResult); final CloudWatchAppender appender = new CloudWatchAppender(); appender.setContext(mockContext); appender.setAwsLogs(mockAwsLogs); appender.start(); appender.doAppend(new LoggingEvent()); appender.stop(); }
@Test public void testAlreadyExists() { final Context mockContext = mock(Context.class); final PutLogEventsResult mockResult = mock(PutLogEventsResult.class); when(mockResult.getNextSequenceToken()).thenReturn("2"); final AWSLogs mockAwsLogs = mock(AWSLogs.class); when(mockAwsLogs.createLogGroup(any())).thenThrow(ResourceAlreadyExistsException.class); when(mockAwsLogs.createLogStream(any())).thenThrow(ResourceAlreadyExistsException.class); when(mockAwsLogs.putLogEvents(any())).thenReturn(mockResult); final CloudWatchAppender appender = new CloudWatchAppender(); appender.setContext(mockContext); appender.setAwsLogs(mockAwsLogs); appender.start(); appender.doAppend(new LoggingEvent()); appender.stop(); }
@Override protected void append(Object eventObject) { if (eventObject == null) { return; } if ( ! eventObject.getClass().isAssignableFrom(LoggingEvent.class) ) { return; } LoggingEvent event = (LoggingEvent) eventObject; String logEntry = event.getFormattedMessage(); if (logEntry == null || logEntry.isEmpty()) { return; } int end = logEntry.indexOf("("); if (end > 0) { String methodName = logEntry.substring(0, end); if (ignoredConsoleEntries.contains(methodName)) { return; } } logEntries.add(logEntry); }
@Test public void testMEssagesStream() { nifiAppender.start(); int i = 0; boolean run=true; while (run) { LoggingEvent event = new LoggingEvent(); event.setMessage("{\"message\":\"rest in peace for " + i + " \" }"); nifiAppender.append(event); i++; try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (i > 10) run=false; } }
public static LoggingInfo build(LoggingEvent loggingEvent) { LoggingInfo loggingInfo = new LoggingInfo(); if (null != loggingEvent) { loggingInfo.setMessage(loggingEvent.getMessage()); loggingInfo.setLevel(loggingEvent.getLevel().toString()); loggingInfo.setLoggerName(loggingEvent.getLoggerName()); loggingInfo.setThreadName(loggingEvent.getThreadName()); if (null != loggingEvent.getThrowableProxy()) { loggingInfo.setExceptionName(loggingEvent.getThrowableProxy().getClassName()); loggingInfo.setExceptionMessage(loggingEvent.getThrowableProxy().getMessage()); StackTraceElementProxy[] stackTraces = loggingEvent.getThrowableProxy().getStackTraceElementProxyArray(); if (null != stackTraces && stackTraces.length > 0) { loggingInfo.setTopStackTrace(stackTraces[0].getStackTraceElement().toString()); } } if (loggingEvent.hasCallerData()) { StackTraceElement st = loggingEvent.getCallerData()[0]; loggingInfo.setCallerData(st.toString()); } loggingInfo.setMdcProperty(loggingEvent.getMDCPropertyMap()); loggingInfo.setCreateTime(millisecondToDateTime(loggingEvent.getTimeStamp())); } return loggingInfo; }
@Test public void shouldNotCaptureLogTentantAwareLogWhenEventLevelIsDifferentFromDeviceLevel() { ILoggingEvent logEvent = new LoggingEvent( LOG.getName(), LOG, Level.DEBUG, "Test Message", null, new Object[]{device.toURI(), device.getLogLevel()} ); konkerLoggerAppender.append(logEvent); Mockito.verify(konkerLoggerAppender, Mockito.never()) .store(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); }
@Test public void shouldNotCaptureTenantAwareLogWhenEventHasNoURI(){ ILoggingEvent logEvent = new LoggingEvent( LOG.getName(), LOG, Level.DEBUG, "Test Message", null, new Object[]{device.getLogLevel()} ); konkerLoggerAppender.append(logEvent); Mockito.verify(konkerLoggerAppender, Mockito.never()) .store(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); }
@Test public void shouldNotCaptureTenantAwareLogWhenEventHasNoContextLogLevel(){ ILoggingEvent logEvent = new LoggingEvent( LOG.getName(), LOG, Level.DEBUG, "Test Message", null, new Object[]{device.toURI()} ); konkerLoggerAppender.append(logEvent); Mockito.verify(konkerLoggerAppender, Mockito.never()) .store(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); }
@Test public void shouldCaptureTenantAwareLog() { ILoggingEvent logEvent = new LoggingEvent( LOG.getName(), LOG, Level.INFO, "Test Message", null, new Object[]{device.toURI(), device.getLogLevel()} ); konkerLoggerAppender.append(logEvent); Mockito.verify(konkerLoggerAppender, Mockito.atLeastOnce()) .store(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); }
@Test public void start_ShouldWaitAndLogUntilDatabaseIsAccessible() throws Exception { Connection mockConnection = mock(Connection.class); when(mockApplicationStartupDependentResource.getDatabaseConnection()) .thenThrow(new SQLException("not there yet")) .thenReturn(mockConnection); applicationStartupDependentResourceChecker.checkAndWaitForResources(); verify(mockApplicationStartupDependentResource, times(2)).getDatabaseConnection(); verify(mockApplicationStartupDependentResource).sleep(5000L); verify(mockAppender, times(3)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> allValues = loggingEventArgumentCaptor.getAllValues(); assertThat(allValues.get(0).getFormattedMessage(), is("Checking for database availability >>>")); assertThat(allValues.get(1).getFormattedMessage(), is("Waiting for 5 seconds till the database is available ...")); assertThat(allValues.get(2).getFormattedMessage(), is("Database available.")); }
@Test public void start_ShouldProgressivelyIncrementSleepingTimeBetweenChecksForDBAccessibility() throws Exception { Connection mockConnection = mock(Connection.class); when(mockApplicationStartupDependentResource.getDatabaseConnection()) .thenThrow(new SQLException("not there")) .thenThrow(new SQLException("not there yet")) .thenThrow(new SQLException("still not there")) .thenReturn(mockConnection); applicationStartupDependentResourceChecker.checkAndWaitForResources(); verify(mockApplicationStartupDependentResource, times(4)).getDatabaseConnection(); verify(mockApplicationStartupDependentResource).sleep(5000L); verify(mockApplicationStartupDependentResource).sleep(10000L); verify(mockApplicationStartupDependentResource).sleep(15000L); verify(mockAppender, times(5)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> logStatement = loggingEventArgumentCaptor.getAllValues(); assertThat(logStatement.get(0).getFormattedMessage(), is("Checking for database availability >>>")); assertThat(logStatement.get(1).getFormattedMessage(), is("Waiting for 5 seconds till the database is available ...")); assertThat(logStatement.get(2).getFormattedMessage(), is("Waiting for 10 seconds till the database is available ...")); assertThat(logStatement.get(3).getFormattedMessage(), is("Waiting for 15 seconds till the database is available ...")); assertThat(logStatement.get(4).getFormattedMessage(), is("Database available.")); }
@Override public void addStatusEvent(final Status status) { final Level level; switch (status.getLevel()) { case Status.INFO: level = Level.INFO; break; case Status.WARN: level = Level.WARN; break; case Status.ERROR: level = Level.ERROR; break; default: level = Level.INFO; break; } final LoggingEvent event = new LoggingEvent(StatusToFileListener.class.getSimpleName(), new LoggerContext().getLogger(StatusToFileListener.class), level, status.getMessage(), null, null); append(event); }
@Override public FilterReply decide(E eventObject) { if (!isStarted()) { return FilterReply.NEUTRAL; } LoggingEvent event = (LoggingEvent) eventObject; if (this.levelMin != null && !event.getLevel().isGreaterOrEqual(levelMin)) { return DENY; } if (this.levelMax != null && event.getLevel().toInt() > levelMax.toInt()) { return DENY; } if (acceptOnMatch) { return ACCEPT; } else { return NEUTRAL; } }
@Test public void testBuildsMessage() { AppenderForTest appender = new AppenderForTest(); appender.setChannel("channel"); appender.setUsername("username"); appender.setIconEmoji("icon-emoji"); appender.setIconUrl("icon-url"); appender.setLinkNames(true); LoggingEvent event = new LoggingEvent(); event.setMessage("text \"quoted\""); appender.append(event); String actual = new String(appender.body, StandardCharsets.UTF_8); String expected = "{ \"text\": \"text \\\"quoted\\\"\", \"channel\": \"channel\", \"username\": \"username\", \"icon_emoji\": \"icon-emoji\", \"icon_url\": \"icon-url\", \"link_names\": 1 }"; Assert.assertEquals(expected, actual); }
@Test public void shouldLogEntryAndExitPointsOfEndPoints() throws Exception { String requestId = UUID.randomUUID().toString(); String requestUrl = "/cardid-request"; String requestMethod = "POST"; when(mockRequest.getRequestURI()).thenReturn(requestUrl); when(mockRequest.getMethod()).thenReturn(requestMethod); when(mockRequest.getHeader(HEADER_REQUEST_ID)).thenReturn(requestId); loggingFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", requestId, requestMethod, requestUrl))); String endLogMessage = loggingEvents.get(1).getFormattedMessage(); assertThat(endLogMessage, containsString(format("[%s] - %s to %s ended - total time ", requestId, requestMethod, requestUrl))); String[] timeTaken = StringUtils.substringsBetween(endLogMessage, "total time ", "ms"); assertTrue(NumberUtils.isNumber(timeTaken[0])); verify(mockFilterChain).doFilter(mockRequest, mockResponse); }
@Test public void shouldLogEntryAndExitPointsEvenIfRequestIdDoesNotExist() throws Exception { String requestUrl = "/cardid-request"; String requestMethod = "POST"; when(mockRequest.getRequestURI()).thenReturn(requestUrl); when(mockRequest.getMethod()).thenReturn(requestMethod); loggingFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", "", requestMethod, requestUrl))); String endLogMessage = loggingEvents.get(1).getFormattedMessage(); assertThat(endLogMessage, containsString(format("[%s] - %s to %s ended - total time ", "", requestMethod, requestUrl))); verify(mockFilterChain).doFilter(mockRequest, mockResponse); }
@Test public void shouldLogEntryAndExitPointsOfEndPoints() throws Exception { String requestId = UUID.randomUUID().toString(); String requestUrl = "/publicauth-request"; String requestMethod = "GET"; when(mockRequest.getRequestURI()).thenReturn(requestUrl); when(mockRequest.getMethod()).thenReturn(requestMethod); when(mockRequest.getHeader(HEADER_REQUEST_ID)).thenReturn(requestId); loggingFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", requestId, requestMethod, requestUrl))); String endLogMessage = loggingEvents.get(1).getFormattedMessage(); assertThat(endLogMessage, containsString(format("[%s] - %s to %s ended - total time ", requestId, requestMethod, requestUrl))); String[] timeTaken = StringUtils.substringsBetween(endLogMessage, "total time ", "ms"); assertTrue(NumberUtils.isNumber(timeTaken[0])); verify(mockFilterChain).doFilter(mockRequest, mockResponse); }
@Test public void shouldLogEntryAndExitPointsEvenIfRequestIdDoesNotExist() throws Exception { String requestUrl = "/publicauth-request"; String requestMethod = "GET"; when(mockRequest.getRequestURI()).thenReturn(requestUrl); when(mockRequest.getMethod()).thenReturn(requestMethod); loggingFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", "", requestMethod, requestUrl))); String endLogMessage = loggingEvents.get(1).getFormattedMessage(); assertThat(endLogMessage, containsString(format("[%s] - %s to %s ended - total time ", "", requestMethod, requestUrl))); verify(mockFilterChain).doFilter(mockRequest, mockResponse); }
@Test public void ignoreDefaultLocale() { Locale originalDefaultLocale = Locale.getDefault(); Locale.setDefault(Locale.TRADITIONAL_CHINESE); try { converter.start(); LoggingEvent le = createLoggingEvent(); calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); le.setTimeStamp(calendar.getTimeInMillis()); String result = converter.convert(le); assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", result); } finally { Locale.setDefault(originalDefaultLocale); } }
@Test public void testSimpleEvaluator() throws NullPointerException, EvaluationException, JoranException { JoranConfigurator jc = new JoranConfigurator(); LoggerContext loggerContext = new LoggerContext(); jc.setContext(loggerContext); jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "simpleEvaluator.xml"); Map evalMap = (Map) loggerContext.getObject(CoreConstants.EVALUATOR_MAP); assertNotNull(evalMap); JaninoEventEvaluator evaluator = (JaninoEventEvaluator) evalMap.get("msgEval"); assertNotNull(evaluator); Logger logger = loggerContext.getLogger("xx"); ILoggingEvent event0 = new LoggingEvent("foo", logger, Level.DEBUG, "Hello world", null, null); assertTrue(evaluator.evaluate(event0)); ILoggingEvent event1 = new LoggingEvent("foo", logger, Level.DEBUG, "random blurb", null, null); assertFalse(evaluator.evaluate(event1)); }
@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()); }
@Test public void testMultipleConditionsInExpression() throws NullPointerException, EvaluationException { LoggerContext loggerContext = new LoggerContext(); Logger logger = loggerContext.getLogger("xx"); JaninoEventEvaluator ee = new JaninoEventEvaluator(); ee.setName("testEval"); ee.setContext(loggerContext); //&& //&& ee.setExpression("message.contains(\"stacktrace\") && message.contains(\"logging\")"); ee.start(); //StatusPrinter.print(loggerContext); String message = "stacktrace bla bla logging"; ILoggingEvent event = new LoggingEvent(this.getClass().getName(), logger, Level.DEBUG, message, null, null); assertTrue(ee.evaluate(event)); }
public LoggingEvent build(int i) { LoggingEvent le = new LoggingEvent(); le.setTimeStamp(System.currentTimeMillis()); Object[] aa = new Object[] { i, "HELLO WORLD [========== ]" + i }; le.setArgumentArray(aa); String msg = MSG + i; le.setMessage(msg); // compute formatted message // this forces le.formmatedMessage to be set (this is the whole point of the // exercise) le.getFormattedMessage(); le.setLevel(Level.DEBUG); le.setLoggerName(logger.getName()); le.setLoggerContextRemoteView(loggerContext.getLoggerContextRemoteView()); le.setThreadName("threadName"); return le; }
@Before public void setUp() throws Exception { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); appender = new MockAppender(); appender.start(); logger = lc.getLogger(getClass()); logger.addAppender(appender); event = new LoggingEvent(logger.getName(), logger, Level.DEBUG, "test message", null, new Object[0]); LoggingEventVO eventVO = LoggingEventVO.build(event); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(eventVO); oos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); client = new RemoteAppenderStreamClient("some client ID", bis); client.setLoggerContext(lc); }
@Test public void testDispatchEventForEnabledLevel() throws Exception { receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); receiver.setPort(6000); receiver.start(); assertTrue(receiver.awaitConnectorCreated(DELAY)); Socket socket = serverSocket.accept(); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); logger.setLevel(Level.DEBUG); ILoggingEvent event = new LoggingEvent(logger.getName(), logger, Level.DEBUG, "test message", null, new Object[0]); LoggingEventVO eventVO = LoggingEventVO.build(event); oos.writeObject(eventVO); oos.flush(); ILoggingEvent rcvdEvent = appender.awaitAppend(DELAY); assertNotNull(rcvdEvent); assertEquals(event.getLoggerName(), rcvdEvent.getLoggerName()); assertEquals(event.getLevel(), rcvdEvent.getLevel()); assertEquals(event.getMessage(), rcvdEvent.getMessage()); }
@Test public void testNoDispatchEventForDisabledLevel() throws Exception { receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); receiver.setPort(6000); receiver.start(); assertTrue(receiver.awaitConnectorCreated(DELAY)); Socket socket = serverSocket.accept(); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); logger.setLevel(Level.INFO); ILoggingEvent event = new LoggingEvent(logger.getName(), logger, Level.DEBUG, "test message", null, new Object[0]); LoggingEventVO eventVO = LoggingEventVO.build(event); oos.writeObject(eventVO); oos.flush(); assertNull(appender.awaitAppend(DELAY)); }
@Test public void testWholeCycle() throws JoranException { String mdcKey = "cycle"; configure(SIFT_FOLDER_PREFIX + "completeCycle.xml"); MDC.put(mdcKey, "a"); logger.debug("smoke"); long timestamp = System.currentTimeMillis(); SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); ListAppender<ILoggingEvent> listAppender = (ListAppender<ILoggingEvent>) sa.getAppenderTracker().find("a"); assertNotNull(listAppender); List<ILoggingEvent> eventList = listAppender.list; assertEquals(1, listAppender.list.size()); assertEquals("smoke", eventList.get(0).getMessage()); MDC.remove(mdcKey); LoggingEvent le = new LoggingEvent("x", logger, Level.INFO, "hello", null, null); le.setTimeStamp(timestamp + ComponentTracker.DEFAULT_TIMEOUT + 1); sa.doAppend(le); assertFalse(listAppender.isStarted()); assertEquals(1, sa.getAppenderTracker().allKeys().size()); assertTrue(sa.getAppenderTracker().allKeys().contains("cycleDefault")); }
@Test public void maxAppendersCountPropertyShouldBeHonored() throws JoranException { configure(SIFT_FOLDER_PREFIX + "maxAppenderCount.xml"); int max = 5; SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); String mdcKey = "max"; for(int i = 0; i <= max; i++) { MDC.put(mdcKey, "" + (diff + i)); LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "max"+i, null, null); event.setTimeStamp(now); sa.doAppend(event); now += AbstractComponentTracker.WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS; } AppenderTracker<ILoggingEvent> tracker = sa.getAppenderTracker(); assertEquals(max, tracker.allKeys().size()); assertNull(tracker.find("" + (diff + 0))); for(int i = 1; i <= max; i++) { assertNotNull(tracker.find("" + (diff + i))); } }
@Test public void timeoutPropertyShouldBeHonored() throws JoranException, InterruptedException { configure(SIFT_FOLDER_PREFIX + "timeout.xml"); long timeout = 30*1000; SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "timeout", null, null); event.setTimeStamp(now); sa.doAppend(event); AppenderTracker<ILoggingEvent> tracker = sa.getAppenderTracker(); assertEquals(1, tracker.getComponentCount()); now += timeout+1; tracker.removeStaleComponents(now); assertEquals(0, tracker.getComponentCount()); statusChecker.assertIsErrorFree(); }
@Test @Ignore public void rawLimit() throws Exception { StringBuilder sb = new StringBuilder(); String header = layout.getFileHeader(); assertTrue(header .startsWith("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">")); sb.append(header); sb.append(layout.getPresentationHeader()); for (int i = 0; i < CoreConstants.TABLE_ROW_LIMIT * 3; i++) { sb.append(layout.doLayout(new LoggingEvent(this.getClass().getName(), root, Level.DEBUG, "test message" + i, null, null))); } sb.append(layout.getPresentationFooter()); sb.append(layout.getFileFooter()); // check that the output adheres to xhtml-strict.dtd parseOutput(sb.toString()); }
@Test public void shouldLogEntryAndExitPointsOfEndPoints() throws Exception { String requestUrl = "/publicapi-request"; String requestId = UUID.randomUUID().toString(); String requestMethod = "GET"; when(mockRequest.getRequestURI()).thenReturn(requestUrl); when(mockRequest.getMethod()).thenReturn(requestMethod); when(mockRequest.getHeader(HEADER_REQUEST_ID)).thenReturn(requestId); loggingFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", requestId, requestMethod, requestUrl))); String endLogMessage = loggingEvents.get(1).getFormattedMessage(); assertThat(endLogMessage, containsString(format("[%s] - %s to %s ended - total time ", requestId, requestMethod, requestUrl))); String[] timeTaken = StringUtils.substringsBetween(endLogMessage, "total time ", "ms"); assertTrue(NumberUtils.isNumber(timeTaken[0])); verify(mockFilterChain).doFilter(mockRequest, mockResponse); }
@Test public void shouldLogEntryAndExitPointsEvenIfRequestIdDoesNotExist() throws Exception { String requestUrl = "/publicapi-request"; String requestMethod = "GET"; when(mockRequest.getRequestURI()).thenReturn(requestUrl); when(mockRequest.getMethod()).thenReturn(requestMethod); loggingFilter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", "", requestMethod, requestUrl))); String endLogMessage = loggingEvents.get(1).getFormattedMessage(); assertThat(endLogMessage, containsString(format("[%s] - %s to %s ended - total time ", "", requestMethod, requestUrl))); verify(mockFilterChain).doFilter(mockRequest, mockResponse); }
@Test public void shouldLogRestClientStartEventWithRequestId() throws Exception { String requestId = UUID.randomUUID().toString(); URI requestUrl = URI.create("/publicapi-request"); String requestMethod = "GET"; MultivaluedMap<String, Object> mockHeaders = new MultivaluedHashMap<>(); when(clientRequestContext.getUri()).thenReturn(requestUrl); when(clientRequestContext.getMethod()).thenReturn(requestMethod); when(clientRequestContext.getHeaders()).thenReturn(mockHeaders); MDC.put(HEADER_REQUEST_ID,requestId); loggingFilter.filter(clientRequestContext); verify(mockAppender, times(1)).doAppend(loggingEventArgumentCaptor.capture()); List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues(); assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", requestId, requestMethod, requestUrl))); }
@Test public void test_parallel_logger() { int logNum = 1000; IntStream.range(0, logNum) .parallel() .forEach(i -> { logger.with("data", i) .info("test" + i); }); final List<LoggingEvent> loggingEvents = getLoggingEvents(); loggingEvents.sort((a, b) -> a.getMessage().compareTo(b.getMessage())); final Set<String> collect = loggingEvents.stream().map(i -> i.getFormattedMessage()).collect(toSet()); for (int i = 0; i < logNum; i++) { assertTrue(collect.contains(String.format("test%s; data=%s", String.valueOf(i), String.valueOf(i)))); } }
@org.junit.Test public void testAppender() { ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); Appender mockAppender = mock(Appender.class); root.addAppender(mockAppender); Appender<ILoggingEvent> appender = root.getAppender("SNMP"); LOG.info("server error", new RuntimeException("info message")); LOG.error("server error", new RuntimeException("error message")); verify(mockAppender,times(2)).doAppend(argThat(new ArgumentMatcher<ILoggingEvent>() { @Override public boolean matches(final Object argument) { return ((LoggingEvent) argument).getFormattedMessage().contains("server error"); } })); Assert.assertThat(appender.getClass().getName(), is(equalTo("com.sathwik.logback.appender.SNMPTrapAppender"))); }
@Test public void testTranslate() throws Exception { //Given LoggerContext context = new LoggerContext(); Logger logger = context.getLogger("SomeLogger"); LoggingEvent le = new LoggingEvent("a.b.C",logger, ch.qos.logback.classic.Level.INFO,"message",null,null); final Map<String, String> split = Splitter.on(",").withKeyValueSeparator("=").split("a=b,b=as"); le.setMDCPropertyMap(split); le.setCallerData(new StackTraceElement[]{new StackTraceElement("a.b.C","someMethod","C.java",120)}); //when final LogData logData = LogbackUtil.translate(le).build(); //then assertEquals(logData.getMessage(),"message"); assertEquals(logData.getLevel(),Level.INFO); assertEquals(logData.getLoggerName(),"SomeLogger"); assertEquals(logData.getClazz(),"a.b.C"); assertEquals(logData.getMethod(),"someMethod"); assertEquals(logData.getLine(),"120"); assertEquals(logData.getProperties(),split); }
private static void logEvent(Ehcache cache, Element elem, CacheEventType eventType) { int cacheApproxSize = -1; if (cache.getStatus() == Status.STATUS_ALIVE) { try { cacheApproxSize = cache.getSize(); } catch (CacheException | IllegalStateException ignored) { } } LoggingEvent loggingEvent = new LoggingEvent(Logger.FQCN, LOGGER, Level.TRACE, String.format(MSG_FORMAT, cache.getName(), cache.getStatus(), cacheApproxSize, elem.getObjectKey(), eventType.getId()), null, null); StackTraceElement[] stackFrames = new Throwable().getStackTrace(); for (int a = 1; a < stackFrames.length; a++) { if (!STACK_SKIP_CLASS_NAMES.contains(stackFrames[a].getClassName())) { stackFrames = ArrayUtils.subarray(stackFrames, a, stackFrames.length); break; } } loggingEvent.setCallerData(stackFrames); LOGGER.callAppenders(loggingEvent); }