Search in sources :

Example 6 with LoggingEvent

use of org.apache.log4j.spi.LoggingEvent in project commons by twitter.

the class JULBridgeLogManagerTest method checkAssimilateTakesOver.

@Test
public void checkAssimilateTakesOver() {
    // Create a test log4j environment
    final List<LoggingEvent> events = new LinkedList<LoggingEvent>();
    org.apache.log4j.Logger log4jRoot = new RootLogger(org.apache.log4j.Level.ALL);
    LoggerRepository loggerRepository = new Hierarchy(log4jRoot);
    loggerRepository.setThreshold(org.apache.log4j.Level.INFO);
    log4jRoot.addAppender(new AppenderSkeleton() {

        @Override
        public boolean requiresLayout() {
            return false;
        }

        @Override
        public void close() {
        }

        @Override
        protected void append(LoggingEvent event) {
            events.add(event);
        }
    });
    JULBridgeLogManager.assimilate(loggerRepository);
    Logger.getLogger("test.1").log(Level.INFO, "test message 1");
    Logger.getLogger("test.2").log(Level.FINE, "test message 2");
    Logger.getLogger("test.3").log(Level.WARNING, "test message 3");
    assertThat(events.size(), is(2));
    assertThat(events.get(0).getLoggerName(), is("test.1"));
    assertThat(events.get(0).getMessage(), is((Object) "test message 1"));
    assertThat(events.get(1).getLoggerName(), is("test.3"));
    assertThat(events.get(1).getMessage(), is((Object) "test message 3"));
}
Also used : LoggingEvent(org.apache.log4j.spi.LoggingEvent) LoggerRepository(org.apache.log4j.spi.LoggerRepository) Hierarchy(org.apache.log4j.Hierarchy) AppenderSkeleton(org.apache.log4j.AppenderSkeleton) RootLogger(org.apache.log4j.spi.RootLogger) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 7 with LoggingEvent

use of org.apache.log4j.spi.LoggingEvent in project commons by twitter.

the class JULBridgeHandlerTest method checkToLoggingEvent.

@Test
public void checkToLoggingEvent() {
    LogRecord record = new LogRecord(Level.FINEST, "test is {0}");
    record.setParameters(new Object[] { "successful" });
    record.setThreadID(42);
    Throwable t = new Throwable();
    record.setThrown(t);
    // source class and method names are usually inferred, but because there's no JUL in the stack
    // frame, it won't work as expected.
    record.setSourceClassName(getClass().getName());
    record.setSourceMethodName("checkToLoggingEvent");
    Logger log4jLogger = new JULBridgeHandler().getLogger(record);
    org.apache.log4j.Level log4jLevel = JULBridgeLevelConverter.toLog4jLevel(Level.FINEST);
    LoggingEvent event = JULBridgeHandler.toLoggingEvent(record, log4jLogger, log4jLevel, false);
    assertThat(event.getLogger(), is((Category) log4jLogger));
    assertThat(event.getLevel(), is(log4jLevel));
    assertThat(event.getMessage(), is((Object) "test is successful"));
    assertThat(event.getThreadName(), is("42"));
    assertThat(event.getTimeStamp(), is(record.getMillis()));
    assertThat(event.getThrowableInformation().getThrowable(), is(sameInstance(t)));
    LocationInfo info = event.getLocationInformation();
    assertThat(info.getClassName(), is(getClass().getName()));
    assertThat(info.getMethodName(), is("checkToLoggingEvent"));
}
Also used : JULBridgeHandler(com.twitter.common.logging.julbridge.JULBridgeHandler) LoggingEvent(org.apache.log4j.spi.LoggingEvent) Category(org.apache.log4j.Category) LogRecord(java.util.logging.LogRecord) Logger(org.apache.log4j.Logger) LocationInfo(org.apache.log4j.spi.LocationInfo) Test(org.junit.Test)

Example 8 with LoggingEvent

use of org.apache.log4j.spi.LoggingEvent in project h2o-3 by h2oai.

the class CustomHttpFilterTest method testNoLog.

@Test
public void testNoLog() throws Exception {
    final Logger _logger = Logger.getLogger("water.default");
    _logger.addAppender(new AppenderSkeleton() {

        @Override
        protected void append(LoggingEvent event) {
            if (event.getRenderedMessage().contains("GET"))
                throw new RuntimeException("All GETs should be filtered");
        }

        @Override
        public void close() {
            _logger.removeAppender(this);
        }

        @Override
        public boolean requiresLayout() {
            return false;
        }
    });
    // let's filter out all GETs
    RequestServer.setFilters(RequestServer.defaultFilter(), new RequestServer.HttpLogFilter() {

        @Override
        public boolean filter(RequestUri uri, Properties header, Properties parms) {
            String[] path = uri.getPath();
            return path[1].equals("GET");
        }
    });
    // mock up a "GET /flow/index.html" call
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    when(request.getServletPath()).thenReturn("/flow/index.html");
    when(request.getRequestURI()).thenReturn("/flow/index.html");
    // mock up the headers
    // define the headers you want to be returned
    HashMap<String, String> headers = new HashMap<>();
    headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36");
    headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    headers.put("Cookie", "_yummy");
    headers.put("Accept-Encoding", "gzip, deflate, sdch");
    headers.put("Host", H2O.getIpPortString());
    headers.put("Upgrade-Insecure-Requests", "1");
    headers.put("Accept-Language", "en-US,en;q=0.8");
    headers.put("Connection", "keep-alive");
    // create an Enumeration over the header keys
    final Iterator<String> iterator = headers.keySet().iterator();
    Enumeration headerNames = new Enumeration<String>() {

        @Override
        public boolean hasMoreElements() {
            return iterator.hasNext();
        }

        @Override
        public String nextElement() {
            return iterator.next();
        }
    };
    when(request.getHeaderNames()).thenReturn(headerNames);
    when(request.getHeader("User-Agent")).thenReturn(headers.get("User-Agent"));
    when(request.getHeader("Accept")).thenReturn(headers.get("Accept"));
    when(request.getHeader("Cookie")).thenReturn(headers.get("Cookie"));
    when(request.getHeader("Accept-Encoding")).thenReturn(headers.get("Accept-Encoding"));
    when(request.getHeader("Host")).thenReturn(headers.get("Host"));
    when(request.getHeader("Upgrade-Insecure-Requests")).thenReturn(headers.get("Upgrade-Insecure-Requests"));
    when(request.getHeader("Accept-Language")).thenReturn(headers.get("Accept-Language"));
    when(request.getHeader("Connection")).thenReturn(headers.get("Connection"));
    when(request.getParameterMap()).thenReturn(new HashMap<String, String[]>());
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
        }
    });
    // start the request lifecycle
    H2O.getJetty().getServer().getChildHandlersByClass(JettyHTTPD.GateHandler.class)[0].handle("/", null, request, response);
    new RequestServer().doGet(request, response);
}
Also used : AppenderSkeleton(org.apache.log4j.AppenderSkeleton) Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Logger(org.apache.log4j.Logger) Properties(java.util.Properties) LoggingEvent(org.apache.log4j.spi.LoggingEvent) HttpServletRequest(javax.servlet.http.HttpServletRequest) JettyHTTPD(water.JettyHTTPD) Test(org.junit.Test)

Example 9 with LoggingEvent

use of org.apache.log4j.spi.LoggingEvent in project symmetric-ds by JumpMind.

the class SymRollingFileAppenderTest method getLoggingEventForTest.

protected LoggingEvent getLoggingEventForTest(String message, Throwable ex, Level loggerLevel) {
    TestCategory category = new TestCategory(SymRollingFileAppenderTest.class.getName());
    category.setLevel(loggerLevel);
    LoggingEvent event = new LoggingEvent(SymRollingFileAppenderTest.class.getName(), category, System.currentTimeMillis(), Level.ERROR, message, ex);
    return event;
}
Also used : LoggingEvent(org.apache.log4j.spi.LoggingEvent)

Example 10 with LoggingEvent

use of org.apache.log4j.spi.LoggingEvent in project symmetric-ds by JumpMind.

the class SymRollingFileAppenderTest method testRollover.

@Test
public void testRollover() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
    SymRollingFileAppender appender = getAppenderForTest(os);
    Exception ex = new Exception("Test exception.");
    LoggingEvent event1 = getLoggingEventForTest("Test Exception.", ex);
    LoggingEvent event2 = getLoggingEventForTest("Test Exception.", ex);
    LoggingEvent event3 = getLoggingEventForTest("Test Exception.", ex);
    LoggingEvent event4 = getLoggingEventForTest("Test Exception.", ex);
    appender.append(event1);
    appender.append(event2);
    String logging = os.toString("UTF8");
    String stackTraceKey1 = null;
    // 2016-08-11 11:55:38,487 ERROR [] [SymRollingFileAppenderTest] [main] Test Exception. StackTraceKey.init [Exception:1478675418]
    Pattern initPattern = Pattern.compile(".*StackTraceKey.init \\[Exception:([0-9]*)\\].*", Pattern.DOTALL);
    {
        Matcher m = initPattern.matcher(logging);
        if (m.matches()) {
            {
                stackTraceKey1 = "Exception:" + m.group(1);
                assertEquals(2, StringUtils.countMatches(logging, stackTraceKey1));
            }
        } else {
            fail("Didn't find proper logging pattern.");
        }
    }
    appender.rollOver();
    os = new ByteArrayOutputStream(1024);
    appender.setOutputStream(os);
    appender.append(event3);
    appender.append(event4);
    logging = os.toString("UTF8");
    String stackTraceKey2 = null;
    {
        Matcher m = initPattern.matcher(logging);
        if (m.matches()) {
            {
                stackTraceKey2 = "Exception:" + m.group(1);
                assertEquals(2, StringUtils.countMatches(logging, stackTraceKey2));
            }
        } else {
            fail("Didn't find proper logging pattern.");
        }
    }
    // should reprint stack trace and get a new key after the roll over.
    assertEquals(stackTraceKey1, stackTraceKey2);
}
Also used : LoggingEvent(org.apache.log4j.spi.LoggingEvent) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) Test(org.junit.Test)

Aggregations

LoggingEvent (org.apache.log4j.spi.LoggingEvent)48 Test (org.junit.Test)21 Logger (org.apache.log4j.Logger)12 Pattern (java.util.regex.Pattern)7 Matcher (java.util.regex.Matcher)6 ByteArrayOutputStream (org.apache.commons.io.output.ByteArrayOutputStream)6 AppenderSkeleton (org.apache.log4j.AppenderSkeleton)3 LoggingException (com.axway.ats.log.autodb.exceptions.LoggingException)2 AbstractLoggingEvent (com.axway.ats.log.autodb.model.AbstractLoggingEvent)2 IOException (java.io.IOException)2 Appender (org.apache.log4j.Appender)2 Category (org.apache.log4j.Category)2 Level (org.apache.log4j.Level)2 Filter (org.apache.log4j.spi.Filter)2 LocationInfo (org.apache.log4j.spi.LocationInfo)2 InsertMessageEvent (com.axway.ats.log.autodb.events.InsertMessageEvent)1 CacheableEvent (com.axway.ats.log.autodb.model.CacheableEvent)1 SystemLogLevel (com.axway.ats.log.model.SystemLogLevel)1 CurrentUser (com.google.gerrit.server.CurrentUser)1 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)1