void run() { Logger rootLogger = Logger.getRootLogger(); List<LoggingEvent> events = new ArrayList<>(); Appender appender = new MockUp<Appender>() { @Mock public void doAppend(LoggingEvent event) { events.add(event); } }.getMockInstance(); rootLogger.addAppender(appender); doRun(events); rootLogger.removeAppender(appender); }
@Test public void testRegisterSchemaException() { InterruptedException e = new InterruptedException(); new MockUp<CountDownLatch>() { @Mock public void await() throws InterruptedException { throw e; } }; new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.registerSchema("msid", "schemaId", "content"); Assert.assertEquals( "register schema msid/schemaId fail.", events.get(0).getMessage()); Assert.assertEquals(e, events.get(0).getThrowableInformation().getThrowable()); } }.run(); }
public String format(LoggingEvent event){ if( event.getLevel() == Level.FATAL){ return fatalErrorColor+super.format(event)+END_COLOR; }else if( event.getLevel() == Level.ERROR){ return errorColor+super.format(event)+END_COLOR; }if( event.getLevel() == Level.WARN){ return super.format(event); // return warnColor+super.format(event)+END_COLOR; }if( event.getLevel() == Level.INFO){ return super.format(event); // return infoColor+super.format(event)+END_COLOR; }if( event.getLevel() == Level.DEBUG){ return super.format(event); // return debugColor+super.format(event)+END_COLOR; }else{ throw new RuntimeException("Unsupported Level "+event.toString()); } }
@Test public void decide() { assertNotNull(mdcFilter); mdcFilter.setExpression("MessageId!=null || LoggedBy!=null"); mdcFilter.setKeys("LoggedBy,MessageId"); final LoggingEvent event = new LoggingEvent("", LOG, LOG.getLevel(), "MessageId=123", null); MDC.put("LoggedBy", "abc"); MDC.put("fff", "abc"); final int ret = mdcFilter.decide(event); LOG.info("decide: " + ret); assertTrue(ret == Filter.NEUTRAL); }
@Override public void append(LoggingEvent event) { Level level = event.getLevel(); // depends on the api, == might not work // see HADOOP-7055 for details if (level.equals(Level.INFO)) { counts.incr(INFO); } else if (level.equals(Level.WARN)) { counts.incr(WARN); } else if (level.equals(Level.ERROR)) { counts.incr(ERROR); } else if (level.equals(Level.FATAL)) { counts.incr(FATAL); } }
@Test public void testLifecycleEvent() throws Exception { when(mockLifeCycle.getState()).thenReturn(LifecycleState.STOPPING); lifeCycleListener.lifecycleEvent(new LifecycleEvent(mockLifeCycle, null, null)); sleep(2500); when(mockLifeCycle.getState()).thenReturn(LifecycleState.STOPPED); lifeCycleListener.lifecycleEvent(new LifecycleEvent(mockLifeCycle, null, null)); sleep(2500); verify(mockAppender, atLeastOnce()).doAppend((LoggingEvent) captorLoggingEvent.capture()); final int eventTotal = captorLoggingEvent.getAllValues().size(); final LoggingEvent loggingEvent = (LoggingEvent) captorLoggingEvent.getAllValues().get(eventTotal - 1); assertEquals("Channel closed", loggingEvent.getMessage()); System.out.println(captorLoggingEvent.getAllValues().size()); // make sure that the scheduler has stopped by checking if there are extra events after the listener has processed // a STOPPED life cycle sleep(2500); // pause to let any rogue scheduler do logging if there are any... assertEquals(eventTotal, captorLoggingEvent.getAllValues().size()); }
/** * Log an event, writing a line in the log file of the form * <pre> * DATE EVENT_TYPE PARAM_1 PARAM_2 ... * </pre> */ synchronized void log(String eventType, Object... params) { try { if (logDisabled) return; StringBuffer buffer = new StringBuffer(); buffer.append(eventType); for (Object param: params) { buffer.append("\t"); buffer.append(param); } String message = buffer.toString(); Logger logger = Logger.getLogger(getClass()); appender.append(new LoggingEvent("", logger, Level.INFO, message, null)); } catch (Exception e) { LOG.error("Failed to append to fair scheduler event log", e); logDisabled = true; } }
/** * 覆写doAppend, 去掉closed的log日志 * @param event */ @Override public synchronized void doAppend(LoggingEvent event) { if (closed) { return; } if (!isAsSevereAsThreshold(event.getLevel())) { return; } Filter f = this.headFilter; FILTER_LOOP: while(f != null) { switch(f.decide(event)) { case Filter.DENY: return; case Filter.ACCEPT: break FILTER_LOOP; case Filter.NEUTRAL: f = f.getNext(); } } this.append(event); }
/** * Returns Filter#DENY if Expression returns false based on the values * returned from the MDC Context. * * @param event * <code>LoggingEvent</code> */ public int decide(final LoggingEvent event) { int ret = DENY; if (keys != null && expression != null) { final List<Object> mdcValues = new ArrayList<Object>(); final List<Class<String>> keyTypes = new ArrayList<Class<String>>(); final String[] keyValues = keys.split(SPLIT_EXPRESSION); if (keyValues != null) { for (final String keyValue : keyValues) { final Object mdcValue = MDC.get(keyValue); keyTypes.add((Class<String>) keyValue.getClass()); mdcValues.add(mdcValue); } } ret = evaluate(getExpressionEvaluator(keyTypes, keyValues), mdcValues); } return ret; }
private String getLoggingMesage( LoggingEvent event ) { Throwable throwable = null; ThrowableInformation throwableInfo = event.getThrowableInformation(); if (throwableInfo != null && throwableInfo.getThrowable() != null) { // logging through methods like error(new Exception); throwable = throwableInfo.getThrowable(); } else if (event.getMessage() instanceof Throwable) { // logging through methods like error("some message", new Exception); throwable = (Throwable) event.getMessage(); } // first format the message using the layout String message = layout.format(event); // then append the exception stack trace if (throwable != null) { message = getExceptionMsg(throwable, message); } return message; }
@Override protected void append(LoggingEvent event) { if (closed) { throw new IllegalStateException("appender is closed"); } if (! ready) { initialize(); } try { internalAppend(new LogMessage(event, getLayout())); } catch (Exception ex) { LogLog.warn("unable to append event", ex); } }
@Test public void testAsciiMessageFromEventDefaultLayout() throws Exception { final long timestamp = System.currentTimeMillis(); final String text = "test"; LoggingEvent event = createLoggingEvent(timestamp, text, null); LogMessage message = new LogMessage(event, new PatternLayout()); // the default pattern appends a newline String expectedText = text + "\n"; assertEquals("timestmap", timestamp, message.getTimestamp()); assertEquals("message", expectedText, message.getMessage()); assertArrayEquals("message as bytes", expectedText.getBytes("UTF-8"), message.getBytes()); assertEquals("size", 5, message.size()); }
@Test public void testUnicodeMessageFromEventDefaultLayout() throws Exception { final long timestamp = System.currentTimeMillis(); final String text = "\u0024\u00a2\u20ac"; LoggingEvent event = createLoggingEvent(timestamp, text, null); LogMessage message = new LogMessage(event, new PatternLayout()); // the default pattern appends a newline String expectedText = text + "\n"; assertEquals("timestmap", timestamp, message.getTimestamp()); assertEquals("message", expectedText, message.getMessage()); assertArrayEquals("message as bytes", expectedText.getBytes("UTF-8"), message.getBytes()); assertEquals("size", 7, message.size()); }
@Test // at this point we'll assume that UTF-8 conversion works as expected public void testAsciiMessageFromEventDefaultLayoutWithException() throws Exception { final long timestamp = System.currentTimeMillis(); final String text = "test"; final Exception ex = new Exception(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(text); ex.printStackTrace(pw); pw.close(); String expectedText = sw.toString(); LoggingEvent event = createLoggingEvent(timestamp, text, ex); LogMessage message = new LogMessage(event, new PatternLayout()); assertEquals("explicit timestamp", timestamp, message.getTimestamp()); assertEquals("message as string", expectedText, message.getMessage()); }
/** * Extracts Stack trace of Throwable contained in LogginEvent, if there is * any * * @param aLoggingEvent * logging event * @return stack trace of throwable */ public String getThrowableRepresentationFromLoggingEvent(LoggingEvent aLoggingEvent) { // extract throwable information from loggingEvent if available ThrowableInformation throwableinfo = aLoggingEvent.getThrowableInformation(); StringBuffer throwableStringBuffer = new StringBuffer(); if (throwableinfo != null) { String[] lines = throwableinfo.getThrowableStrRep(); for (int index = 0; index < lines.length; index++) { throwableStringBuffer = (StringBuffer) throwableStringBuffer.append(lines[index] + "\r\n"); } } String result = quotedString(throwableStringBuffer.toString()); if (this.getThrowableMaxChars() != -1 && result.length() > this.getThrowableMaxChars()) { result = result.substring(0, this.getThrowableMaxChars() - 1); } return result; }
@Override protected void append(LoggingEvent event) { try { Connection connection = dataSource.getConnection(); try { PreparedStatement stmt = connection.prepareStatement(sql); try { eventAdapter.eventToStatement(getName(), event, userInfoProvider.getUserInfo(), stmt); stmt.executeUpdate(); } finally { stmt.close(); } } finally { connection.close(); } } catch (SQLException e) { exceptionHandler.handleException(e); } }
@Override protected void append(LoggingEvent event) { if (this.useFastLocation) { if (this.stackOffset < 0) this.stackOffset = FastLoggingEvent.getStackOffset(event); event = new FastLoggingEvent(event, this.stackOffset); } if (this.storeLocation) event.getLocationInformation(); if (this.storeThreadName) event.getThreadName(); int position = -1; synchronized (this) { this.currentPosition = position = ++this.currentPosition % this.eventRing.length; this.counter++; } // SYNCH this.eventRing[position] = event; // assert(event.getLoggerName().contains("Handler") == false) : event; }
public static Collection<String> getLoggingMessages(RingBufferAppender...appenders) { List<LoggingEvent> events = new ArrayList<LoggingEvent>(); Layout layout = null; for (RingBufferAppender rba : appenders) { LoggingEvent e[] = rba.getLogEvents(); if (LOG.isDebugEnabled()) LOG.debug("Got " + e.length + " LoggingEvents for " + rba); CollectionUtil.addAll(events, e); if (layout == null) layout = rba.getLayout(); } // FOR if (events.isEmpty() == false) assert(layout != null); Collections.sort(events, new Comparator<LoggingEvent>() { @Override public int compare(LoggingEvent o1, LoggingEvent o2) { return (int)(o1.timeStamp - o2.timeStamp); } }); List<String> messages = new ArrayList<String>(); for (LoggingEvent event : events) { messages.add(layout.format(event)); } // FOR return (messages); }
protected void appendLevelText(LoggingEvent event, StringBuilder sbuf) { if( event.getLevel().equals(Level.DEBUG) ) { sbuf.append("<font color=\"#339933\">"); sbuf.append(event.getLevel()); sbuf.append("</font>"); } else if( event.getLevel().isGreaterOrEqual(Level.WARN) ) { sbuf.append("<font color=\"#993300\"><strong>"); sbuf.append(event.getLevel()); sbuf.append("</strong></font>"); } else { sbuf.append(event.getLevel()); } }
@Override protected void subAppend(LoggingEvent event) { LogLog.debug("subAppend"); long now = System.currentTimeMillis(); if( now >= nextRollTime ) { LogLog.debug("Have to roll directory"); calculateRollOverTime(); rollDirectory(); } else if( getFile() != null && ((CountingQuietWriter) qw).getCount() >= maxFileSize ) { LogLog.debug("Have to roll file"); rollFile(); } LogLog.debug("Calling Super Sub Append"); super.subAppend(event); }
public void append(LoggingEvent event) { super.append(event); if (available == true) { Log temp = parseLog(event); logList.add(temp); } }
private Log parseLog(LoggingEvent event) { Log log = new Log(); log.setLogName(event.getLogger().getName()); log.setLogLevel(event.getLevel()); log.setLogThread(event.getThreadName()); log.setLogMessage(event.getMessage().toString()); return log; }
/** * 获得message * @param event * @return */ private String getMessage(LoggingEvent event) { if (this.layout == null) { return event.getRenderedMessage(); } else { // 获取host和app String msg = System.nanoTime() + Constants.SEMICOLON + this.layout.format(event); return msg.replaceFirst(Constants.APP_NAME, this.app).replaceFirst(Constants.HOSTNAME, this.host); } }
public boolean addEvent(LoggingEvent event) { synchronized (list) { list.add(event); if (list.size() >= size) { return true; } return false; } }
private List<LoggingEvent> infoEvents() { List<LoggingEvent> info = new ArrayList<LoggingEvent>(); List<LoggingEvent> loggingEvents = logCaptor.loggedEvents(); for (LoggingEvent le : loggingEvents) { if (le.getLevel().equals(Level.INFO)) { info.add(le); } } return info; }
@Override protected void append(LoggingEvent event) { String message = subAppend(event); LogLog.debug("[" + new Date(event.getTimeStamp()) + "]" + message); Future<RecordMetadata> response = producer.send( new ProducerRecord<byte[], byte[]>(topic, message.getBytes(StandardCharsets.UTF_8))); if (syncSend) { try { response.get(); } catch (InterruptedException | ExecutionException ex) { throw new RuntimeException(ex); } } }
@Test public void testRollingFileAppenderExt(@Injectable LoggingEvent event, @Injectable Layout layout) throws Exception { new Expectations() { { layout.format(event); result = "test"; } }; File cur = new File(System.getProperty("user.dir")); File temp = new File(cur, "temptestfile.log"); if (temp.exists()) { temp.delete(); } RollingFileAppenderExt ext = new RollingFileAppenderExt(); ext.setLayout(layout); ext.setLogPermission("rw-------"); ext.setFile(temp.getAbsolutePath()); ext.setFile(temp.getAbsolutePath(), false, false, 300000); Assert.assertEquals(ext.getLogPermission(), "rw-------"); Assert.assertTrue(temp.exists()); temp.delete(); ext.subAppend(event); Assert.assertTrue(temp.exists()); ext.close(); temp.delete(); Assert.assertFalse(temp.exists()); }
@Test public void testRegisterSchemaNoResponse() { new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.registerSchema("msid", "schemaId", "content"); Assert.assertEquals("Register schema msid/schemaId failed.", events.get(0).getMessage()); } }.run(); }
@Test public void testRegisterSchemaErrorResponse() { new MockUp<ServiceRegistryClientImpl>() { @Mock Handler<RestResponse> syncHandlerEx(CountDownLatch countDownLatch, Holder<ResponseWrapper> holder) { return restResponse -> { HttpClientResponse response = Mockito.mock(HttpClientResponse.class); Mockito.when(response.statusCode()).thenReturn(400); Mockito.when(response.statusMessage()).thenReturn("client error"); Buffer bodyBuffer = Buffer.buffer(); bodyBuffer.appendString("too big"); ResponseWrapper responseWrapper = new ResponseWrapper(); responseWrapper.response = response; responseWrapper.bodyBuffer = bodyBuffer; holder.value = responseWrapper; }; } }; new MockUp<RestUtils>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { responseHandler.handle(null); } }; new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.registerSchema("msid", "schemaId", "content"); Assert.assertEquals( "Register schema msid/schemaId failed, statusCode: 400, statusMessage: client error, description: too big.", events.get(0).getMessage()); } }.run(); }
@Test public void testRegisterSchemaSuccess() { new MockUp<ServiceRegistryClientImpl>() { @Mock Handler<RestResponse> syncHandlerEx(CountDownLatch countDownLatch, Holder<ResponseWrapper> holder) { return restResponse -> { HttpClientResponse response = Mockito.mock(HttpClientResponse.class); Mockito.when(response.statusCode()).thenReturn(200); ResponseWrapper responseWrapper = new ResponseWrapper(); responseWrapper.response = response; holder.value = responseWrapper; }; } }; new MockUp<RestUtils>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { responseHandler.handle(null); } }; new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.registerSchema("msid", "schemaId", "content"); Assert.assertEquals( "register schema msid/schemaId success.", events.get(0).getMessage()); } }.run(); }
@Override public void write(String loggerName, String filePrefix, String content) { RollingFileAppender logger = fileAppenders.computeIfAbsent(loggerName, f -> initLogger(loggerName, filePrefix)); LoggingEvent event = new LoggingEvent(loggerName, Logger.getLogger(loggerName), Level.ALL, content, null); logger.append(event); }
@Override protected void append(LoggingEvent event) { if (super.getProducer() == null) { activateOptions(); } super.append(event); }
public FastLoggingEvent(LoggingEvent event, int stackOffset) { super(event.getFQNOfLoggerClass(), event.getLogger(), event.getLevel(), event.getMessage(), (event.getThrowableInformation() != null ? event.getThrowableInformation().getThrowable() : null)); this.event = event; this.stackOffset = stackOffset; }
public static int getStackOffset(LoggingEvent event) { Throwable t = new Throwable(); String fqnOfCallingClass = event.getFQNOfLoggerClass(); if (fqnOfCallingClass == null) return 0; // HACK StackTraceElement stack[] = t.getStackTrace(); int offset = stack.length - 1; for (; offset >= 0; offset--) { if (stack[offset].getClassName().equals(fqnOfCallingClass)) break; } // FOR return (offset + 2); }
private void init(int size) { this.eventRing = new LoggingEvent[size]; this.currentPosition = -1; this.counter = 0; if (LOG.isDebugEnabled()) LOG.debug(String.format("Initialized appender with new buffer [size=%d, useFastLocation=%s, storeLocation=%s, storeThreadName=%s, layout=%s]", size, this.useFastLocation, this.storeLocation, this.storeThreadName, (this.getLayout() != null ? this.getLayout().getClass().getSimpleName() : null))); }
/** * test TaskLogAppender */ @SuppressWarnings("deprecation") @Test (timeout=5000) public void testTaskLogAppender(){ TaskLogAppender appender= new TaskLogAppender(); System.setProperty(TaskLogAppender.TASKID_PROPERTY,"attempt_01_02_m03_04_001"); System.setProperty(TaskLogAppender.LOGSIZE_PROPERTY, "1003"); appender.activateOptions(); assertEquals(appender.getTaskId(), "attempt_01_02_m03_04_001"); assertEquals(appender.getTotalLogFileSize(),1000); assertEquals(appender.getIsCleanup(),false); // test writer Writer writer= new StringWriter(); appender.setWriter(writer); Layout layout = new PatternLayout("%-5p [%t]: %m%n"); appender.setLayout(layout); Category logger= Logger.getLogger(getClass().getName()); LoggingEvent event = new LoggingEvent("fqnOfCategoryClass", logger, Priority.INFO, "message", new Throwable()); appender.append(event); appender.flush() ; appender.close(); assertTrue(writer.toString().length()>0); // test cleanup should not changed appender= new TaskLogAppender(); appender.setIsCleanup(true); appender.activateOptions(); assertEquals(appender.getIsCleanup(),true); }
public static Collection<LoggingEvent> getLoggingEvents(Logger...loggers) { SortedSet<LoggingEvent> events = new TreeSet<LoggingEvent>(new Comparator<LoggingEvent>() { @Override public int compare(LoggingEvent o1, LoggingEvent o2) { return (int)(o1.timeStamp - o2.timeStamp); } }); for (Logger log : loggers) { RingBufferAppender rba = getRingBufferAppender(log); if (rba != null) { CollectionUtil.addAll(events, rba.getLogEvents()); } } // FOR return (events); }
@Override protected void append(LoggingEvent event) { // System.err.println("Got event: " + event); TestFastLoggingEvent.this.offset = FastLoggingEvent.getStackOffset(event); TestFastLoggingEvent.this.origEvent = event; TestFastLoggingEvent.this.origEvent.getLocationInformation(); TestFastLoggingEvent.this.fastEvent = new FastLoggingEvent(event, TestFastLoggingEvent.this.offset); TestFastLoggingEvent.this.fastEvent.getLocationInformation(); }
@Override public String format(LoggingEvent event) { try { return toJson(event); } catch (IOException e) { //this really should not happen, and rather than throw an exception //which may hide the real problem, the log class is printed //in JSON format. The classname is used to ensure valid JSON is //returned without playing escaping games return "{ \"logfailure\":\"" + e.getClass().toString() + "\"}"; } }