Java Code Examples for org.apache.log4j.spi.LoggingEvent#getThrowableStrRep()

The following examples show how to use org.apache.log4j.spi.LoggingEvent#getThrowableStrRep() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WriterAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Actual writing occurs here.
 *
 * <p>Most subclasses of <code>WriterAppender</code> will need to
 * override this method.
 *
 * @since 0.9.0
 */
protected void subAppend(LoggingEvent event) {
    this.qw.write(this.layout.format(event));

    if (layout.ignoresThrowable()) {
        String[] s = event.getThrowableStrRep();
        if (s != null) {
            int len = s.length;
            for (int i = 0; i < len; i++) {
                this.qw.write(s[i]);
                this.qw.write(Layout.LINE_SEP);
            }
        }
    }

    if (shouldFlush(event)) {
        this.qw.flush();
    }
}
 
Example 2
Source File: TerminalLoggingAppender.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
    final StringBuilder buffer = new StringBuilder();
    buffer.append(layout.format(event));
    if(layout.ignoresThrowable()) {
        final String[] trace = event.getThrowableStrRep();
        if(trace != null) {
            buffer.append(Layout.LINE_SEP);
            for(final String t : trace) {
                buffer.append(t).append(Layout.LINE_SEP);
            }
        }
    }
    console.printf("\r%s%s%s", Ansi.ansi()
                    .saveCursorPosition()
                    .eraseLine(Ansi.Erase.ALL)
                    .fg(Ansi.Color.MAGENTA)
                    .restoreCursorPosition(),
            buffer.toString(), Ansi.ansi().reset());
}
 
Example 3
Source File: SystemLogAppender.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
    if(null == event.getMessage()) {
        return;
    }
    final StringBuilder buffer = new StringBuilder();
    buffer.append(layout.format(event));
    if(layout.ignoresThrowable()) {
        final String[] trace = event.getThrowableStrRep();
        if(trace != null) {
            buffer.append(Layout.LINE_SEP);
            for(final String t : trace) {
                buffer.append(t).append(Layout.LINE_SEP);
            }
        }
    }
    library.NSLog("%@", buffer.toString());
}
 
Example 4
Source File: NTEventLogAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void append(LoggingEvent event) {

    StringBuffer sbuf = new StringBuffer();

    sbuf.append(layout.format(event));
    if(layout.ignoresThrowable()) {
      String[] s = event.getThrowableStrRep();
      if (s != null) {
   int len = s.length;
   for(int i = 0; i < len; i++) {
     sbuf.append(s[i]);
   }
      }
    }
    // Normalize the log message level into the supported categories
    int nt_category = event.getLevel().toInt();

    // Anything above FATAL or below DEBUG is labeled as INFO.
    //if (nt_category > FATAL || nt_category < DEBUG) {
    //  nt_category = INFO;
    //}
    reportEvent(_handle, sbuf.toString(), nt_category);
  }
 
Example 5
Source File: WriterAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Actual writing occurs here.
 *
 * <p>Most subclasses of <code>WriterAppender</code> will need to
 * override this method.
 * @param event The event to log.
 *
 * @since 0.9.0
 */
protected void subAppend(LoggingEvent event) {
    this.qw.write(this.layout.format(event));

    if (layout.ignoresThrowable()) {
        String[] s = event.getThrowableStrRep();
        if (s != null) {
            int len = s.length;
            for (int i = 0; i < len; i++) {
                this.qw.write(s[i]);
                this.qw.write(Layout.LINE_SEP);
            }
        }
    }

    if (shouldFlush(event)) {
        this.qw.flush();
    }
}
 
Example 6
Source File: WriterAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    Actual writing occurs here.

    <p>Most subclasses of <code>WriterAppender</code> will need to
    override this method.

    @since 0.9.0 */
 protected
 void subAppend(LoggingEvent event) {
   this.qw.write(this.layout.format(event));

   if(layout.ignoresThrowable()) {
     String[] s = event.getThrowableStrRep();
     if (s != null) {
int len = s.length;
for(int i = 0; i < len; i++) {
  this.qw.write(s[i]);
  this.qw.write(Layout.LINE_SEP);
}
     }
   }

   if(this.immediateFlush) {
     this.qw.flush();
   }
 }
 
Example 7
Source File: SocketCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
private void handleLog4j(LoggingEvent loggingEvent) throws UnknownHostException {
    LOGGER.debug("Received log event {}", loggingEvent.getLoggerName());
    Map<String, Object> data = new HashMap<>();
    data.put("type", "log");

    data.put("timestamp", loggingEvent.getTimeStamp());
    data.put("loggerClass", loggingEvent.getFQNOfLoggerClass());
    data.put("loggerName", loggingEvent.getLoggerName());
    data.put("threadName", loggingEvent.getThreadName());
    data.put("message", loggingEvent.getMessage());
    data.put("level", loggingEvent.getLevel().toString());
    data.put("renderedMessage", loggingEvent.getRenderedMessage());
    data.put("MDC", loggingEvent.getProperties());
    putLocation(data, loggingEvent.getLocationInformation());
    String[] throwableAr = loggingEvent.getThrowableStrRep();
    if (throwableAr != null) {
        data.put("throwable", join(throwableAr));
    }

    try {
        PropertiesPreparator.prepare(data, properties);
    } catch (Exception e) {
        LOGGER.warn("Can't prepare data for the dispatcher", e);
    }

    String topic = loggerName2Topic(loggingEvent.getLoggerName());
    Event event = new Event(topic, data);
    dispatcher.postEvent(event);
}
 
Example 8
Source File: StringLog4jFormatter.java    From suro with Apache License 2.0 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
    StringBuilder sb = new StringBuilder();
    sb.append(fmt.print(new DateTime())).append(fieldDelim);
    sb.append(event.getLevel()).append(fieldDelim).append(event.getLoggerName());

    Object obj = event.getMessage();

    routingKey = null;

    // time UTC^]Level^]Map
    if (obj instanceof Map) {
        Map map = (Map) event.getMessage();
        Iterator it = map.keySet().iterator();
        String key = null;
        while (it.hasNext()) {
            key = (String) it.next();
            sb.append(fieldDelim).append(key).append(fieldEqual).append(map.get(key));
            if (key.equalsIgnoreCase(TagKey.ROUTING_KEY)) {
                routingKey = (String) map.get(key);
            }
        }
    } else {
        // time UTC^]Level^]String
        sb.append(fieldDelim).append(obj.toString());
    }

    // Extract exceptions
    String[] s = event.getThrowableStrRep();
    if (s != null && s.length > 0) {
        sb.append(fieldDelim).append("Exception").append(fieldEqual).append(s[0]);
        for (int i = 1; i < s.length; i++) {
            sb.append('\n').append(s[i]);
        }
    }

    return sb.toString();
}
 
Example 9
Source File: IMAppender.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Send the contents of the cyclic buffer as an IM message.
 */
protected void sendBuffer() {
    try {
        final StringBuilder buf = new StringBuilder();

        final int len = cb.length();
        for (int i = 0; i < len; i++) {
            final LoggingEvent event = cb.get();
            buf.append(layout.format(event));
            // if layout doesn't handle exception, the appender has to do it
            if (layout.ignoresThrowable()) {
                final String[] s = event.getThrowableStrRep();
                if (s != null) {
                    for (int j = 0; j < s.length; j++) {
                        buf.append(Layout.LINE_SEP);
                        buf.append(s[j]);
                    }
                }
            }
        }

        if (chatroom) {
            groupchat.sendMessage(buf.toString());
        } else {
            final Iterator iter = chats.iterator();
            while (iter.hasNext()) {
                final Chat chat = (Chat) iter.next();
                chat.sendMessage(buf.toString());
            }
        }

    } catch (final Exception e) {
        errorHandler.error("Could not send message in IMAppender [" + name + "]", e, ErrorCode.GENERIC_FAILURE);
    }
}
 
Example 10
Source File: LCSLog4jAppender.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void append(LoggingEvent loggingEvent) {
  Message message;
  if (loggingEvent.getMessage() instanceof Message) {
    message = (Message) loggingEvent.getMessage();
  } else {
    String value = layout.format(loggingEvent);
    if (layout.ignoresThrowable()) {
      String[] lineList = loggingEvent.getThrowableStrRep();
      if (lineList != null) {
        for (String line : lineList) {
          value += line + Layout.LINE_SEP;
        }
      }
    }

    message = new Message();
    message.setCreateTimestamp(System.currentTimeMillis());
    message.setMessageType(MessageType.BINARY);
    try {
      message.setMessage(value.getBytes(encoding));
    } catch (Exception e) {
      logger.error("appendMessage failed", e);
      return;
    }
  }
  lcsAppender.addMessage(message);
}
 
Example 11
Source File: TelnetAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** Handles a log event.  For this appender, that means writing the
   message to each connected client.  */
 protected void append(LoggingEvent event) {
   sh.send(this.layout.format(event));
   if(layout.ignoresThrowable()) {
     String[] s = event.getThrowableStrRep();
     if (s != null) {
int len = s.length;
for(int i = 0; i < len; i++) {
  sh.send(s[i]);
  sh.send(Layout.LINE_SEP);
}
     }
   }
 }
 
Example 12
Source File: CassandraAppender.java    From cassandra-log4j-appender with Apache License 2.0 5 votes vote down vote up
/**
   * 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);
  }
 
Example 13
Source File: LogPipe.java    From MSPaintIDE with MIT License 5 votes vote down vote up
public void consume(LoggingEvent event) {
    try {
        IOUtils.write(format(event), this.standardOut);

        String[] stackTrace = event.getThrowableStrRep();
        if (stackTrace != null) {
            for (var value : stackTrace) {
                IOUtils.write(value + Layout.LINE_SEP, this.errorOut);
            }
        }
    } catch (IOException e) {
        e.printStackTrace(); // Not printing to logger as it may cause a recursive call
    }
}
 
Example 14
Source File: UnifiedSystemLogAppender.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
    if(null == event.getMessage()) {
        return;
    }
    // Category name
    final String logger = String.format("%s %s", event.getThreadName(), event.getLogger().getName());
    switch(event.getLevel().toInt()) {
        case Level.FATAL_INT:
        case Level.ERROR_INT:
            this.log(OS_LOG_TYPE_ERROR, logger, event.getMessage().toString());
            break;
        case Level.TRACE_INT:
        case Level.DEBUG_INT:
            this.log(OS_LOG_TYPE_DEBUG, logger, event.getMessage().toString());
            break;
        case Level.INFO_INT:
            this.log(OS_LOG_TYPE_INFO, logger, event.getMessage().toString());
            break;
        case Level.WARN_INT:
        default:
            this.log(OS_LOG_TYPE_DEFAULT, logger, event.getMessage().toString());
            break;
    }
    if(layout.ignoresThrowable()) {
        // Appender responsible for rendering
        final String[] trace = event.getThrowableStrRep();
        if(trace != null) {
            for(final String t : trace) {
                this.log(OS_LOG_TYPE_DEFAULT, logger, t);
            }
        }
    }
}
 
Example 15
Source File: LogAppender.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void append(LoggingEvent event) {
    if (event == null) return;
    String line = this.layout.format(event);
    if (line != null) this.lines.add(line);
    if (event.getThrowableInformation() != null) {
        for (String t: event.getThrowableStrRep()) if (t != null)  this.lines.add(t + "\n");
    }
    if (this.a.incrementAndGet() % 100 == 0) {
        clean(this.maxlines);
        this.a.set(0);
    }
}
 
Example 16
Source File: JsonLog4jFormatter.java    From suro with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public String format(LoggingEvent event) {
    Object obj = event.getMessage();

    routingKey = null;

    if (obj instanceof Map) {
        Map map = (Map) event.getMessage();
        DateTime now = new DateTime();
        map.put("ts", now.getMillis());
        map.put("datetime", fmt.print(now));
        map.put("logLevel", event.getLevel().toString());
        map.put("class", event.getLoggerName());

        routingKey = (String) map.get(TagKey.ROUTING_KEY);

        // Extract exceptions
        String[] s = event.getThrowableStrRep();
        if (s != null && s.length > 0) {
            map.put("Exception", s);
        }
        try {
            return jsonMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            jsonParsingError.incrementAndGet();
            return stringFormatter.format(event);
        }
    } else {
        jsonParsingError.incrementAndGet();
        return stringFormatter.format(event);
    }
}
 
Example 17
Source File: HTMLLayout.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public
String format(LoggingEvent event) {

  if(sbuf.capacity() > MAX_CAPACITY) {
    sbuf = new StringBuffer(BUF_SIZE);
  } else {
    sbuf.setLength(0);
  }

  sbuf.append(Layout.LINE_SEP + "<tr>" + Layout.LINE_SEP);

  sbuf.append("<td>");
  sbuf.append(event.timeStamp - LoggingEvent.getStartTime());
  sbuf.append("</td>" + Layout.LINE_SEP);

  String escapedThread = Transform.escapeTags(event.getThreadName());
  sbuf.append("<td title=\"" + escapedThread + " thread\">");
  sbuf.append(escapedThread);
  sbuf.append("</td>" + Layout.LINE_SEP);

  sbuf.append("<td title=\"Level\">");
  if (event.getLevel().equals(Level.DEBUG)) {
    sbuf.append("<font color=\"#339933\">");
    sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
    sbuf.append("</font>");
  }
  else if(event.getLevel().isGreaterOrEqual(Level.WARN)) {
    sbuf.append("<font color=\"#993300\"><strong>");
    sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
    sbuf.append("</strong></font>");
  } else {
    sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
  }
  sbuf.append("</td>" + Layout.LINE_SEP);

  String escapedLogger = Transform.escapeTags(event.getLoggerName());
  sbuf.append("<td title=\"" + escapedLogger + " category\">");
  sbuf.append(escapedLogger);
  sbuf.append("</td>" + Layout.LINE_SEP);

  if(locationInfo) {
    LocationInfo locInfo = event.getLocationInformation();
    sbuf.append("<td>");
    sbuf.append(Transform.escapeTags(locInfo.getFileName()));
    sbuf.append(':');
    sbuf.append(locInfo.getLineNumber());
    sbuf.append("</td>" + Layout.LINE_SEP);
  }

  sbuf.append("<td title=\"Message\">");
  sbuf.append(Transform.escapeTags(event.getRenderedMessage()));
  sbuf.append("</td>" + Layout.LINE_SEP);
  sbuf.append("</tr>" + Layout.LINE_SEP);

  if (event.getNDC() != null) {
    sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : xx-small;\" colspan=\"6\" title=\"Nested Diagnostic Context\">");
    sbuf.append("NDC: " + Transform.escapeTags(event.getNDC()));
    sbuf.append("</td></tr>" + Layout.LINE_SEP);
  }

  String[] s = event.getThrowableStrRep();
  if(s != null) {
    sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : xx-small;\" colspan=\"6\">");
    appendThrowableAsHTML(s, sbuf);
    sbuf.append("</td></tr>" + Layout.LINE_SEP);
  }

  return sbuf.toString();
}
 
Example 18
Source File: SyslogAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public
void append(LoggingEvent event) {

  if(!isAsSevereAsThreshold(event.getLevel()))
    return;

  // We must not attempt to append if sqw is null.
  if(sqw == null) {
    errorHandler.error("No syslog host is set for SyslogAppedender named \""+
	this.name+"\".");
    return;
  }

  if (!layoutHeaderChecked) {
      if (layout != null && layout.getHeader() != null) {
          sendLayoutMessage(layout.getHeader());
      }
      layoutHeaderChecked = true;
  }

  String hdr = getPacketHeader(event.timeStamp);
  String packet = layout.format(event);
  if(facilityPrinting || hdr.length() > 0) {
      StringBuffer buf = new StringBuffer(hdr);
      if(facilityPrinting) {
          buf.append(facilityStr);
      }
      buf.append(packet);
      packet = buf.toString();
  }

  sqw.setLevel(event.getLevel().getSyslogEquivalent());
  //
  //   if message has a remote likelihood of exceeding 1024 bytes
  //      when encoded, consider splitting message into multiple packets
  if (packet.length() > 256) {
      splitPacket(hdr, packet);
  } else {
      sqw.write(packet);
  }

  if (layout.ignoresThrowable()) {
    String[] s = event.getThrowableStrRep();
    if (s != null) {
      for(int i = 0; i < s.length; i++) {
          if (s[i].startsWith("\t")) {
             sqw.write(hdr+TAB+s[i].substring(1));
          } else {
             sqw.write(hdr+s[i]);
          }
      }
    }
  }
}
 
Example 19
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
    Send the contents of the cyclic buffer as an e-mail message.
  */
 protected
 void sendBuffer() {

   // Note: this code already owns the monitor for this
   // appender. This frees us from needing to synchronize on 'cb'.
   try {
     MimeBodyPart part = new MimeBodyPart();

     StringBuffer sbuf = new StringBuffer();
     String t = layout.getHeader();
     if(t != null)
sbuf.append(t);
     int len =  cb.length();
     for(int i = 0; i < len; i++) {
//sbuf.append(MimeUtility.encodeText(layout.format(cb.get())));
LoggingEvent event = cb.get();
sbuf.append(layout.format(event));
if(layout.ignoresThrowable()) {
  String[] s = event.getThrowableStrRep();
  if (s != null) {
    for(int j = 0; j < s.length; j++) {
      sbuf.append(s[j]);
      sbuf.append(Layout.LINE_SEP);
    }
  }
}
     }
     t = layout.getFooter();
     if(t != null)
sbuf.append(t);
     part.setContent(sbuf.toString(), layout.getContentType());

     Multipart mp = new MimeMultipart();
     mp.addBodyPart(part);
     msg.setContent(mp);

     msg.setSentDate(new Date());
     Transport.send(msg);
   } catch(Exception e) {
     LogLog.error("Error occured while sending e-mail notification.", e);
   }
 }
 
Example 20
Source File: Log4jQiniuAppender.java    From qiniu-logging-plugin with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected void append(LoggingEvent logEvent) {
    Point point = new Point();
    point.append("timestamp", logEvent.getTimeStamp());
    point.append("level", logEvent.getLevel().toString());
    point.append("logger", logEvent.getLoggerName());
    point.append("marker", "");//log4j 1.x doest not support marker
    point.append("message", logEvent.getMessage().toString());
    point.append("thread_name", logEvent.getThreadName());
    point.append("thread_id", 0); // log4j 1.x doest not support thread id
    point.append("thread_priority", 0);
    if (logEvent.getThrowableStrRep() != null) {
        StringBuilder exceptionBuilder = new StringBuilder();
        for (String msg : logEvent.getThrowableStrRep()) {
            exceptionBuilder.append(msg).append("\n");
        }
        point.append("exception", exceptionBuilder.toString());
    } else {
        point.append("exception", "");
    }

    //lock
    this.rwLock.lock();
    if (!batch.canAdd(point)) {
        final byte[] postBody = batch.toString().getBytes(Constants.UTF_8);
        try {
            this.executorService.execute(new Runnable() {
                public void run() {
                    try {
                        Response response = logPushSender.send(postBody);
                        response.close();
                    } catch (QiniuException e) {
                        //e.printStackTrace();
                        guard.write(postBody);
                    }
                }
            });
        } catch (RejectedExecutionException ex) {
            guard.write(postBody);
        }

        batch.clear();
    }
    batch.add(point);
    this.rwLock.unlock();
}