Java Code Examples for org.apache.log4j.spi.LoggingEvent

The following are top voted examples for showing how to use org.apache.log4j.spi.LoggingEvent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-servicecomb-java-chassis   File: TestServiceRegistryClientImpl.java   Source Code and License 7 votes vote down vote up
void run() {
  Logger rootLogger = Logger.getRootLogger();

  List<LoggingEvent> events = new ArrayList<>();
  Appender appender = new MockUp<Appender>() {
    @Mock
    public void doAppend(LoggingEvent event) {
      events.add(event);
    }
  }.getMockInstance();
  rootLogger.addAppender(appender);

  doRun(events);

  rootLogger.removeAppender(appender);
}
 
Example 2
Project: incubator-servicecomb-java-chassis   File: TestServiceRegistryClientImpl.java   Source Code and License 6 votes vote down vote up
@Test
public void testRegisterSchemaException() {
  InterruptedException e = new InterruptedException();
  new MockUp<CountDownLatch>() {
    @Mock
    public void await() throws InterruptedException {
      throw e;
    }
  };

  new RegisterSchemaTester() {
    void doRun(java.util.List<LoggingEvent> events) {
      oClient.registerSchema("msid", "schemaId", "content");
      Assert.assertEquals(
          "register schema msid/schemaId fail.",
          events.get(0).getMessage());
      Assert.assertEquals(e, events.get(0).getThrowableInformation().getThrowable());
    }
  }.run();
}
 
Example 3
Project: sstore-soft   File: ColoredPatternLayout.java   Source Code and License 6 votes vote down vote up
public String format(LoggingEvent event){
    if( event.getLevel() == Level.FATAL){
        return fatalErrorColor+super.format(event)+END_COLOR;
    }else if( event.getLevel() == Level.ERROR){
        return errorColor+super.format(event)+END_COLOR;
    }if( event.getLevel() == Level.WARN){
        return super.format(event);
//        return warnColor+super.format(event)+END_COLOR;
    }if( event.getLevel() == Level.INFO){
        return super.format(event);
//        return infoColor+super.format(event)+END_COLOR;
    }if( event.getLevel() == Level.DEBUG){
        return super.format(event);
//        return debugColor+super.format(event)+END_COLOR;
    }else{
        throw new RuntimeException("Unsupported Level "+event.toString());
    }
    }
 
Example 4
Project: jaffa-framework   File: MDCFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void decide() {

	assertNotNull(mdcFilter);

	mdcFilter.setExpression("MessageId!=null || LoggedBy!=null");
	mdcFilter.setKeys("LoggedBy,MessageId");

	final LoggingEvent event = new LoggingEvent("", LOG, LOG.getLevel(),
			"MessageId=123", null);

	MDC.put("LoggedBy", "abc");
	MDC.put("fff", "abc");

	final int ret = mdcFilter.decide(event);
	LOG.info("decide: " + ret);
	assertTrue(ret == Filter.NEUTRAL);
}
 
Example 5
Project: hadoop-oss   File: EventCounter.java   Source Code and License 6 votes vote down vote up
@Override
public void append(LoggingEvent event) {
  Level level = event.getLevel();
  // depends on the api, == might not work
  // see HADOOP-7055 for details
  if (level.equals(Level.INFO)) {
    counts.incr(INFO);
  }
  else if (level.equals(Level.WARN)) {
    counts.incr(WARN);
  }
  else if (level.equals(Level.ERROR)) {
    counts.incr(ERROR);
  }
  else if (level.equals(Level.FATAL)) {
    counts.incr(FATAL);
  }
}
 
Example 6
Project: jwala   File: JGroupsReportingLifeCycleListenerImplTest.java   Source Code and License 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 7
Project: hadoop   File: FairSchedulerEventLog.java   Source Code and License 6 votes vote down vote up
/**
 * Log an event, writing a line in the log file of the form
 * <pre>
 * DATE    EVENT_TYPE   PARAM_1   PARAM_2   ...
 * </pre>
 */
synchronized void log(String eventType, Object... params) {
  try {
    if (logDisabled)
      return;
    StringBuffer buffer = new StringBuffer();
    buffer.append(eventType);
    for (Object param: params) {
      buffer.append("\t");
      buffer.append(param);
    }
    String message = buffer.toString();
    Logger logger = Logger.getLogger(getClass());
    appender.append(new LoggingEvent("", logger, Level.INFO, message, null));
  } catch (Exception e) {
    LOG.error("Failed to append to fair scheduler event log", e);
    logDisabled = true;
  }
}
 
Example 8
Project: SkyEye   File: KafkaAppender.java   Source Code and License 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 9
Project: jaffa-framework   File: MDCFilter.java   Source Code and License 6 votes vote down vote up
/**
 * Returns Filter#DENY if Expression returns false based on the values
 * returned from the MDC Context.
 * 
 * @param event
 *          <code>LoggingEvent</code>
 */
public int decide(final LoggingEvent event) {

	int ret = DENY;

	if (keys != null && expression != null) {
		final List<Object> mdcValues = new ArrayList<Object>();
		final List<Class<String>> keyTypes = new ArrayList<Class<String>>();
		final String[] keyValues = keys.split(SPLIT_EXPRESSION);
		if (keyValues != null) {
			for (final String keyValue : keyValues) {
				final Object mdcValue = MDC.get(keyValue);
				keyTypes.add((Class<String>) keyValue.getClass());
				mdcValues.add(mdcValue);
			}
		}
		ret = evaluate(getExpressionEvaluator(keyTypes, keyValues), mdcValues);
	}

	return ret;
}
 
Example 10
Project: ats-framework   File: DbEventRequestProcessor.java   Source Code and License 6 votes vote down vote up
private String getLoggingMesage( LoggingEvent event ) {

        Throwable throwable = null;
        ThrowableInformation throwableInfo = event.getThrowableInformation();
        if (throwableInfo != null && throwableInfo.getThrowable() != null) {
            // logging through methods like error(new Exception);
            throwable = throwableInfo.getThrowable();
        } else if (event.getMessage() instanceof Throwable) {
            // logging through methods like error("some message", new Exception);
            throwable = (Throwable) event.getMessage();
        }

        // first format the message using the layout
        String message = layout.format(event);
        // then append the exception stack trace
        if (throwable != null) {
            message = getExceptionMsg(throwable, message);
        }

        return message;

    }
 
Example 11
Project: log4j-aws-appenders   File: AbstractAppender.java   Source Code and License 6 votes vote down vote up
@Override
protected void append(LoggingEvent event)
{
    if (closed)
    {
        throw new IllegalStateException("appender is closed");
    }

    if (! ready)
    {
        initialize();
    }

    try
    {
        internalAppend(new LogMessage(event, getLayout()));
    }
    catch (Exception ex)
    {
        LogLog.warn("unable to append event", ex);
    }
}
 
Example 12
Project: log4j-aws-appenders   File: TestLogMessage.java   Source Code and License 6 votes vote down vote up
@Test
public void testAsciiMessageFromEventDefaultLayout() throws Exception
{
    final long timestamp = System.currentTimeMillis();
    final String text = "test";

    LoggingEvent event = createLoggingEvent(timestamp, text, null);
    LogMessage message = new LogMessage(event, new PatternLayout());

    // the default pattern appends a newline
    String expectedText = text + "\n";

    assertEquals("timestmap",               timestamp,                      message.getTimestamp());
    assertEquals("message",                 expectedText,                   message.getMessage());
    assertArrayEquals("message as bytes",   expectedText.getBytes("UTF-8"), message.getBytes());
    assertEquals("size",                    5,                              message.size());
}
 
Example 13
Project: log4j-aws-appenders   File: TestLogMessage.java   Source Code and License 6 votes vote down vote up
@Test
public void testUnicodeMessageFromEventDefaultLayout() throws Exception
{
    final long timestamp = System.currentTimeMillis();
    final String text = "\u0024\u00a2\u20ac";

    LoggingEvent event = createLoggingEvent(timestamp, text, null);
    LogMessage message = new LogMessage(event, new PatternLayout());

    // the default pattern appends a newline
    String expectedText = text + "\n";

    assertEquals("timestmap",               timestamp,                      message.getTimestamp());
    assertEquals("message",                 expectedText,                   message.getMessage());
    assertArrayEquals("message as bytes",   expectedText.getBytes("UTF-8"), message.getBytes());
    assertEquals("size",                    7,                              message.size());
}
 
Example 14
Project: log4j-aws-appenders   File: TestLogMessage.java   Source Code and License 6 votes vote down vote up
@Test
// at this point we'll assume that UTF-8 conversion works as expected
public void testAsciiMessageFromEventDefaultLayoutWithException() throws Exception
{
    final long timestamp = System.currentTimeMillis();
    final String text = "test";
    final Exception ex = new Exception();

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    pw.println(text);
    ex.printStackTrace(pw);
    pw.close();
    String expectedText = sw.toString();

    LoggingEvent event = createLoggingEvent(timestamp, text, ex);
    LogMessage message = new LogMessage(event, new PatternLayout());

    assertEquals("explicit timestamp",  timestamp,      message.getTimestamp());
    assertEquals("message as string",   expectedText,   message.getMessage());
}
 
Example 15
Project: jaffa-framework   File: JDBCLogger.java   Source Code and License 6 votes vote down vote up
/**
 * Extracts Stack trace of Throwable contained in LogginEvent, if there is
 * any
 * 
 * @param aLoggingEvent
 *            logging event
 * @return stack trace of throwable
 */
public String getThrowableRepresentationFromLoggingEvent(LoggingEvent aLoggingEvent) {
	// extract throwable information from loggingEvent if available
	ThrowableInformation throwableinfo = aLoggingEvent.getThrowableInformation();
	StringBuffer throwableStringBuffer = new StringBuffer();

	if (throwableinfo != null) {
		String[] lines = throwableinfo.getThrowableStrRep();
		for (int index = 0; index < lines.length; index++) {
			throwableStringBuffer = (StringBuffer) throwableStringBuffer.append(lines[index]
					+ "\r\n");
		}
	}
	String result = quotedString(throwableStringBuffer.toString());
	if (this.getThrowableMaxChars() != -1 && result.length() > this.getThrowableMaxChars()) {
		result = result.substring(0, this.getThrowableMaxChars() - 1);
	}

	return result;
}
 
Example 16
Project: cf-mta-deploy-service   File: DBAppender.java   Source Code and License 6 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
    try {
        Connection connection = dataSource.getConnection();
        try {
            PreparedStatement stmt = connection.prepareStatement(sql);
            try {
                eventAdapter.eventToStatement(getName(), event, userInfoProvider.getUserInfo(), stmt);
                stmt.executeUpdate();
            } finally {
                stmt.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        exceptionHandler.handleException(e);
    }
}
 
Example 17
Project: s-store   File: RingBufferAppender.java   Source Code and License 6 votes vote down vote up
@Override
    protected void append(LoggingEvent event) {
        if (this.useFastLocation) {
            if (this.stackOffset < 0) this.stackOffset = FastLoggingEvent.getStackOffset(event);
            event = new FastLoggingEvent(event, this.stackOffset); 
        }
        if (this.storeLocation) event.getLocationInformation();
        if (this.storeThreadName) event.getThreadName();
        
        int position = -1;
        synchronized (this) {
            this.currentPosition = position = ++this.currentPosition % this.eventRing.length;
            this.counter++;
        } // SYNCH
        this.eventRing[position] = event;
//        assert(event.getLoggerName().contains("Handler") == false) : event;
    }
 
Example 18
Project: hadoop   File: EventCounter.java   Source Code and License 6 votes vote down vote up
@Override
public void append(LoggingEvent event) {
  Level level = event.getLevel();
  // depends on the api, == might not work
  // see HADOOP-7055 for details
  if (level.equals(Level.INFO)) {
    counts.incr(INFO);
  }
  else if (level.equals(Level.WARN)) {
    counts.incr(WARN);
  }
  else if (level.equals(Level.ERROR)) {
    counts.incr(ERROR);
  }
  else if (level.equals(Level.FATAL)) {
    counts.incr(FATAL);
  }
}
 
Example 19
Project: s-store   File: RingBufferAppender.java   Source Code and License 6 votes vote down vote up
public static Collection<String> getLoggingMessages(RingBufferAppender...appenders) {
    List<LoggingEvent> events = new ArrayList<LoggingEvent>();
    Layout layout = null; 
    for (RingBufferAppender rba : appenders) {
        LoggingEvent e[] = rba.getLogEvents();
        if (LOG.isDebugEnabled())
            LOG.debug("Got " + e.length + " LoggingEvents for " + rba);
        CollectionUtil.addAll(events, e);
        if (layout == null) layout = rba.getLayout();
    } // FOR
    if (events.isEmpty() == false) assert(layout != null);
    
    Collections.sort(events, new Comparator<LoggingEvent>() {
        @Override
        public int compare(LoggingEvent o1, LoggingEvent o2) {
            return (int)(o1.timeStamp - o2.timeStamp);
        }
    });
    List<String> messages = new ArrayList<String>();
    for (LoggingEvent event : events) {
        messages.add(layout.format(event));
    } // FOR
    return (messages);
}
 
Example 20
Project: Equella   File: HTMLLayout3.java   Source Code and License 6 votes vote down vote up
protected void appendLevelText(LoggingEvent event, StringBuilder sbuf)
{
	if( event.getLevel().equals(Level.DEBUG) )
	{
		sbuf.append("<font color=\"#339933\">");
		sbuf.append(event.getLevel());
		sbuf.append("</font>");
	}
	else if( event.getLevel().isGreaterOrEqual(Level.WARN) )
	{
		sbuf.append("<font color=\"#993300\"><strong>");
		sbuf.append(event.getLevel());
		sbuf.append("</strong></font>");
	}
	else
	{
		sbuf.append(event.getLevel());
	}
}
 
Example 21
Project: Equella   File: DailySizeRollingAppender.java   Source Code and License 6 votes vote down vote up
@Override
protected void subAppend(LoggingEvent event)
{
	LogLog.debug("subAppend");
	long now = System.currentTimeMillis();
	if( now >= nextRollTime )
	{
		LogLog.debug("Have to roll directory");
		calculateRollOverTime();
		rollDirectory();
	}
	else if( getFile() != null && ((CountingQuietWriter) qw).getCount() >= maxFileSize )
	{
		LogLog.debug("Have to roll file");
		rollFile();
	}
	LogLog.debug("Calling Super Sub Append");
	super.subAppend(event);
}
 
Example 22
Project: dubbocloud   File: DubboAppender.java   Source Code and License 5 votes vote down vote up
public void append(LoggingEvent event) {
    super.append(event);
    if (available == true) {
        Log temp = parseLog(event);
        logList.add(temp);
    }
}
 
Example 23
Project: dubbocloud   File: DubboAppender.java   Source Code and License 5 votes vote down vote up
private Log parseLog(LoggingEvent event) {
    Log log = new Log();
    log.setLogName(event.getLogger().getName());
    log.setLogLevel(event.getLevel());
    log.setLogThread(event.getThreadName());
    log.setLogMessage(event.getMessage().toString());
    return log;
}
 
Example 24
Project: SkyEye   File: KafkaAppender.java   Source Code and License 5 votes vote down vote up
/**
 * 获得message
 * @param event
 * @return
 */
private String getMessage(LoggingEvent event) {
    if (this.layout == null) {
        return event.getRenderedMessage();
    } else {
        // 获取host和app
        String msg = System.nanoTime() + Constants.SEMICOLON + this.layout.format(event);
        return msg.replaceFirst(Constants.APP_NAME, this.app).replaceFirst(Constants.HOSTNAME, this.host);
    }
}
 
Example 25
Project: openrasp   File: EventCache.java   Source Code and License 5 votes vote down vote up
public boolean addEvent(LoggingEvent event) {
    synchronized (list) {
        list.add(event);
        if (list.size() >= size) {
            return true;
        }
        return false;
    }
}
 
Example 26
Project: aws-sdk-java-v2   File: DefaultErrorResponseHandlerTest.java   Source Code and License 5 votes vote down vote up
private List<LoggingEvent> infoEvents() {
    List<LoggingEvent> info = new ArrayList<LoggingEvent>();
    List<LoggingEvent> loggingEvents = logCaptor.loggedEvents();
    for (LoggingEvent le : loggingEvents) {
        if (le.getLevel().equals(Level.INFO)) {
            info.add(le);
        }
    }
    return info;
}
 
Example 27
Project: wngn-jms-kafka   File: KafkaLog4jAppender.java   Source Code and License 5 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
    String message = subAppend(event);
    LogLog.debug("[" + new Date(event.getTimeStamp()) + "]" + message);
    Future<RecordMetadata> response = producer.send(
        new ProducerRecord<byte[], byte[]>(topic, message.getBytes(StandardCharsets.UTF_8)));
    if (syncSend) {
        try {
            response.get();
        } catch (InterruptedException | ExecutionException ex) {
            throw new RuntimeException(ex);
        }
    }
}
 
Example 28
Project: incubator-servicecomb-java-chassis   File: TestRollingFileAppenderExt.java   Source Code and License 5 votes vote down vote up
@Test
public void testRollingFileAppenderExt(@Injectable LoggingEvent event,
    @Injectable Layout layout) throws Exception {
  new Expectations() {
    {
      layout.format(event);
      result = "test";
    }
  };
  File cur = new File(System.getProperty("user.dir"));
  File temp = new File(cur, "temptestfile.log");
  if (temp.exists()) {
    temp.delete();
  }
  RollingFileAppenderExt ext = new RollingFileAppenderExt();
  ext.setLayout(layout);
  ext.setLogPermission("rw-------");
  ext.setFile(temp.getAbsolutePath());
  ext.setFile(temp.getAbsolutePath(), false, false, 300000);
  Assert.assertEquals(ext.getLogPermission(), "rw-------");
  Assert.assertTrue(temp.exists());

  temp.delete();
  ext.subAppend(event);
  Assert.assertTrue(temp.exists());

  ext.close();
  temp.delete();
  Assert.assertFalse(temp.exists());
}
 
Example 29
Project: incubator-servicecomb-java-chassis   File: TestServiceRegistryClientImpl.java   Source Code and License 5 votes vote down vote up
@Test
public void testRegisterSchemaNoResponse() {
  new RegisterSchemaTester() {
    void doRun(java.util.List<LoggingEvent> events) {
      oClient.registerSchema("msid", "schemaId", "content");
      Assert.assertEquals("Register schema msid/schemaId failed.", events.get(0).getMessage());
    }
  }.run();
}
 
Example 30
Project: incubator-servicecomb-java-chassis   File: TestServiceRegistryClientImpl.java   Source Code and License 5 votes vote down vote up
@Test
public void testRegisterSchemaErrorResponse() {
  new MockUp<ServiceRegistryClientImpl>() {
    @Mock
    Handler<RestResponse> syncHandlerEx(CountDownLatch countDownLatch, Holder<ResponseWrapper> holder) {
      return restResponse -> {
        HttpClientResponse response = Mockito.mock(HttpClientResponse.class);
        Mockito.when(response.statusCode()).thenReturn(400);
        Mockito.when(response.statusMessage()).thenReturn("client error");

        Buffer bodyBuffer = Buffer.buffer();
        bodyBuffer.appendString("too big");

        ResponseWrapper responseWrapper = new ResponseWrapper();
        responseWrapper.response = response;
        responseWrapper.bodyBuffer = bodyBuffer;
        holder.value = responseWrapper;
      };
    }
  };
  new MockUp<RestUtils>() {
    @Mock
    void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
      responseHandler.handle(null);
    }
  };

  new RegisterSchemaTester() {
    void doRun(java.util.List<LoggingEvent> events) {
      oClient.registerSchema("msid", "schemaId", "content");
      Assert.assertEquals(
          "Register schema msid/schemaId failed, statusCode: 400, statusMessage: client error, description: too big.",
          events.get(0).getMessage());
    }
  }.run();
}
 
Example 31
Project: incubator-servicecomb-java-chassis   File: TestServiceRegistryClientImpl.java   Source Code and License 5 votes vote down vote up
@Test
public void testRegisterSchemaSuccess() {
  new MockUp<ServiceRegistryClientImpl>() {
    @Mock
    Handler<RestResponse> syncHandlerEx(CountDownLatch countDownLatch, Holder<ResponseWrapper> holder) {
      return restResponse -> {
        HttpClientResponse response = Mockito.mock(HttpClientResponse.class);
        Mockito.when(response.statusCode()).thenReturn(200);

        ResponseWrapper responseWrapper = new ResponseWrapper();
        responseWrapper.response = response;
        holder.value = responseWrapper;
      };
    }
  };
  new MockUp<RestUtils>() {
    @Mock
    void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
      responseHandler.handle(null);
    }
  };

  new RegisterSchemaTester() {
    void doRun(java.util.List<LoggingEvent> events) {
      oClient.registerSchema("msid", "schemaId", "content");
      Assert.assertEquals(
          "register schema msid/schemaId success.",
          events.get(0).getMessage());
    }
  }.run();
}
 
Example 32
Project: incubator-servicecomb-java-chassis   File: Log4JMetricsFileWriter.java   Source Code and License 5 votes vote down vote up
@Override
public void write(String loggerName, String filePrefix, String content) {
  RollingFileAppender logger = fileAppenders.computeIfAbsent(loggerName, f -> initLogger(loggerName, filePrefix));
  LoggingEvent event = new LoggingEvent(loggerName, Logger.getLogger(loggerName), Level.ALL,
      content, null);
  logger.append(event);
}
 
Example 33
Project: kafka-0.11.0.0-src-with-comment   File: MockKafkaLog4jAppender.java   Source Code and License 5 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
    if (super.getProducer() == null) {
        activateOptions();
    }
    super.append(event);
}
 
Example 34
Project: sstore-soft   File: FastLoggingEvent.java   Source Code and License 5 votes vote down vote up
public FastLoggingEvent(LoggingEvent event, int stackOffset) {
    super(event.getFQNOfLoggerClass(),
          event.getLogger(),
          event.getLevel(),
          event.getMessage(),
          (event.getThrowableInformation() != null ? event.getThrowableInformation().getThrowable() : null));
    this.event = event;
    this.stackOffset = stackOffset;
}
 
Example 35
Project: sstore-soft   File: FastLoggingEvent.java   Source Code and License 5 votes vote down vote up
public static int getStackOffset(LoggingEvent event) {
    Throwable t = new Throwable();
    String fqnOfCallingClass = event.getFQNOfLoggerClass();
    if (fqnOfCallingClass == null) return 0;

    // HACK
    StackTraceElement stack[] = t.getStackTrace();
    int offset = stack.length - 1;
    for (; offset >= 0; offset--) {
        if (stack[offset].getClassName().equals(fqnOfCallingClass)) break;
    } // FOR
    return (offset + 2);
}
 
Example 36
Project: sstore-soft   File: RingBufferAppender.java   Source Code and License 5 votes vote down vote up
private void init(int size) {
    this.eventRing = new LoggingEvent[size];
    this.currentPosition = -1;
    this.counter = 0;
    if (LOG.isDebugEnabled())
        LOG.debug(String.format("Initialized appender with new buffer [size=%d, useFastLocation=%s, storeLocation=%s, storeThreadName=%s, layout=%s]",
                                size, this.useFastLocation, this.storeLocation, this.storeThreadName,
                                (this.getLayout() != null ? this.getLayout().getClass().getSimpleName() : null)));
}
 
Example 37
Project: hadoop   File: TestTaskLogAppender.java   Source Code and License 5 votes vote down vote up
/**
* test TaskLogAppender 
*/
 @SuppressWarnings("deprecation")
 @Test (timeout=5000)
 public void testTaskLogAppender(){
   TaskLogAppender appender= new TaskLogAppender();
   
   System.setProperty(TaskLogAppender.TASKID_PROPERTY,"attempt_01_02_m03_04_001");
   System.setProperty(TaskLogAppender.LOGSIZE_PROPERTY, "1003");
   appender.activateOptions();
   assertEquals(appender.getTaskId(), "attempt_01_02_m03_04_001");
   assertEquals(appender.getTotalLogFileSize(),1000);
   assertEquals(appender.getIsCleanup(),false);
   
   // test writer   
   Writer writer= new StringWriter();
   appender.setWriter(writer);
   Layout layout =  new PatternLayout("%-5p [%t]: %m%n");
   appender.setLayout(layout);
   Category logger= Logger.getLogger(getClass().getName());
   LoggingEvent event = new LoggingEvent("fqnOfCategoryClass", logger, Priority.INFO, "message", new Throwable());
   appender.append(event);
   appender.flush() ;
   appender.close();
   assertTrue(writer.toString().length()>0);
   
   // test cleanup should not changed 
   appender= new TaskLogAppender();
   appender.setIsCleanup(true);
   appender.activateOptions();
   assertEquals(appender.getIsCleanup(),true);

 
 }
 
Example 38
Project: sstore-soft   File: RingBufferAppender.java   Source Code and License 5 votes vote down vote up
public static Collection<LoggingEvent> getLoggingEvents(Logger...loggers) {
    SortedSet<LoggingEvent> events = new TreeSet<LoggingEvent>(new Comparator<LoggingEvent>() {
        @Override
        public int compare(LoggingEvent o1, LoggingEvent o2) {
            return (int)(o1.timeStamp - o2.timeStamp);
        }
    });
    for (Logger log : loggers) {
        RingBufferAppender rba = getRingBufferAppender(log);
        if (rba != null) {
            CollectionUtil.addAll(events, rba.getLogEvents());
        }
    } // FOR
    return (events);
}
 
Example 39
Project: sstore-soft   File: TestFastLoggingEvent.java   Source Code and License 5 votes vote down vote up
@Override
        protected void append(LoggingEvent event) {
//            System.err.println("Got event: " + event);
            
            TestFastLoggingEvent.this.offset = FastLoggingEvent.getStackOffset(event);
            TestFastLoggingEvent.this.origEvent = event;
            TestFastLoggingEvent.this.origEvent.getLocationInformation();
            TestFastLoggingEvent.this.fastEvent = new FastLoggingEvent(event, TestFastLoggingEvent.this.offset);
            TestFastLoggingEvent.this.fastEvent.getLocationInformation();
        }
 
Example 40
Project: hadoop-oss   File: Log4Json.java   Source Code and License 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
  try {
    return toJson(event);
  } catch (IOException e) {
    //this really should not happen, and rather than throw an exception
    //which may hide the real problem, the log class is printed
    //in JSON format. The classname is used to ensure valid JSON is 
    //returned without playing escaping games
    return "{ \"logfailure\":\"" + e.getClass().toString() + "\"}";
  }
}