org.apache.log4j.spi.LoggingEvent Java Examples

The following examples show how to use org.apache.log4j.spi.LoggingEvent. 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: EclipseLogAppender.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
	if (isDoLog(event.getLevel())) {
		String logString = layout.format(event);

		ILog myLog = getLog();
		if (myLog != null) {
			String loggerName = event.getLoggerName();
			int severity = mapLevel(event.getLevel());
			final Throwable throwable = event.getThrowableInformation() != null ? event.getThrowableInformation()
					.getThrowable() : null;
			IStatus status = createStatus(severity, loggerName, logString, throwable);
			getLog().log(status);
		} else {
			// nothing to do (message should be logged to stdout by default appender)
		}
	}
}
 
Example #2
Source File: ThreadLocalAwareLogger.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public void l7dlog(Priority priority, String key, Object[] params, Throwable t) {
    if (isForcedToLog(priority)) {
        // from super.l7dlog:
        String pattern = getResourceBundleString(key);
        String msg;
        if (pattern == null)
            msg = key;
        else
            msg = java.text.MessageFormat.format(pattern, params);

        final Appender forcedAppender = getForcedAppender();

        // force the logging and modify the log message (the latter might return the original message)
        if (forcedAppender != null) {
            // only call the forced appender
            forcedAppender.doAppend(new LoggingEvent(FQCN, this, priority, modifyLogMessage(msg), t));
        } else {
            // go via the normal appenders
            forcedLog(FQCN, priority, modifyLogMessage(msg), t);
        }

    } else {
        super.l7dlog(priority, key, params, t);
    }
}
 
Example #3
Source File: JulAppender.java    From presto with Apache License 2.0 6 votes vote down vote up
/**
 * Append a log event at the appropriate JUL level, depending on the log4j level.
 */
@Override
protected void append(LoggingEvent loggingEvent)
{
    java.util.logging.Logger logger = java.util.logging.Logger.getLogger(loggingEvent.getLoggerName());
    if (logger == null) {
        LogLog.warn(format("Cannot obtain JUL %s. Verify that this appender is used while an appropriate LogManager is active.", loggingEvent.getLoggerName()));
        return;
    }

    Level level = loggingEvent.getLevel();
    java.util.logging.Level julLevel = convertLog4jLevel(level);

    LogRecord record = new LogRecord(julLevel, loggingEvent.getRenderedMessage());
    record.setMillis(loggingEvent.getTimeStamp());
    LocationInfo location = loggingEvent.getLocationInformation();
    if (location != null) {
        record.setSourceClassName(location.getClassName());
        record.setSourceMethodName(location.getMethodName());
    }

    logger.log(record);
}
 
Example #4
Source File: RewriteAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRewrite() throws Exception {
    Logger logger = LogManager.getLogger("test");
    ThreadContext.put("key1", "This is a test");
    ThreadContext.put("hello", "world");
    logger.debug("Say hello");
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    assertNotNull("No properties in the event", events.get(0).getProperties());
    assertTrue("Key was not inserted", events.get(0).getProperties().containsKey("key2"));
    assertEquals("Key value is incorrect", "Log4j", events.get(0).getProperties().get("key2"));
}
 
Example #5
Source File: DailyMaxRollingFileAppender.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
   DailyMaxRollingFileAppender dmrfa = new DailyMaxRollingFileAppender();
   dmrfa.setDatePattern("'.'yyyy-MM-dd-HH-mm");
   dmrfa.setFile("prova");
   System.out.println("dmrfa.getMaxBackupIndex():" + dmrfa.getMaxBackupIndex());
   dmrfa.activateOptions();

   for(int i = 0; i < 5; ++i) {
      dmrfa.subAppend((LoggingEvent)null);

      try {
         Thread.sleep(60000L);
      } catch (InterruptedException var3) {
         ;
      }

      System.out.println("Fine attesa");
   }

}
 
Example #6
Source File: StructuredJsonLayoutTest.java    From common with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  when(builder.withTimeMs(anyLong())).thenReturn(builder);
  when(builder.withLoggerName(anyString())).thenReturn(builder);
  when(builder.withLevel(anyString())).thenReturn(builder);
  when(builder.withMessageJson(anyString())).thenReturn(builder);
  when(builder.build()).thenReturn(SERIALIZED_MSG);
  loggingEvent = new LoggingEvent(
      "fcqn",
      new FakeCategory(LOGGER_NAME),
      LOG_TIME_MS,
      LOG_LEVEL,
      STRUCTURED_MSG,
      null
  );
  layout = new StructuredJsonLayout(() -> builder);
}
 
Example #7
Source File: CompositeRollingAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Handles append time behavior for CompositeRollingAppender.  This checks
 * if a roll over either by date (checked first) or time (checked second)
 * is need and then appends to the file last.
*/
protected void subAppend(LoggingEvent event) {

	if (rollDate) {
		long n = System.currentTimeMillis();
		if (n >= nextCheck) {
			now.setTime(n);
			nextCheck = rc.getNextCheckMillis(now);

			rollOverTime();
		}
	}

	if (rollSize) {
		if ((fileName != null) && ((CountingQuietWriter) qw).getCount() >= maxFileSize) {
		    rollOverSize();
		}
	}

	super.subAppend(event);
}
 
Example #8
Source File: LoghubAppender.java    From aliyun-log-log4j-appender with Apache License 2.0 6 votes vote down vote up
private String getThrowableStr(LoggingEvent event) {
  ThrowableInformation throwable = event.getThrowableInformation();
  if (throwable == null) {
    return null;
  }
  StringBuilder sb = new StringBuilder();
  boolean isFirst = true;
  for (String s : throwable.getThrowableStrRep()) {
    if (isFirst) {
      isFirst = false;
    } else {
      sb.append(System.getProperty("line.separator"));
    }
    sb.append(s);
  }
  return sb.toString();
}
 
Example #9
Source File: JGroupsReportingLifeCycleListenerImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
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 #11
Source File: StringMatchFilter.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    Returns {@link Filter#NEUTRAL} is there is no string match.
  */
 public
 int decide(LoggingEvent event) {
   String msg = event.getRenderedMessage();

   if(msg == null ||  stringToMatch == null)
     return Filter.NEUTRAL;
   

   if( msg.indexOf(stringToMatch) == -1 ) {
     return Filter.NEUTRAL;
   } else { // we've got a match
     if(acceptOnMatch) {
return Filter.ACCEPT;
     } else {
return Filter.DENY;
     }
   }
 }
 
Example #12
Source File: KafkaAppender.java    From SkyEye with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 覆写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);
}
 
Example #13
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 #14
Source File: WriterAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * This method is called by the {@link AppenderSkeleton#doAppend}
 * method.
 *
 * <p>If the output stream exists and is writable then write a log
 * statement to the output stream. Otherwise, write a single warning
 * message to <code>System.err</code>.
 *
 * <p>The format of the output will depend on this appender's
 * layout.
 */
public void append(LoggingEvent event) {

    // Reminder: the nesting of calls is:
    //
    //    doAppend()
    //      - check threshold
    //      - filter
    //      - append();
    //        - checkEntryConditions();
    //        - subAppend();

    if (!checkEntryConditions()) {
        return;
    }
    subAppend(event);
}
 
Example #15
Source File: PatternLayoutTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Tests format.
 */
public void testFormat() {
  Logger logger = Logger.getLogger("org.apache.log4j.LayoutTest");
  LoggingEvent event =
    new LoggingEvent(
      "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null);
  PatternLayout layout = (PatternLayout) createLayout();
  String result = layout.format(event);
  StringBuffer buf = new StringBuffer(100);
  buf.append('[');
  buf.append(event.getThreadName());
  buf.append("] ");
  buf.append(event.getLevel().toString());
  buf.append(' ');
  buf.append(event.getLoggerName());
  buf.append(" - ");
  buf.append(event.getMessage());
  buf.append(System.getProperty("line.separator"));
  assertEquals(buf.toString(), result);
}
 
Example #16
Source File: LoggingEventStringSerde.java    From samza with Apache License 2.0 5 votes vote down vote up
/**
 * Convert bytes to a {@link org.apache.log4j.spi.LoggingEvent}. This LoggingEvent uses logging
 * information of the {@link LoggingEventStringSerde}, which includes log
 * name, log category and log level.
 *
 * @param bytes bytes for decoding
 * @return LoggingEvent a new LoggingEvent
 */
@Override
public LoggingEvent fromBytes(byte[] bytes) {
  if (bytes == null) {
    return null;
  }
  String log;
  try {
    log = new String(bytes, ENCODING);
  } catch (UnsupportedEncodingException e) {
    throw new SamzaException("can not decode to String", e);
  }
  return new LoggingEvent(logger.getName(), logger, logger.getLevel(), log, null);
}
 
Example #17
Source File: EqualsRuleTest.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
/**
 * getRule with "timestamp" and time should return a TimestampEqualsRule.
 */
@Test public void test4() {
    Stack<Object> stack = new Stack<>();
    stack.push("timestamp");
    stack.push("2008-05-21 00:45:44");
    Rule rule = EqualsRule.getRule(stack);
    AssertJUnit.assertEquals(0, stack.size());
    AssertJUnit.assertTrue(rule instanceof TimestampEqualsRule);
    Calendar cal = new GregorianCalendar(2008, 4, 21, 0, 45, 44);
    LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
            Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO,
            "Hello, World", null);
    AssertJUnit.assertTrue(rule.evaluate(Log4jUtil.translateLog4j(event), null));
}
 
Example #18
Source File: BasicTest.java    From cassandra-log4j-appender with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoThrowableSuccess() throws Exception
{
    CassandraAppender appender = new CassandraAppender();
    LoggingEvent event = new LoggingEvent(BasicTest.class.getName(),
                                          Category.getInstance(BasicTest.class),
                                          Priority.WARN,
                                          "test 12",
                                          null);
    appender.doAppend(event);
}
 
Example #19
Source File: GremlinServerAuditLogIntegrateTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAuditLogWithKrb5Authenticator() throws Exception {
    final Cluster cluster = TestClientFactory.build().jaasEntry(TESTCONSOLE)
            .protocol(kdcServer.serverPrincipalName).addContactPoint(kdcServer.hostname).create();
    final Client client = cluster.connect();
    try {
        assertEquals(2, client.submit("1+1").all().get().get(0).getInt());
        assertEquals(3, client.submit("1+2").all().get().get(0).getInt());
        assertEquals(4, client.submit("1+3").all().get().get(0).getInt());
    } finally {
        cluster.close();
    }

    // wait for logger to flush - (don't think there is a way to detect this)
    stopServer();
    Thread.sleep(1000);

    final List<LoggingEvent> log = recordingAppender.getEvents();
    final Stream<LoggingEvent> auditEvents = log.stream().filter(event -> event.getLoggerName().equals(AUDIT_LOGGER_NAME));
    final LoggingEvent authEvent = auditEvents
            .filter(event -> event.getMessage().toString().contains("Krb5Authenticator")).iterator().next();
    final String authMsg = authEvent.getMessage().toString();
    assertTrue(authEvent.getLevel() == INFO &&
            authMsg.matches(String.format("User %s with address .*? authenticated by Krb5Authenticator", kdcServer.clientPrincipalName)));
    assertTrue(log.stream().anyMatch(item -> item.getLevel() == INFO &&
            item.getMessage().toString().matches("User with address .*? requested: 1\\+1")));
    assertTrue(log.stream().anyMatch(item -> item.getLevel() == INFO &&
            item.getMessage().toString().matches("User with address .*? requested: 1\\+2")));
    assertTrue(log.stream().anyMatch(item -> item.getLevel() == INFO &&
            item.getMessage().toString().matches("User with address .*? requested: 1\\+3")));
}
 
Example #20
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 #21
Source File: GelfAppender.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
    GelfMessage gelfMessage = GelfMessageFactory.makeMessage(layout, event, this);

    if (getGelfSender() == null) {
        errorHandler.error("Could not send GELF message. Gelf Sender is not initialised and equals null");
    } else {
        GelfSenderResult gelfSenderResult = getGelfSender().sendMessage(gelfMessage);
        if (!GelfSenderResult.OK.equals(gelfSenderResult)) {
            errorHandler.error("Error during sending GELF message. Error code: " + gelfSenderResult.getCode() + ".", gelfSenderResult.getException(), ErrorCode.WRITE_FAILURE);
        }
    }

}
 
Example #22
Source File: SnmpEnhancedPatternLayoutTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void ParseAlertWithKeyValueDelimeterInMessageTest() {
    LoggingEvent event = mock(LoggingEvent.class);
    setMessage(" alertType:: 14 // dataCenterId:: 1 // podId:: 1 // " + "clusterId:: null // message:: Management"
        + " ::network CIDR is not configured originally. Set it default to 10.102.192.0/22", event);
    SnmpTrapInfo info = _snmpEnhancedPatternLayout.parseEvent(event);
    commonAssertions(info, "Management ::network CIDR is not configured originally. Set it default to 10.102.192" + ".0/22");
}
 
Example #23
Source File: LoggingTester.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
  String _renderedMessage = event.getRenderedMessage();
  String _loggerName = event.getLoggerName();
  long _timeStamp = event.getTimeStamp();
  Level _level = event.getLevel();
  final LoggingTester.LogEntry entry = new LoggingTester.LogEntry(_renderedMessage, _loggerName, _timeStamp, _level);
  this.events.add(entry);
}
 
Example #24
Source File: GremlinServerAuditLogIntegrateTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAuditLogWithSimpleAuthenticator() throws Exception {
    final String username = "stephen";
    final String password = "password";

    final Cluster cluster = TestClientFactory.build().credentials(username, password)
            .addContactPoint(kdcServer.hostname).create();
    final Client client = cluster.connect();

    try {
        assertEquals(2, client.submit("1+1").all().get().get(0).getInt());
        assertEquals(3, client.submit("1+2").all().get().get(0).getInt());
        assertEquals(4, client.submit("1+3").all().get().get(0).getInt());
        assertEquals(5, client.submit("1+4").all().get().get(0).getInt());
    } finally {
        cluster.close();
    }

    // wait for logger to flush - (don't think there is a way to detect this)
    stopServer();
    Thread.sleep(1000);

    final String simpleAuthenticatorName = SimpleAuthenticator.class.getSimpleName();

    final List<LoggingEvent> log = recordingAppender.getEvents();
    final Stream<LoggingEvent> auditEvents = log.stream().filter(event -> event.getLoggerName().equals(AUDIT_LOGGER_NAME));
    final LoggingEvent authEvent = auditEvents
            .filter(event -> event.getMessage().toString().contains(simpleAuthenticatorName)).iterator().next();
    final String authMsg = authEvent.getMessage().toString();
    assertTrue(authEvent.getLevel() == INFO &&
            authMsg.matches(String.format("User %s with address .*? authenticated by %s", username, simpleAuthenticatorName)));
    assertTrue(log.stream().anyMatch(item -> item.getLevel() == INFO &&
            item.getMessage().toString().matches("User with address .*? requested: 1\\+1")));
    assertTrue(log.stream().anyMatch(item -> item.getLevel() == INFO &&
            item.getMessage().toString().matches("User with address .*? requested: 1\\+2")));
    assertTrue(log.stream().anyMatch(item -> item.getLevel() == INFO &&
            item.getMessage().toString().matches("User with address .*? requested: 1\\+3")));
}
 
Example #25
Source File: JdbmStoreAndForwardAppender.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
protected void append( LoggingEvent event ) {
  try {
    if( fetchLocationInfo ) {
      event.getLocationInformation();
    }
    queue.enqueue( event );
  } catch ( IOException e ) {
    throw new RuntimeException( e );
  }
}
 
Example #26
Source File: Log4jPipedAppenderTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void doAppend() throws IOException {
  PipedOutputStream pipedOutputStream = mock( PipedOutputStream.class );
  LoggingEvent loggingEvent = mock( LoggingEvent.class );
  Layout testLayout = mock( Layout.class );
  when( testLayout.format( loggingEvent ) ).thenReturn( "LOG_TEST_LINE" );
  log4jPipedAppender.setLayout( testLayout );
  log4jPipedAppender.setPipedOutputStream( pipedOutputStream );
  log4jPipedAppender.doAppend( loggingEvent );
  verify( pipedOutputStream ).write( ( "LOG_TEST_LINE" + Const.CR ).getBytes() );
}
 
Example #27
Source File: InputSocket.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
  logger.info("Starting socket server (port: {}, protocol: {}, secure: {})", port, protocol, secure);
  ServerSocketFactory socketFactory = secure ? SSLServerSocketFactory.getDefault() : ServerSocketFactory.getDefault();
  InputSocketMarker inputSocketMarker = new InputSocketMarker(this, port, protocol, secure, log4j);
  LogsearchConversion loggerConverter = new LogsearchConversion();

  try {
    serverSocket = socketFactory.createServerSocket(port);
    while (!isDrain()) {
      Socket socket = serverSocket.accept();
      if (log4j) {
        try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()))) {
          LoggingEvent loggingEvent = (LoggingEvent) ois.readObject();
          String jsonStr = loggerConverter.createOutput(loggingEvent);
          logger.trace("Incoming socket logging event: " + jsonStr);
          outputLine(jsonStr, inputSocketMarker);
        }
      } else {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
          String line = in.readLine();
          logger.trace("Incoming socket message: " + line);
          outputLine(line, inputSocketMarker);
        }
      }
    }
  } catch (SocketException socketEx) {
    logger.warn("{}", socketEx.getMessage());
  } finally {
    serverSocket.close();
  }
}
 
Example #28
Source File: BoundedFIFO.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    Place a {@link LoggingEvent} in the buffer. If the buffer is full
    then the event is <b>silently dropped</b>. It is the caller's
    responsability to make sure that the buffer has free space.  */
 public 
 void put(LoggingEvent o) {
   if(numElements != maxSize) {      
     buf[next] = o;    
     if(++next == maxSize) {
next = 0;
     }
     numElements++;
   }
 }
 
Example #29
Source File: InfoOnlyLogLayout.java    From systemsgenetics with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
	if (event.getLevel() == Level.INFO) {
		sbuf.setLength(0);
		sbuf.append(event.getRenderedMessage());
		sbuf.append(LINE_SEP);
		return sbuf.toString();
	} else {
		return "";
	}
}
 
Example #30
Source File: Log4jFileAppender.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public void doAppend( LoggingEvent event ) {
  String line = layout.format( event ) + Const.CR;
  try {
    fileOutputStream.write( line.getBytes( Const.XML_ENCODING ) );
  } catch ( IOException e ) {
    System.out.println( "Unable to close Logging file [" + file.getName() + "] : " + e.getMessage() );
  }
}