public String fullDump(ILoggingEvent evt) { try { IThrowableProxy proxy = evt.getThrowableProxy(); if(proxy == null) return null; StringBuilder builder = new StringBuilder(); for (StackTraceElementProxy step : proxy .getStackTraceElementProxyArray()) { String string = step.toString(); builder.append(CoreConstants.TAB).append(string); ThrowableProxyUtil.subjoinPackagingData(builder, step); builder.append(CoreConstants.LINE_SEPARATOR); } return builder.toString(); } catch(Exception e) { addError("exception trying to log exception", e); return "exception parsing exception"; } }
private void appendStackTrace(StringBuilder log, ThrowableProxy proxy) { if (proxy != null) { Stream<StackTraceElementProxy> trace = Arrays.stream(proxy.getStackTraceElementProxyArray()); trace.forEach(step -> { String string = step.toString(); log.append(CoreConstants.TAB).append(string); ThrowableProxyUtil.subjoinPackagingData(log, step); log.append(CoreConstants.LINE_SEPARATOR); }); trace.close(); } }
private void loopCauses(StringBuilder log, ThrowableProxy parentProxy, int depth) { ThrowableProxy cause = (ThrowableProxy) parentProxy.getCause(); if (cause != null) { log.append(String.format( "Caused by: %s: %s", cause.getThrowable().getClass().getCanonicalName(), cause.getThrowable().getMessage() )); log.append(CoreConstants.LINE_SEPARATOR); } appendStackTrace(log, cause); if (cause != null && depth < STACKTRACE_DEPTH) { loopCauses(log, cause, depth + 1); } }
void render(StringBuilder sbuf, IThrowableProxy tp) { printFirstLine(sbuf, tp); int commonFrames = tp.getCommonFrames(); StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); for (int i = 0; i < stepArray.length - commonFrames; i++) { StackTraceElementProxy step = stepArray[i]; sbuf.append(TRACE_PREFIX); sbuf.append(Transform.escapeTags(step.toString())); sbuf.append(CoreConstants.LINE_SEPARATOR); } if (commonFrames > 0) { sbuf.append(TRACE_PREFIX); sbuf.append("\t... ").append(commonFrames).append(" common frames omitted").append(CoreConstants.LINE_SEPARATOR); } }
@Test public void log() throws Exception { Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); LoggerContext context = logger.getLoggerContext(); context.reset(); Map<String, String> ruleRegistry = (Map) context.getObject(CoreConstants.PATTERN_RULE_REGISTRY); if (ruleRegistry == null) { ruleRegistry = new HashMap<String, String>(); context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, ruleRegistry); } ruleRegistry.put("ex1L", OnelineThrowableProxyConverter.class.getCanonicalName()); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); encoder.setPattern("%d{yyyy/MM/dd HH:mm:ss:SSS}\\t%-5level\\t%msg\\t%ex1L"); encoder.start(); ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>(); appender.setContext(context); appender.setEncoder(encoder); appender.start(); logger.addAppender(appender); logger.error("error", new RuntimeException("foo")); }
@Test public void log() throws Exception { Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); LoggerContext context = logger.getLoggerContext(); context.reset(); Map<String, String> ruleRegistry = (Map) context.getObject(CoreConstants.PATTERN_RULE_REGISTRY); if (ruleRegistry == null) { ruleRegistry = new HashMap<String, String>(); context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, ruleRegistry); } ruleRegistry.put("xEx1L", OnelineExtendedThrowableProxyConverter.class.getCanonicalName()); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); encoder.setPattern("%d{yyyy/MM/dd HH:mm:ss:SSS}\\t%-5level\\t%msg\\t%xEx1L"); encoder.start(); ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>(); appender.setContext(context); appender.setEncoder(encoder); appender.start(); logger.addAppender(appender); logger.error("error", new RuntimeException()); }
public void setMockServerAndConfigure(int expectedCount, String suffixPattern) throws InterruptedException { int port = RandomUtil.getRandomServerPort(); mockServer = new MockSyslogServer(expectedCount, port); mockServer.start(); // give MockSyslogServer head start Thread.sleep(100); sa.setSyslogHost("localhost"); sa.setFacility("MAIL"); sa.setPort(port); sa.setSuffixPattern(suffixPattern); sa.setStackTracePattern("[%thread] foo "+CoreConstants.TAB); sa.start(); assertTrue(sa.isStarted()); String loggerName = this.getClass().getName(); Logger logger = lc.getLogger(loggerName); logger.addAppender(sa); }
void subjoinThrowableProxy(StringBuilder buf, IThrowableProxy tp) { subjoinFirstLine(buf, tp); buf.append(CoreConstants.LINE_SEPARATOR); final StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); final int commonFrames = tp.getCommonFrames(); int maxIndex = stepArray.length; if (commonFrames > 0) { maxIndex -= commonFrames; } for (int i = 0; i < maxIndex; i++) { final String string = stepArray[i].toString(); buf.append(PREFIX); buf.append(string); extraData(buf, stepArray[i]); // allow other data to be added buf.append(CoreConstants.LINE_SEPARATOR); } if (commonFrames > 0) { buf.append("!... ").append(tp.getCommonFrames()).append( " common frames omitted").append(CoreConstants.LINE_SEPARATOR); } }
private void handleLiteralState(char c, List<Token> tokenList, StringBuffer buf) { switch (c) { case ESCAPE_CHAR: escape("%()", buf); break; case CoreConstants.PERCENT_CHAR: addValuedToken(Token.LITERAL, buf, tokenList); tokenList.add(Token.PERCENT_TOKEN); state = TokenizerState.FORMAT_MODIFIER_STATE; break; case CoreConstants.RIGHT_PARENTHESIS_CHAR: addValuedToken(Token.LITERAL, buf, tokenList); state = TokenizerState.RIGHT_PARENTHESIS_STATE; break; default: buf.append(c); } }
/** * Returns a map where the default converter map is merged with the map * contained in the context. */ public Map<String, String> getEffectiveConverterMap() { Map<String, String> effectiveMap = new HashMap<String, String>(); // add the least specific map fist Map<String, String> defaultMap = getDefaultConverterMap(); if (defaultMap != null) { effectiveMap.putAll(defaultMap); } // contextMap is more specific than the default map Context context = getContext(); if (context != null) { @SuppressWarnings("unchecked") Map<String, String> contextMap = (Map<String, String>) context .getObject(CoreConstants.PATTERN_RULE_REGISTRY); if (contextMap != null) { effectiveMap.putAll(contextMap); } } // set the most specific map last effectiveMap.putAll(instanceConverterMap); return effectiveMap; }
private void handleLiteralState(char c, List<Token> tokenList, StringBuilder stringBuilder) { if (c == CoreConstants.DOLLAR) { addLiteralToken(tokenList, stringBuilder); stringBuilder.setLength(0); state = TokenizerState.START_STATE; } else if (c == CoreConstants.COLON_CHAR) { addLiteralToken(tokenList, stringBuilder); stringBuilder.setLength(0); state = TokenizerState.DEFAULT_VAL_STATE; } else if (c == CoreConstants.CURLY_LEFT) { addLiteralToken(tokenList, stringBuilder); tokenList.add(Token.CURLY_LEFT_TOKEN); stringBuilder.setLength(0); } else if (c == CoreConstants.CURLY_RIGHT) { addLiteralToken(tokenList, stringBuilder); tokenList.add(Token.CURLY_RIGHT_TOKEN); stringBuilder.setLength(0); } else { stringBuilder.append(c); } }
public long periodsElapsed(long start, long end) { if (start > end) throw new IllegalArgumentException("Start cannot come before end"); long diff = end - start; switch (periodicityType) { case TOP_OF_MILLISECOND: return diff; case TOP_OF_SECOND: return diff / CoreConstants.MILLIS_IN_ONE_SECOND; case TOP_OF_MINUTE: return diff / CoreConstants.MILLIS_IN_ONE_MINUTE; case TOP_OF_HOUR: return (int) diff / CoreConstants.MILLIS_IN_ONE_HOUR; case TOP_OF_DAY: return diff / CoreConstants.MILLIS_IN_ONE_DAY; case TOP_OF_WEEK: return diff / CoreConstants.MILLIS_IN_ONE_WEEK; case TOP_OF_MONTH: return diffInMonths(start, end); default: throw new IllegalStateException("Unknown periodicity type."); } }
@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()); }
@Override public String convert(IAccessEvent ae) { StringBuilder buf = new StringBuilder(); buf.append(ae.getRequestURL()); buf.append(CoreConstants.LINE_SEPARATOR); Enumeration headerNames = ae.getRequestHeaderNames(); while(headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); buf.append(name); buf.append(": "); buf.append(ae.getRequestHeader(name)); buf.append(CoreConstants.LINE_SEPARATOR); } buf.append(CoreConstants.LINE_SEPARATOR); buf.append(ae.getRequestContent()); return buf.toString(); }
private static void appendThrowable(StringBuilder sb, Throwable t) { String[] stringRep = ThrowableToStringArray.convert(t); for (String s : stringRep) { if (s.startsWith(CoreConstants.CAUSED_BY)) { // nothing } else if (Character.isDigit(s.charAt(0))) { // if line resembles "48 common frames omitted" sb.append("\t... "); } else { // most of the time. just add a tab+"at" sb.append("\tat "); } sb.append(s).append(CoreConstants.LINE_SEPARATOR); } }
public static void buildStr(StringBuilder sb, String indentation, Status s) { String prefix; if (s.hasChildren()) { prefix = indentation + "+ "; } else { prefix = indentation + "|-"; } if (cachingDateFormat != null) { String dateStr = cachingDateFormat.format(s.getDate()); sb.append(dateStr).append(" "); } sb.append(prefix).append(s).append(CoreConstants.LINE_SEPARATOR); if (s.getThrowable() != null) { appendThrowable(sb, s.getThrowable()); } if (s.hasChildren()) { Iterator<Status> ite = s.iterator(); while (ite.hasNext()) { Status child = ite.next(); buildStr(sb, indentation + " ", child); } } }
public String doLayout(ILoggingEvent event) { StringBuilder sbuf = new StringBuilder(128); if (prefix != null) { sbuf.append(prefix + ": "); } sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime()); sbuf.append(" "); sbuf.append(event.getLevel()); if (printThreadName) { sbuf.append(" ["); sbuf.append(event.getThreadName()); sbuf.append("] "); } else { sbuf.append(" "); } sbuf.append(event.getLoggerName()); sbuf.append(" - "); sbuf.append(event.getFormattedMessage()); sbuf.append(CoreConstants.LINE_SEPARATOR); return sbuf.toString(); }
/** * Returns a map where the default converter map is merged with the map * contained in the context. */ public Map<String, String> getEffectiveConverterMap() { Map<String, String> effectiveMap = new HashMap<String, String>(); // add the least specific map fist Map<String, String> defaultMap = getDefaultConverterMap(); if (defaultMap != null) { effectiveMap.putAll(defaultMap); } // contextMap is more specific than the default map Context context = getContext(); if (context != null) { @SuppressWarnings("unchecked") Map<String, String> contextMap = (Map<String, String>) context .getObject(CoreConstants.PATTERN_RULE_REGISTRY); if (contextMap != null) { effectiveMap.putAll(contextMap); } } return effectiveMap; }
/** * Create a child of this logger by suffix, that is, the part of the name * extending this logger. For example, if this logger is named "x.y" and the * lastPart is "z", then the created child logger will be named "x.y.z". * * <p> * IMPORTANT: Calls to this method must be within a syncronized block on this * logger. * * @param lastPart * the suffix (i.e. last part) of the child logger name. This * parameter may not include dots, i.e. the logger separator * character. * @return */ HLogger createChildByLastNamePart(final String lastPart) { int i_index = lastPart.indexOf(CoreConstants.DOT); if (i_index != -1) { throw new IllegalArgumentException("Child name [" + lastPart + " passed as parameter, may not include [" + CoreConstants.DOT + "]"); } if (childrenMap == null) { childrenMap = new HashMap<String, HLogger>(2); } HLogger childHLogger; if (this.isRootLogger()) { childHLogger = new HLogger(lastPart, this); } else { childHLogger = new HLogger(name + CoreConstants.DOT + lastPart, this); } childrenMap.put(lastPart, childHLogger); childHLogger.effectiveLevel = this.effectiveLevel; return childHLogger; }
@Override public String convert(IAccessEvent ae) { StringBuilder buf = new StringBuilder(); buf.append("HTTP/1.1 "); int statusCode = ae.getStatusCode(); buf.append(statusCode); buf.append(" "); buf.append(getStatusCodeDescription(statusCode)); buf.append(CoreConstants.LINE_SEPARATOR); List<String> hnList = ae.getResponseHeaderNameList(); for(String headerName: hnList) { buf.append(headerName); buf.append(": "); buf.append(ae.getResponseHeader(headerName)); buf.append(CoreConstants.LINE_SEPARATOR); } buf.append(CoreConstants.LINE_SEPARATOR); buf.append(ae.getResponseContent()); buf.append(CoreConstants.LINE_SEPARATOR); return buf.toString(); }
/** * Create a child of this logger by suffix, that is, the part of the name * extending this logger. For example, if this logger is named "x.y" and the * lastPart is "z", then the created child logger will be named "x.y.z". * * <p> * IMPORTANT: Calls to this method must be within a synchronized block on this * logger. * * @param lastPart * the suffix (i.e. last part) of the child logger name. This * parameter may not include dots, i.e. the logger separator * character. * @return */ Logger createChildByLastNamePart(final String lastPart) { int i_index = LoggerNameUtil.getFirstSeparatorIndexOf(lastPart); if (i_index != -1) { throw new IllegalArgumentException("Child name [" + lastPart + " passed as parameter, may not include [" + CoreConstants.DOT + "]"); } if (childrenList == null) { childrenList = new ArrayList<Logger>(); } Logger childLogger; if (this.isRootLogger()) { childLogger = new Logger(lastPart, this, this.loggerContext); } else { childLogger = new Logger(name + CoreConstants.DOT + lastPart, this, this.loggerContext); } childrenList.add(childLogger); childLogger.effectiveLevelInt = this.effectiveLevelInt; return childLogger; }
static int computeDotIndexes(final String className, int[] dotArray) { int dotCount = 0; int k = 0; while (true) { // ignore the $ separator in our computations. This is both convenient // and sensible. k = className.indexOf(CoreConstants.DOT, k); if (k != -1 && dotCount < ClassicConstants.MAX_DOTS) { dotArray[dotCount] = k; dotCount++; k++; } else { break; } } return dotCount; }
/** * @param sb The StringBuilder the STEPs are appended to. * @param indentLevel indentation level used for the STEPs, usually REGULAR_EXCEPTION_INDENT. * @param tp the IThrowableProxy containing the STEPs. */ public static void subjoinSTEPArray(StringBuilder sb, int indentLevel, IThrowableProxy tp) { StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); int commonFrames = tp.getCommonFrames(); for (int i = 0; i < stepArray.length - commonFrames; i++) { StackTraceElementProxy step = stepArray[i]; indent(sb, indentLevel); subjoinSTEP(sb, step); sb.append(CoreConstants.LINE_SEPARATOR); } if (commonFrames > 0) { indent(sb, indentLevel); sb.append("... ").append(commonFrames).append(" common frames omitted") .append(CoreConstants.LINE_SEPARATOR); } }
@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()); }
public void run() { if (mainConfigurationURL == null) { addInfo("Due to missing top level configuration file, skipping reconfiguration"); return; } LoggerContext lc = (LoggerContext) context; addInfo(CoreConstants.RESET_MSG_PREFIX + "named [" + context.getName() + "]"); if (mainConfigurationURL.toString().endsWith("xml")) { performXMLConfiguration(lc); } else if (mainConfigurationURL.toString().endsWith("groovy")) { if (EnvUtil.isGroovyAvailable()) { lc.reset(); // avoid directly referring to GafferConfigurator so as to avoid // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214 GafferUtil.runGafferConfiguratorOn(lc, this, mainConfigurationURL); } else { addError("Groovy classes are not available on the class path. ABORTING INITIALIZATION."); } } }
@Test public void shouldLimitTotalLinesExcludingSkipped() throws Exception { //given final Throwable t = TeztHelper.makeNestedException(0); t.printStackTrace(pw); final ILoggingEvent le = createLoggingEvent(t); tpc.setOptionList(Arrays.asList("3", "shouldLimitTotalLinesExcludingSkipped")); tpc.start(); //when final String result = tpc.convert(le); //then String[] lines = result.split(CoreConstants.LINE_SEPARATOR); assertThat(lines).hasSize(3 + 1); }
@Test public void testPerformanceWithParameters() { if (EnvUtilForTests.isLinux()) { return; } LoggingEventWithParametersBuilder builder = new LoggingEventWithParametersBuilder(); // warm up for (int i = 0; i < 3; i++) { doLoop(builder, LOOP_LEN); noos.reset(); } double rt = doLoop(builder, LOOP_LEN); long averageSize = (long) (noos.size() / (LOOP_LEN)); System.out.println("noos size " + noos.size() + " average size=" + averageSize); double averageSizeLimit = 160; assertTrue("averageSize " + averageSize + " should be less than " + averageSizeLimit, averageSizeLimit > averageSize); // the reference was computed on Orion (Ceki's computer) long referencePerf = 7000; BogoPerf.assertDuration(rt, referencePerf, CoreConstants.REFERENCE_BIPS); }
@Test public void autoscanShouldReconfigureOnFileChange() throws Exception { String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "scan1.xml"; configure(configFileAsStr); File file = new File(configFileAsStr); file.setLastModified(System.currentTimeMillis()); Thread.sleep(10); // scanning requires 16 logs for (int i = 0; i < 16; i++) { logger.debug("after " + i); } loggerContext.getExecutorService().shutdown(); loggerContext.getExecutorService().awaitTermination(1000, TimeUnit.MILLISECONDS); StatusChecker checker = new StatusChecker(loggerContext); checker.assertIsErrorFree(); checker.assertContainsMatch(CoreConstants.RESET_MSG_PREFIX); }
@Test public void testAppendThrowable() throws Exception { StringBuilder buf = new StringBuilder(); DummyThrowableProxy tp = new DummyThrowableProxy(); tp.setClassName("test1"); tp.setMessage("msg1"); StackTraceElement ste1 = new StackTraceElement("c1", "m1", "f1", 1); StackTraceElement ste2 = new StackTraceElement("c2", "m2", "f2", 2); StackTraceElementProxy[] stepArray = { new StackTraceElementProxy(ste1), new StackTraceElementProxy(ste2) }; tp.setStackTraceElementProxyArray(stepArray); DefaultThrowableRenderer renderer = (DefaultThrowableRenderer) layout .getThrowableRenderer(); renderer.render(buf, tp); System.out.println(buf.toString()); String[] result = buf.toString().split(CoreConstants.LINE_SEPARATOR); System.out.println(result[0]); assertEquals("test1: msg1", result[0]); assertEquals(DefaultThrowableRenderer.TRACE_PREFIX + "at c1.m1(f1:1)", result[1]); }
@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)); }
@Override public void setContext(Context context) { super.setContext(context); final String hostname = context.getProperty(CoreConstants.HOSTNAME_KEY); if (hostname == null) { addError("Hostname could not be found in context. HostNamePartitioningStrategy will not work."); } else { hostnameHash = ByteBuffer.allocate(4).putInt(hostname.hashCode()).array(); } }
@Override public void setContext(Context context) { super.setContext(context); final String hostname = context.getProperty(CoreConstants.CONTEXT_NAME_KEY); if (hostname == null) { addError("Hostname could not be found in context. HostNamePartitioningStrategy will not work."); } else { contextNameHash = ByteBuffer.allocate(4).putInt(hostname.hashCode()).array(); } }
@Test public void shouldPartitionByHostName() { ctx.putProperty(CoreConstants.HOSTNAME_KEY, "localhost"); unit.setContext(ctx); final ILoggingEvent evt = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.ALL, "msg", null, new Object[0]); Assert.assertThat(unit.createKey(evt), Matchers.equalTo(ByteBuffer.allocate(4).putInt("localhost".hashCode()).array())); }
@Override public String doLayout(ILoggingEvent event) { Instant instant = Instant.ofEpochMilli(event.getTimeStamp()); ZonedDateTime dateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); StringBuilder log = new StringBuilder(dateTime.format(dateFormat)); log.append(String.format(" %-5s", event.getLevel().levelStr)); if (requireThread) { log.append(String.format(" [%s]", event.getThreadName())); } int lineNumber = event.getCallerData().length > 0 ? event.getCallerData()[0].getLineNumber() : 0; log.append(String.format(" %s:%d: ", event.getLoggerName(), lineNumber)); ThrowableProxy proxy = (ThrowableProxy) event.getThrowableProxy(); if (requireAlertLevel || requireErrorCode) { appendExtraExceptionFlags(log, AbstractLoggingException.getFromThrowableProxy(proxy)); } log.append(event.getFormattedMessage()).append(CoreConstants.LINE_SEPARATOR); appendStackTrace(log, proxy); if (proxy != null) { loopCauses(log, proxy, 0); } return log.toString(); }
/** * ログbyte配列のの文字列変換 * * @param encodedLog ログbyte配列 * @return 変換後文字列 */ protected String toStringLog(byte[] encodedLog) { String s = new String(encodedLog, getCharset()); if (s.endsWith(CoreConstants.LINE_SEPARATOR)) { s = s.substring(0, s.length() - CoreConstants.LINE_SEPARATOR.length()); } return s; }
public void printFirstLine(StringBuilder sb, IThrowableProxy tp) { int commonFrames = tp.getCommonFrames(); if (commonFrames > 0) { sb.append("\t").append(CoreConstants.CAUSED_BY); } sb.append(tp.getClassName()).append(": ").append(Transform.escapeTags(tp.getMessage())); sb.append(CoreConstants.LINE_SEPARATOR); }
private void appendEvent(E eventObject) { //init Event Object if (!(eventObject instanceof LoggingEvent)) { return; } LoggingEvent event = (LoggingEvent) eventObject; List<LogItem> logItems = new ArrayList<LogItem>(); LogItem item = new LogItem(); logItems.add(item); item.SetTime((int) (event.getTimeStamp() / 1000)); //item.PushBack("time", formatter.format(new Date(event.getTimeStamp()))); item.PushBack("level", event.getLevel().toString()); item.PushBack("thread", event.getThreadName()); StackTraceElement[] caller = event.getCallerData(); if (caller != null && caller.length > 0) { item.PushBack("location", caller[0].toString()); } String message = event.getFormattedMessage(); IThrowableProxy iThrowableProxy = event.getThrowableProxy(); if (iThrowableProxy != null) { message += CoreConstants.LINE_SEPARATOR; message += getExceptionInfo(iThrowableProxy); message += fullDump(event.getThrowableProxy().getStackTraceElementProxyArray()); } item.PushBack("message", message); producer.send(projectConfig.projectName, logstore, topic, null, logItems, new LoghubAppenderCallback<E>(this, projectConfig.projectName, logstore, topic, null, logItems)); }
private String fullDump(StackTraceElementProxy[] stackTraceElementProxyArray) { StringBuilder builder = new StringBuilder(); for (StackTraceElementProxy step : stackTraceElementProxyArray) { builder.append(CoreConstants.LINE_SEPARATOR); String string = step.toString(); builder.append(CoreConstants.TAB).append(string); ThrowableProxyUtil.subjoinPackagingData(builder, step); } return builder.toString(); }