/** * Tests LoggingEvent.getLocationInfo() when no FQCN is specified. * See bug 41186. */ public void testLocationInfoNoFQCN() { Category root = Logger.getRootLogger(); Priority level = Level.INFO; LoggingEvent event = new LoggingEvent( null, root, 0L, level, "Hello, world.", null); LocationInfo info = event.getLocationInformation(); // // log4j 1.2 returns an object, its layout doesn't check for nulls. // log4j 1.3 returns a null. // assertNotNull(info); if (info != null) { assertEquals("?", info.getLineNumber()); assertEquals("?", info.getClassName()); assertEquals("?", info.getFileName()); assertEquals("?", info.getMethodName()); } }
public void testEventLogger() { EventData data[] = new EventData[2]; data[0] = new EventData(); data[0].setEventType("Login"); data[0].setEventId("1"); data[0].setEventDateTime(new Date()); data[0].put("Userid", "TestUser"); EventLogger.logEvent(data[0]); data[1] = new EventData(); data[1].setEventType("Update"); data[1].setEventId("2"); data[1].setEventDateTime(new Date()); data[1].put("FileName", "/etc/hosts"); EventLogger.logEvent(data[1]); assertEquals(2, listAppender.list.size()); for (int i = 0; i < 2; ++i) { LoggingEvent event = listAppender.list.get(i); verify(event, data[i].toXML()); LocationInfo li = event.getLocationInformation(); assertEquals(this.getClass().getName(), li.getClassName()); assertEquals(event.getMDC("hostname"), "localhost"); } }
public void testSmoke() { SLF4JBridgeHandler.install(); String msg = "msg"; julLogger.info(msg); assertEquals(1, listAppender.list.size()); LoggingEvent le = (LoggingEvent) listAppender.list.get(0); assertEquals(LOGGER_NAME, le.getLoggerName()); assertEquals(msg, le.getMessage()); // get the location info in the event. // Note that this must have been computed previously // within an appender for the following assertion to // work properly LocationInfo li = le.getLocationInformation(); System.out.println(li.fullInfo); assertEquals("SLF4JBridgeHandlerTest.java", li.getFileName()); assertEquals("testSmoke", li.getMethodName()); }
private JSONObject createLogSourceEvent(LoggingEvent loggingEvent, HostData host) { JSONObject logSourceEvent = new JSONObject(); if (locationInfo) { LocationInfo info = loggingEvent.getLocationInformation(); logSourceEvent.put(LayoutFields.FILE_NAME, info.getFileName()); logSourceEvent.put(LayoutFields.LINE_NUMBER, info.getLineNumber()); logSourceEvent.put(LayoutFields.CLASS_NAME, info.getClassName()); logSourceEvent.put(LayoutFields.METHOD_NAME, info.getMethodName()); RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); String jvmName = runtimeBean.getName(); logSourceEvent.put(LayoutFields.PROCESS_ID, Long.valueOf(jvmName.split("@")[0])); } logSourceEvent.put(LayoutFields.LOGGER_NAME, loggingEvent.getLoggerName()); logSourceEvent.put(LayoutFields.HOST_NAME, host.getHostName()); logSourceEvent.put(LayoutFields.HOST_IP, host.getHostAddress()); return logSourceEvent; }
/** * testGetStackifyErrorWithoutException */ @Test public void testGetStackifyErrorWithoutException() { LocationInfo locInfo = Mockito.mock(LocationInfo.class); Mockito.when(locInfo.getClassName()).thenReturn("class"); Mockito.when(locInfo.getMethodName()).thenReturn("method"); Mockito.when(locInfo.getLineNumber()).thenReturn("123"); LoggingEvent event = Mockito.mock(LoggingEvent.class); Mockito.when(event.getMessage()).thenReturn("Exception message"); Mockito.when(event.getLocationInformation()).thenReturn(locInfo); LoggingEventAdapter adapter = new LoggingEventAdapter(Mockito.mock(EnvironmentDetail.class)); StackifyError error = adapter.getStackifyError(event, null); Assert.assertNotNull(error); Assert.assertEquals("StringException", error.getError().getErrorType()); }
/** * testGetClassName */ @Test public void testGetClassName() { LocationInfo locInfo = Mockito.mock(LocationInfo.class); Mockito.when(locInfo.getClassName()).thenReturn("class"); LoggingEvent event = Mockito.mock(LoggingEvent.class); Mockito.when(event.getLocationInformation()).thenReturn(locInfo); LoggingEventAdapter adapter = new LoggingEventAdapter(Mockito.mock(EnvironmentDetail.class)); String className = adapter.getClassName(event); Assert.assertNotNull(className); Assert.assertEquals("class", className); }
@Override public LocationInfo getLocationInformation() { if (this.locationInfo == null) { // HACK: Use preprocessor information String msg = this.event.getMessage().toString(); Matcher m = PREPROCESSOR_PATTERN.matcher(msg); if (LOG.isDebugEnabled()) LOG.debug("Checking whether we can use PREPROCESSOR info for location: " + msg); if (m.find()) { if (LOG.isDebugEnabled()) LOG.debug("Using preprocessor information get source location [" + m + "]"); String fileName = m.group(1); int lineNumber = Integer.parseInt(m.group(2)); this.locationInfo = new FastLocationInfo(lineNumber, fileName, "", ""); this.cleanMessage = m.replaceFirst(""); } else { if (LOG.isDebugEnabled()) LOG.debug("Using stack offset lookup to get source location"); StackTraceElement stack[] = Thread.currentThread().getStackTrace(); // System.err.println(String.format("Stack=%d / Offset=%d", stack.length, this.stackOffset)); if (this.stackOffset < stack.length) { // for (int i = 0; i < stack.length; i++) { // System.err.printf("[%02d] %s\n", i, stack[i]); // } this.locationInfo = new FastLocationInfo(stack[this.stackOffset].getLineNumber(), stack[this.stackOffset].getFileName(), stack[this.stackOffset].getClassName(), stack[this.stackOffset].getMethodName()); } } } return (this.locationInfo); }
/** * testLocationInfo */ public void testLocationInfo() throws Exception { LocationInfo expected = this.origEvent.getLocationInformation(); assertNotNull(expected); LocationInfo actual = this.fastEvent.getLocationInformation(); assertNotNull(actual); System.err.println(this.fastEvent.getLocationInformation()); assertEquals(expected.getLineNumber(), actual.getLineNumber()); assertEquals(expected.getFileName(), actual.getFileName()); assertEquals(expected.getClassName(), actual.getClassName()); assertEquals(expected.getMethodName(), actual.getMethodName()); }
/** * testPreProcessorLocationInfo */ public void testPreProcessorLocationInfo() { String fileName = "ExecutionSite.java"; String lineNum = "1958"; String msg = "Dispatching 1 messages and waiting for the results for InsertCallForwarding #1024611756678316032/0"; logger.info(String.format("%s:%s %s", fileName, lineNum, msg)); assertNotNull(fastEvent); LocationInfo actual = this.fastEvent.getLocationInformation(); assertNotNull(actual); assertEquals(fileName, actual.getFileName()); assertEquals(lineNum, actual.getLineNumber()); assertEquals(msg, fastEvent.getMessage()); }
@Override public String format(LoggingEvent event) { Map<String,Object> map = new TreeMap<String,Object>(); map.put("timestamp", new Date(event.getTimeStamp())); map.put("thread", event.getThreadName()); map.put("logger", event.getLogger().getName()); map.put("level", event.getLevel().toString()); map.put("message", event.getRenderedMessage()); if (event.getThrowableStrRep() != null) map.put("exception", event.getThrowableStrRep()); if (event.getNDC() != null) map.put("ndc", event.getNDC()); if (tags != null) map.put("tags", tags); if ((event.getProperties() != null) && ! event.getProperties().isEmpty()) { map.put("mdc", event.getProperties()); } if (processId != null) map.put("processId", processId); if (hostname != null) map.put("hostname", hostname); if (instanceId != null) map.put("instanceId", instanceId); if (enableLocation) { LocationInfo info = event.getLocationInformation(); Map<String,Object> location = new TreeMap<String,Object>(); location.put("className", info.getClassName()); location.put("methodName", info.getMethodName()); location.put("fileName", info.getFileName()); location.put("lineNumber", info.getLineNumber()); map.put("locationInfo", location); } return converterTL.get().convert(map); }
public LocationInfo getLocationInformation() { if (location == null) { Throwable t = new Throwable(); // t.printStackTrace(); location = new LambdaLocation(t); } return location; }
@Override public String format(LoggingEvent event) { BenderLogEntry entry = new BenderLogEntry(); entry.threadName = event.getThreadName(); entry.posixTimestamp = event.getTimeStamp(); entry.timestamp = FORMATTER.print(entry.posixTimestamp); entry.message = event.getRenderedMessage(); entry.level = event.getLevel().toString(); entry.logger = event.getLogger().getName(); entry.alias = ALIAS; entry.version = VERSION; if (event.getThrowableInformation() != null) { final ThrowableInformation throwableInfo = event.getThrowableInformation(); ExceptionLog ex = new ExceptionLog(); if (throwableInfo.getThrowable().getClass().getCanonicalName() != null) { ex.clazz = throwableInfo.getThrowable().getClass().getCanonicalName(); } if (throwableInfo.getThrowable().getMessage() != null) { ex.message = throwableInfo.getThrowable().getMessage(); } if (throwableInfo.getThrowableStrRep() != null) { Arrays.asList(throwableInfo.getThrowableStrRep()).forEach(m -> { ex.stacktrace.add(m.replaceAll("\\t", " ")); }); } entry.exception = ex; } LocationInfo locinfo = event.getLocationInformation(); entry.file = locinfo.getFileName(); entry.lineNumber = Integer.parseInt(locinfo.getLineNumber()); entry.method = locinfo.getMethodName(); entry.clazz = locinfo.getClassName(); return GSON.toJson(entry) + "\n"; }
public String convert(LoggingEvent event) { LocationInfo locationInfo = event.getLocationInformation(); switch(type) { case FULL_LOCATION_CONVERTER: return locationInfo.fullInfo; case METHOD_LOCATION_CONVERTER: return locationInfo.getMethodName(); case LINE_LOCATION_CONVERTER: return locationInfo.getLineNumber(); case FILE_LOCATION_CONVERTER: return locationInfo.getFileName(); default: return null; } }
/** * Serialize a logging event with an exception and check it against * a witness. * @throws Exception if exception during test. * */ public void testSerializationWithLocation() throws Exception { Logger root = Logger.getRootLogger(); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", null); LocationInfo info = event.getLocationInformation(); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/location.bin", event, skip, 237); }
/** * Format a logging event. * @param event event to format. * @param toAppendTo string buffer to which class name will be appended. */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { final int initialLength = toAppendTo.length(); LocationInfo li = event.getLocationInformation(); if (li == null) { toAppendTo.append(LocationInfo.NA); } else { toAppendTo.append(li.getClassName()); } abbreviate(initialLength, toAppendTo); }
/** Create new instance. @since 1.2.15 @param fqnOfCategoryClass Fully qualified class name of Logger implementation. @param logger The logger generating this event. @param timeStamp the timestamp of this logging event @param level The level of this event. @param message The message of this event. @param threadName thread name @param throwable The throwable of this event. @param ndc Nested diagnostic context @param info Location info @param properties MDC properties */ public LogEvent(final String fqnOfCategoryClass, final Logger logger, final long timeStamp, final Level level, final Object message, final String threadName, final ThrowableInformation throwable, final String ndc, final LocationInfo info, final java.util.Map properties) { super(); this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; if (logger != null) { categoryName = logger.getName(); } else { categoryName = null; } this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = throwable; } this.timeStamp = timeStamp; this.threadName = threadName; ndcLookupRequired = false; this.ndc = ndc; this.locationInfo = info; mdcCopyLookupRequired = false; if (properties != null) { mdcCopy = new java.util.Hashtable(properties); } }
/** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { output.append(locationInfo.fullInfo); } }
/** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { output.append(locationInfo.getFileName()); } }
/** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer output) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { output.append(locationInfo.getLineNumber()); } }
/** * {@inheritDoc} */ public void format(final LoggingEvent event, final StringBuffer toAppendTo) { LocationInfo locationInfo = event.getLocationInformation(); if (locationInfo != null) { toAppendTo.append(locationInfo.getMethodName()); } }
/** * Adds the LocationInfo object to an existing BSON object. * * @param bson * The BSON object to add the location info to <i>(must not be null)</i>. * @param locationInfo * The LocationInfo object to add to the BSON object <i>(may be null)</i>. */ protected void addLocationInformation(Document bson, final LocationInfo locationInfo) { if (locationInfo != null) { nullSafePut(bson, KEY_FILE_NAME, locationInfo.getFileName()); nullSafePut(bson, KEY_METHOD, locationInfo.getMethodName()); nullSafePut(bson, KEY_LINE_NUMBER, locationInfo.getLineNumber()); nullSafePut(bson, KEY_CLASS_NAME, bsonifyClassName(locationInfo.getClassName())); nullSafePut(bson, KEY_CLASS, locationInfo.getClassName()); } }
private LoggingEvent parseMatcher(String event, Matcher m, String messageAdd, List<String> causes) throws ParseException{ LoggingEvent e = null; String thread = m.group(2); SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss,SSS"); sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT+3")); long timestamp = sdf.parse(m.group(3)).getTime(); String loggerFqn = m.group(5); Category cat = new EventCategory(loggerFqn); String level = m.group(4); Level prio = null; messageAdd = messageAdd + validateCauses(causes); switch(level){ case "FATAL": prio = Level.FATAL; break; case "ERROR":prio = Level.ERROR; break; case "WARN":prio = Level.WARN; break; case "INFO":prio = Level.INFO; break; case "DEBUG":prio = Level.DEBUG; break; case "TRACE":prio = Level.TRACE; break; } String message = m.group(6)+messageAdd; e = new LoggingEvent(loggerFqn, cat, timestamp, prio, message, thread, new ThrowableInformation(causes.toArray(new String[causes.size()])), (String)null, (LocationInfo)null, null); events++; System.out.println("Parsed "+events+" event(s). Last event on "+m.group(3)); return e; }
@Override protected LoggingEvent newEvent(LogDetails logDetails) { LocationInfo locationInfo = new LocationInfo(logDetails.getFileName(), logDetails.getClassName(), logDetails.getMethodName(), String.valueOf(logDetails.getLineNumber())); Logger logger = Logger.getLogger(logDetails.getClassName()); ThrowableInformation throwableInformation = logDetails.getException() != null ? new ThrowableInformation(logDetails.getException()) : null; Properties mdc = new Properties(); logDetails.getMdc().entrySet().stream().forEach(it -> mdc.put(it.getKey(), it.getValue())); LoggingEvent event = new LoggingEvent(logDetails.getClassName(), logger, logDetails.getTimeMillis(), Level.toLevel(logDetails.getSeverity()), logDetails.getLogMessage(), logDetails.getThreadName(), throwableInformation, null, locationInfo, mdc); return event; }
public void doAppend(LoggingEvent event) { Throwable ex = null; ThrowableInformation ti = event.getThrowableInformation(); if (ti != null) { ex = ti.getThrowable(); } LocationInfo li = event.getLocationInformation(); this.listener.afterLog(String.valueOf(event.getMessage()), ex, String.valueOf(event.getLevel()), event.getThreadName(), li.getClassName(), li.getMethodName(), li.getFileName(), li.getLineNumber()); }
@Override public String getClassName(LoggingEvent record) { LocationInfo locationInformation = record.getLocationInformation(); return (locationInformation != null) ? locationInformation.getClassName() : null; }
@Override public String getMethodName(LoggingEvent record) { LocationInfo locationInformation = record.getLocationInformation(); return (locationInformation != null) ? record.getLocationInformation().getMethodName() : null; }
@Override protected void append(LoggingEvent event) { final LevelTag level = LevelTag.get(event.getLevel()); registry.counter(numMessages[level.ordinal()]).increment(); ThrowableInformation info = event.getThrowableInformation(); if (info != null) { LocationInfo loc = event.getLocationInformation(); final String file = (loc == null) ? "unknown" : loc.getFileName(); Id stackTraceId = numStackTraces[level.ordinal()] .withTag("exception", info.getThrowable().getClass().getSimpleName()) .withTag("file", file); registry.counter(stackTraceId).increment(); } }
/** * @see com.stackify.api.common.log.EventAdapter#getClassName(java.lang.Object) */ @Override public String getClassName(final LoggingEvent event) { LocationInfo locInfo = event.getLocationInformation(); if (locInfo != null) { return locInfo.getClassName(); } return null; }
/** * testGetLogMsg */ @Test public void testGetLogMsg() { String msg = "msg"; StackifyError ex = Mockito.mock(StackifyError.class); String th = "th"; String level = "debug"; String srcClass = "srcClass"; String srcMethod = "srcMethod"; Integer srcLine = Integer.valueOf(14); Map<String, String> properties = new HashMap<String, String>(); properties.put("key", "value"); LocationInfo locInfo = Mockito.mock(LocationInfo.class); Mockito.when(locInfo.getClassName()).thenReturn(srcClass); Mockito.when(locInfo.getMethodName()).thenReturn(srcMethod); Mockito.when(locInfo.getLineNumber()).thenReturn(srcLine.toString()); LoggingEvent event = Mockito.mock(LoggingEvent.class); Mockito.when(event.getMessage()).thenReturn(msg); Mockito.when(event.getThreadName()).thenReturn(th); Mockito.when(event.getLevel()).thenReturn(Level.DEBUG); Mockito.when(event.getLocationInformation()).thenReturn(locInfo); Mockito.when(event.getProperties()).thenReturn(properties); LoggingEventAdapter adapter = new LoggingEventAdapter(Mockito.mock(EnvironmentDetail.class)); LogMsg logMsg = adapter.getLogMsg(event, ex); Assert.assertNotNull(logMsg); Assert.assertEquals(msg, logMsg.getMsg()); Assert.assertEquals("{\"key\":\"value\"}", logMsg.getData()); Assert.assertEquals(ex, logMsg.getEx()); Assert.assertEquals(th, logMsg.getTh()); Assert.assertEquals(level, logMsg.getLevel()); Assert.assertEquals(srcClass + "." + srcMethod, logMsg.getSrcMethod()); Assert.assertEquals(srcLine, logMsg.getSrcLine()); Assert.assertEquals(srcLine, logMsg.getSrcLine()); }
private String getSourceMethodName() { String methodName = loggingEvent.getLocationInformation().getMethodName(); if(LocationInfo.NA.equals(methodName)){ return null; } return methodName; }
private String getSourceLineNumber() { String lineNumber = loggingEvent.getLocationInformation().getLineNumber(); if(LocationInfo.NA.equals(lineNumber)){ return null; } return lineNumber; }
private String getSourceClassName() { String className = loggingEvent.getLocationInformation().getClassName(); if(LocationInfo.NA.equals(className)){ return null; } return className; }
/** * JDBCAppender 에서 로그 기록 시 해당 로깅 이벤트를 buffer에 추가하는 부분으로 여기서는 * log4j-1.3alpha-8 의 DB Appender 에서 기본 제공되는 logging_event 테이블에 대한 * 칼럼들(sequence_number, timestamp, rendered_message, logger_name, * level_string, thread_name, reference_flag) 과 locationInfo 설정에 따른 추가 * 정보(caller_filename, caller_class, caller_method, caller_line)를 MDC 를 이용해 * 설정하였다. * * @param event * - JDBCAppender 형식으로 기록하는 현재 LoggingEvent */ @Override public void append(LoggingEvent event) { MDC.put("sequence_number", event.getSequenceNumber()); MDC.put("timestamp", event.getTimeStamp()); MDC.put("rendered_message", event.getRenderedMessage()); MDC.put("logger_name", event.getLoggerName()); MDC.put("level_string", event.getLevel().toString()); String ndc = event.getNDC(); if (ndc != null) { MDC.put("ndc", ndc); } MDC.put("thread_name", event.getThreadName()); MDC.put("reference_flag", DBHelper.computeReferenceMask(event)); LocationInfo li; if (event.locationInformationExists() || locationInfo) { li = event.getLocationInformation(); } else { li = LocationInfo.NA_LOCATION_INFO; } MDC.put("caller_filename", li.getFileName()); MDC.put("caller_class", li.getClassName()); MDC.put("caller_method", li.getMethodName()); MDC.put("caller_line", li.getLineNumber()); // TODO Auto-generated method stub super.append(event); }
/** * Send one logging event to Cassandra. We just bind the new values into the preprocessed query * built by setupStatement */ private void createAndExecuteQuery(LoggingEvent event) { BoundStatement bound = new BoundStatement(statement); // A primary key combination of timestamp/hostname/threadname should be unique as long as the thread names // are set, but would not be backwards compatible. Do we care? bound.setUUID(0, UUID.randomUUID()); bound.setString(1, appName); bound.setString(2, ip); bound.setString(3, hostname); bound.setString(4, event.getLoggerName()); bound.setString(5, event.getLevel().toString()); LocationInfo locInfo = event.getLocationInformation(); if (locInfo != null) { bound.setString(6, locInfo.getClassName()); bound.setString(7, locInfo.getFileName()); bound.setString(8, locInfo.getLineNumber()); bound.setString(9, locInfo.getMethodName()); } bound.setString(10, event.getRenderedMessage()); bound.setString(11, event.getNDC()); bound.setLong(12, new Long(LoggingEvent.getStartTime())); bound.setString(13, event.getThreadName()); String[] throwableStrs = event.getThrowableStrRep(); bound.setString(14, throwableStrs == null ? null : Joiner.on(", ").join(throwableStrs)); bound.setLong(15, new Long(event.getTimeStamp())); session.execute(bound); }