Java 类org.apache.logging.log4j.ThreadContext.ContextStack 实例源码

项目:stackify-log-log4j2    文件:LogEventAdapterTest.java   
/**
 * testGetPropertiesWithNdc
 */
@Test
public void testGetPropertiesWithNdc() {
    ContextStack contextStack = Mockito.mock(ContextStack.class);
    Mockito.when(contextStack.peek()).thenReturn("ndcContext");

    LogEvent event = Mockito.mock(LogEvent.class);
    Mockito.when(event.getContextStack()).thenReturn(contextStack);

    LogEventAdapter adapter = new LogEventAdapter(Mockito.mock(EnvironmentDetail.class));
    Map<String, String> properties = adapter.getProperties(event);

    Assert.assertNotNull(properties);
    Assert.assertEquals(1, properties.size());
    Assert.assertEquals("ndcContext", properties.get("NDC"));
}
项目:stackify-log-log4j2    文件:LogEventAdapterTest.java   
/**
 * testGetPropertiesWithMdcAndNdc
 */
@Test
public void testGetPropertiesWithMdcAndNdc() {
    Map<String, String> mdcProperties = new HashMap<String, String>();
    mdcProperties.put("mdc1", "val1");
    mdcProperties.put("mdc2", "val2");

    ContextStack contextStack = Mockito.mock(ContextStack.class);
    Mockito.when(contextStack.peek()).thenReturn("ndcContext");

    LogEvent event = Mockito.mock(LogEvent.class);
    Mockito.when(event.getContextMap()).thenReturn(mdcProperties);
    Mockito.when(event.getContextStack()).thenReturn(contextStack);

    LogEventAdapter adapter = new LogEventAdapter(Mockito.mock(EnvironmentDetail.class));
    Map<String, String> properties = adapter.getProperties(event);

    Assert.assertNotNull(properties);
    Assert.assertEquals(3, properties.size());
    Assert.assertEquals("val1", properties.get("mdc1"));
    Assert.assertEquals("val2", properties.get("mdc2"));
    Assert.assertEquals("ndcContext", properties.get("NDC"));
}
项目:log4j2    文件:RingBufferLogEventTranslator.java   
public void setValues(final AsyncLogger asyncLogger, final String loggerName,
        final Marker marker, final String fqcn, final Level level, final Message message,
        final Throwable thrown, final Map<String, String> contextMap,
        final ContextStack contextStack, final String threadName,
        final StackTraceElement location, final long currentTimeMillis) {
    this.asyncLogger = asyncLogger;
    this.loggerName = loggerName;
    this.marker = marker;
    this.fqcn = fqcn;
    this.level = level;
    this.message = message;
    this.thrown = thrown;
    this.contextMap = contextMap;
    this.contextStack = contextStack;
    this.threadName = threadName;
    this.location = location;
    this.currentTimeMillis = currentTimeMillis;
}
项目:log4j2    文件:RingBufferLogEvent.java   
public void setValues(final AsyncLogger asyncLogger,
        final String loggerName, final Marker marker, final String fqcn,
        final Level level, final Message data, final Throwable t,
        final Map<String, String> map, final ContextStack contextStack,
        final String threadName, final StackTraceElement location,
        final long currentTimeMillis) {
    this.asyncLogger = asyncLogger;
    this.loggerName = loggerName;
    this.marker = marker;
    this.fqcn = fqcn;
    this.level = level;
    this.message = data;
    this.thrown = t;
    this.contextMap = map;
    this.contextStack = contextStack;
    this.threadName = threadName;
    this.location = location;
    this.currentTimeMillis = currentTimeMillis;
}
项目:logging-log4j2    文件:PatternLayoutBenchmark.java   
private static LogEvent createLogEvent() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(STR);
    final Throwable t = null;
    final StringMap mdc = null;
    final ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
项目:logging-log4j2    文件:PatternLayoutComparisonBenchmark.java   
private static LogEvent createLog4j2Event() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(STR);
    final Throwable t = null;
    final StringMap mdc = null;
    final ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
项目:logging-log4j2    文件:TextEncoderHelperBenchmark.java   
private static LogEvent createLogEvent() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(STR);
    final Throwable t = null;
    final StringMap mdc = null;
    final ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
项目:logging-log4j2    文件:RingBufferLogEventTranslator.java   
public void setBasicValues(final AsyncLogger anAsyncLogger, final String aLoggerName, final Marker aMarker,
                           final String theFqcn, final Level aLevel, final Message msg, final Throwable aThrowable,
                           final ContextStack aContextStack, final StackTraceElement aLocation,
                           final Clock aClock, final NanoClock aNanoClock) {
    this.asyncLogger = anAsyncLogger;
    this.loggerName = aLoggerName;
    this.marker = aMarker;
    this.fqcn = theFqcn;
    this.level = aLevel;
    this.message = msg;
    this.thrown = aThrowable;
    this.contextStack = aContextStack;
    this.location = aLocation;
    this.clock = aClock;
    this.nanoClock = aNanoClock;
}
项目:logging-log4j2    文件:RingBufferLogEvent.java   
public void setValues(final AsyncLogger anAsyncLogger, final String aLoggerName, final Marker aMarker,
                      final String theFqcn, final Level aLevel, final Message msg, final Throwable aThrowable,
                      final StringMap mutableContextData, final ContextStack aContextStack, final long threadId,
                      final String threadName, final int threadPriority, final StackTraceElement aLocation,
                      final Clock clock, final NanoClock nanoClock) {
    this.threadPriority = threadPriority;
    this.threadId = threadId;
    this.level = aLevel;
    this.threadName = threadName;
    this.loggerName = aLoggerName;
    setMessage(msg);
    initTime(clock);
    this.nanoTime = nanoClock.nanoTime();
    this.thrown = aThrowable;
    this.thrownProxy = null;
    this.marker = aMarker;
    this.fqcn = theFqcn;
    this.location = aLocation;
    this.contextData = mutableContextData;
    this.contextStack = aContextStack;
    this.asyncLogger = anAsyncLogger;
}
项目:logging-log4j2    文件:AsyncLogger.java   
@Override
public void translateTo(final RingBufferLogEvent event, final long sequence, final Object... args) {
    // Implementation note: candidate for optimization: exceeds 35 bytecodes.
    final AsyncLogger asyncLogger = (AsyncLogger) args[0];
    final StackTraceElement location = (StackTraceElement) args[1];
    final String fqcn = (String) args[2];
    final Level level = (Level) args[3];
    final Marker marker = (Marker) args[4];
    final Message message = (Message) args[5];
    final Throwable thrown = (Throwable) args[6];

    // needs shallow copy to be fast (LOG4J2-154)
    final ContextStack contextStack = ThreadContext.getImmutableStack();

    final Thread currentThread = Thread.currentThread();
    final String threadName = THREAD_NAME_CACHING_STRATEGY.getThreadName();
    event.setValues(asyncLogger, asyncLogger.getName(), marker, fqcn, level, message, thrown,
            // config properties are taken care of in the EventHandler thread
            // in the AsyncLogger#actualAsyncLog method
            CONTEXT_DATA_INJECTOR.injectContextData(null, (StringMap) event.getContextData()),
            contextStack, currentThread.getId(), threadName, currentThread.getPriority(), location,
            CLOCK, nanoClock);
}
项目:logging-log4j2    文件:RingBufferLogEventTest.java   
@Test
public void testGetLevelReturnsOffIfNullLevelSet() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = null;
    final Marker marker = null;
    final String fqcn = null;
    final Level level = null;
    final Message data = null;
    final Throwable t = null;
    final ContextStack contextStack = null;
    final String threadName = null;
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location, new FixedPreciseClock(), new DummyNanoClock(1));
    assertEquals(Level.OFF, evt.getLevel());
}
项目:logging-log4j2    文件:RingBufferLogEventTest.java   
@Test
public void testGetMessageReturnsNonNullMessage() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = null;
    final Marker marker = null;
    final String fqcn = null;
    final Level level = null;
    final Message data = null;
    final Throwable t = null;
    final ContextStack contextStack = null;
    final String threadName = null;
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location, new FixedPreciseClock(), new DummyNanoClock(1));
    assertNotNull(evt.getMessage());
}
项目:logging-log4j2    文件:RingBufferLogEventTest.java   
@Test
public void testGetMillisReturnsConstructorMillisForNormalMessage() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = null;
    final Marker marker = null;
    final String fqcn = null;
    final Level level = null;
    final Message data = null;
    final Throwable t = null;
    final ContextStack contextStack = null;
    final String threadName = null;
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location, new FixedPreciseClock(123, 456), new DummyNanoClock(1));
    assertEquals(123, evt.getTimeMillis());
    assertEquals(456, evt.getInstant().getNanoOfMillisecond());
}
项目:logging-log4j2    文件:ThreadLocalVsPoolBenchmark.java   
private static LogEvent createLog4j2Event() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final String STR = "AB!(%087936DZYXQWEIOP$#^~-=/><nb"; // length=32
    final Message message = new SimpleMessage(STR);
    final Throwable t = null;
    final StringMap mdc = null;
    final ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
项目:logging-log4j2    文件:DefaultThreadContextStackTest.java   
@Test
public void testImmutableOrNullReturnsCopyOfContents() {
    final DefaultThreadContextStack stack = createStack();
    assertTrue(!stack.isEmpty());
    final ContextStack actual = stack.getImmutableStackOrNull();
    assertNotNull(actual);
    assertEquals(stack, actual);
}
项目:logging-log4j2    文件:DefaultThreadContextStackTest.java   
@Test(expected = UnsupportedOperationException.class)
public void testModifyingImmutableOrNullThrowsException() {
    final DefaultThreadContextStack stack = createStack();
    final int originalSize = stack.size();
    assertTrue(originalSize > 0);
    final ContextStack actual = stack.getImmutableStackOrNull();
    assertEquals(originalSize, actual.size());

    actual.pop();
}
项目:logging-log4j2    文件:Initializers.java   
void initialize(final SimpleModule simpleModule, final boolean objectMessageAsJsonObject) {
    // Workaround because mix-ins do not work for classes that already have a built-in deserializer.
    // See Jackson issue 429.
    simpleModule.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    simpleModule.addDeserializer(ContextStack.class, new MutableThreadContextStackDeserializer());
    if (objectMessageAsJsonObject) {
            simpleModule.addSerializer(ObjectMessage.class, new ObjectMessageSerializer());
    }
    simpleModule.addSerializer(Message.class, new MessageSerializer());
}
项目:logging-log4j2    文件:RingBufferLogEventTest.java   
@Test
public void testSerializationDeserialization() throws IOException, ClassNotFoundException {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = "logger.name";
    final Marker marker = null;
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    final Message data = new SimpleMessage("message");
    final Throwable t = new InternalError("not a real error");
    final ContextStack contextStack = null;
    final String threadName = "main";
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location,
            new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
    ((StringMap) evt.getContextData()).putValue("key", "value");

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(evt);

    final ObjectInputStream in = new FilteredObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final RingBufferLogEvent other = (RingBufferLogEvent) in.readObject();
    assertEquals(loggerName, other.getLoggerName());
    assertEquals(marker, other.getMarker());
    assertEquals(fqcn, other.getLoggerFqcn());
    assertEquals(level, other.getLevel());
    assertEquals(data, other.getMessage());
    assertNull("null after serialization", other.getThrown());
    assertEquals(new ThrowableProxy(t), other.getThrownProxy());
    assertEquals(evt.getContextData(), other.getContextData());
    assertEquals(contextStack, other.getContextStack());
    assertEquals(threadName, other.getThreadName());
    assertEquals(location, other.getSource());
    assertEquals(12345, other.getTimeMillis());
    assertEquals(678, other.getInstant().getNanoOfMillisecond());
}
项目:logging-log4j2    文件:RingBufferLogEventTest.java   
@SuppressWarnings("deprecation")
@Test
public void testCreateMementoReturnsCopy() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = "logger.name";
    final Marker marker = MarkerManager.getMarker("marked man");
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    final Message data = new SimpleMessage("message");
    final Throwable t = new InternalError("not a real error");
    final ContextStack contextStack = new MutableThreadContextStack(Arrays.asList("a", "b"));
    final String threadName = "main";
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location, new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
    ((StringMap) evt.getContextData()).putValue("key", "value");

    final LogEvent actual = evt.createMemento();
    assertEquals(evt.getLoggerName(), actual.getLoggerName());
    assertEquals(evt.getMarker(), actual.getMarker());
    assertEquals(evt.getLoggerFqcn(), actual.getLoggerFqcn());
    assertEquals(evt.getLevel(), actual.getLevel());
    assertEquals(evt.getMessage(), actual.getMessage());
    assertEquals(evt.getThrown(), actual.getThrown());
    assertEquals(evt.getContextMap(), actual.getContextMap());
    assertEquals(evt.getContextData(), actual.getContextData());
    assertEquals(evt.getContextStack(), actual.getContextStack());
    assertEquals(evt.getThreadName(), actual.getThreadName());
    assertEquals(evt.getTimeMillis(), actual.getTimeMillis());
    assertEquals(evt.getInstant().getNanoOfMillisecond(), actual.getInstant().getNanoOfMillisecond());
    assertEquals(evt.getSource(), actual.getSource());
    assertEquals(evt.getThrownProxy(), actual.getThrownProxy());
}
项目:log4j2-jsonevent-layout    文件:JSONLog4j2Layout.java   
/**
   * Adds the field.
   *
   * @param builder the builder
   * @param key the key
   * @param value the value
   * @param comma the comma
   */
  private void addField(StringBuilder builder,String key,Object value,boolean comma){
    LOGGER.debug("addField {}={} ({})",key,value,comma);
    if(value == null){
        builder.append(ENTITY_SEP).append(key).append(ENTITY_SEP).append(DOTS).append(ENTITY_SEP).append(ENTITY_SEP);

    }else if(value instanceof String){
        builder.append(ENTITY_SEP).append(key).append(ENTITY_SEP).append(DOTS);
        builder.append(ENTITY_SEP).append(cleanJSON(value.toString())).append(ENTITY_SEP);

    } else if (value instanceof Number){
        builder.append(ENTITY_SEP).append(key).append(ENTITY_SEP).append(DOTS).append(value);

    } else if (value instanceof ContextStack){
        List<String> stack = ((ContextStack) value).asList();
        builder.append(ENTITY_SEP).append(key).append(ENTITY_SEP).append(DOTS);
        builder.append(LST_S);
        if(stack!=null && !stack.isEmpty()){
        for(int i=0;i<stack.size();i++){
            builder.append(ENTITY_SEP).append(cleanJSON(stack.get(i))).append(ENTITY_SEP);
            if(i<stack.size()-1){
                builder.append(COMMA);
            }
        }
        }
        builder.append(LST_E);

    } else if(value instanceof Map){
        builder.append(ENTITY_SEP).append(key).append(ENTITY_SEP).append(DOTS).append(getMap((Map<?,?>) value) );

    } else if (value instanceof Throwable){
        Throwable t = (Throwable) value;
        builder.append(ENTITY_SEP).append(key).append(ENTITY_SEP).append(DOTS);

        builder.append(OBJ_S);
            addField(builder,"exception_class",t.getClass().getCanonicalName());
            addField(builder,"exception_message",cleanJSON(t.getMessage()));
            addField(builder,"stacktrace",getStackTrace(t.getStackTrace()),false);
        builder.append(OBJ_E);
    }
if(comma){
    builder.append(COMMA);
}       
  }
项目:log4j2    文件:RingBufferLogEvent.java   
@Override
public ContextStack getContextStack() {
    return contextStack;
}
项目:logging-log4j2    文件:MutableThreadContextStack.java   
@Override
public ContextStack getImmutableStackOrNull() {
    return copy();
}
项目:logging-log4j2    文件:DefaultThreadContextStack.java   
@Override
public ContextStack getImmutableStackOrNull() {
    return STACK.get();
}
项目:logging-log4j2    文件:AbstractLogEvent.java   
@Override
public ContextStack getContextStack() {
    return ThreadContext.EMPTY_STACK;
}
项目:logging-log4j2    文件:LogEventWithContextListMixIn.java   
@JsonProperty(JsonConstants.ELT_CONTEXT_STACK)
@JacksonXmlElementWrapper(namespace = XmlConstants.XML_NAMESPACE, localName = XmlConstants.ELT_CONTEXT_STACK)
@JacksonXmlProperty(namespace = XmlConstants.XML_NAMESPACE, localName = XmlConstants.ELT_CONTEXT_STACK_ITEM)
@Override
public abstract ContextStack getContextStack();
项目:logging-log4j2    文件:LogEventJsonMixIn.java   
@JsonProperty(JsonConstants.ELT_CONTEXT_STACK)
@JacksonXmlElementWrapper(namespace = XmlConstants.XML_NAMESPACE, localName = XmlConstants.ELT_CONTEXT_STACK)
@JacksonXmlProperty(namespace = XmlConstants.XML_NAMESPACE, localName = XmlConstants.ELT_CONTEXT_STACK_ITEM)
@Override
public abstract ContextStack getContextStack();
项目:logging-log4j2    文件:RingBufferLogEvent.java   
@Override
public ContextStack getContextStack() {
    return contextStack;
}
项目:logging-log4j2    文件:Log4jLogEventTest.java   
@SuppressWarnings("deprecation")
@Test
public void testBuilderCorrectlyCopiesAllEventAttributes() {
    final StringMap contextData = ContextDataFactory.createContextData();
    contextData.putValue("A", "B");
    final ContextStack contextStack = ThreadContext.getImmutableStack();
    final Exception exception = new Exception("test");
    final Marker marker = MarkerManager.getMarker("EVENTTEST");
    final Message message = new SimpleMessage("foo");
    final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123);
    final String fqcn = "qualified";
    final String name = "Ceci n'est pas une pipe";
    final String threadName = "threadName";
    final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
            .setContextData(contextData) //
            .setContextStack(contextStack) //
            .setEndOfBatch(true) //
            .setIncludeLocation(true) //
            .setLevel(Level.FATAL) //
            .setLoggerFqcn(fqcn) //
            .setLoggerName(name) //
            .setMarker(marker) //
            .setMessage(message) //
            .setNanoTime(1234567890L) //
            .setSource(stackTraceElement) //
            .setThreadName(threadName) //
            .setThrown(exception) //
            .setTimeMillis(987654321L)
            .build();

    assertEquals(contextData, event.getContextData());
    assertSame(contextStack, event.getContextStack());
    assertEquals(true, event.isEndOfBatch());
    assertEquals(true, event.isIncludeLocation());
    assertSame(Level.FATAL, event.getLevel());
    assertSame(fqcn, event.getLoggerFqcn());
    assertSame(name, event.getLoggerName());
    assertSame(marker, event.getMarker());
    assertSame(message, event.getMessage());
    assertEquals(1234567890L, event.getNanoTime());
    assertSame(stackTraceElement, event.getSource());
    assertSame(threadName, event.getThreadName());
    assertSame(exception, event.getThrown());
    assertEquals(987654321L, event.getTimeMillis());

    final LogEvent event2 = new Log4jLogEvent.Builder(event).build();
    assertEquals("copy constructor builder", event2, event);
    assertEquals("same hashCode", event2.hashCode(), event.hashCode());
}
项目:logging-log4j2    文件:Log4jLogEventTest.java   
@Test
public void testBuilderCorrectlyCopiesAllEventAttributesInclContextData() {
    final StringMap contextData = new SortedArrayStringMap();
    contextData.putValue("A", "B");
    final ContextStack contextStack = ThreadContext.getImmutableStack();
    final Exception exception = new Exception("test");
    final Marker marker = MarkerManager.getMarker("EVENTTEST");
    final Message message = new SimpleMessage("foo");
    final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123);
    final String fqcn = "qualified";
    final String name = "Ceci n'est pas une pipe";
    final String threadName = "threadName";
    final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
            .setContextData(contextData) //
            .setContextStack(contextStack) //
            .setEndOfBatch(true) //
            .setIncludeLocation(true) //
            .setLevel(Level.FATAL) //
            .setLoggerFqcn(fqcn) //
            .setLoggerName(name) //
            .setMarker(marker) //
            .setMessage(message) //
            .setNanoTime(1234567890L) //
            .setSource(stackTraceElement) //
            .setThreadName(threadName) //
            .setThrown(exception) //
            .setTimeMillis(987654321L)
            .build();

    assertSame(contextData, event.getContextData());
    assertSame(contextStack, event.getContextStack());
    assertEquals(true, event.isEndOfBatch());
    assertEquals(true, event.isIncludeLocation());
    assertSame(Level.FATAL, event.getLevel());
    assertSame(fqcn, event.getLoggerFqcn());
    assertSame(name, event.getLoggerName());
    assertSame(marker, event.getMarker());
    assertSame(message, event.getMessage());
    assertEquals(1234567890L, event.getNanoTime());
    assertSame(stackTraceElement, event.getSource());
    assertSame(threadName, event.getThreadName());
    assertSame(exception, event.getThrown());
    assertEquals(987654321L, event.getTimeMillis());

    final LogEvent event2 = new Log4jLogEvent.Builder(event).build();
    assertEquals("copy constructor builder", event2, event);
    assertEquals("same hashCode", event2.hashCode(), event.hashCode());
}
项目:logging-log4j2    文件:Log4jLogEventTest.java   
@Test
public void testBuilderCorrectlyCopiesMutableLogEvent() throws Exception {
    final StringMap contextData = new SortedArrayStringMap();
    contextData.putValue("A", "B");
    final ContextStack contextStack = ThreadContext.getImmutableStack();
    final Exception exception = new Exception("test");
    final Marker marker = MarkerManager.getMarker("EVENTTEST");
    final Message message = new SimpleMessage("foo");
    new StackTraceElement("A", "B", "file", 123);
    final String fqcn = "qualified";
    final String name = "Ceci n'est pas une pipe";
    final String threadName = "threadName";
    final MutableLogEvent event = new MutableLogEvent();
    event.setContextData(contextData);
    event.setContextStack(contextStack);
    event.setEndOfBatch(true);
    event.setIncludeLocation(true);
    //event.setSource(stackTraceElement); // cannot be explicitly set
    event.setLevel(Level.FATAL);
    event.setLoggerFqcn(fqcn);
    event.setLoggerName(name);
    event.setMarker(marker);
    event.setMessage(message);
    event.setNanoTime(1234567890L);
    event.setThreadName(threadName);
    event.setThrown(exception);
    event.setTimeMillis(987654321L);

    assertSame(contextData, event.getContextData());
    assertSame(contextStack, event.getContextStack());
    assertEquals(true, event.isEndOfBatch());
    assertEquals(true, event.isIncludeLocation());
    assertSame(Level.FATAL, event.getLevel());
    assertSame(fqcn, event.getLoggerFqcn());
    assertSame(name, event.getLoggerName());
    assertSame(marker, event.getMarker());
    assertSame(message, event.getMessage());
    assertEquals(1234567890L, event.getNanoTime());
    //assertSame(stackTraceElement, event.getSource()); // don't invoke
    assertSame(threadName, event.getThreadName());
    assertSame(exception, event.getThrown());
    assertEquals(987654321L, event.getTimeMillis());

    final LogEvent e2 = new Log4jLogEvent.Builder(event).build();
    assertEquals(contextData, e2.getContextData());
    assertSame(contextStack, e2.getContextStack());
    assertEquals(true, e2.isEndOfBatch());
    assertEquals(true, e2.isIncludeLocation());
    assertSame(Level.FATAL, e2.getLevel());
    assertSame(fqcn, e2.getLoggerFqcn());
    assertSame(name, e2.getLoggerName());
    assertSame(marker, e2.getMarker());
    assertSame(message, e2.getMessage());
    assertEquals(1234567890L, e2.getNanoTime());
    //assertSame(stackTraceElement, e2.getSource()); // don't invoke
    assertSame(threadName, e2.getThreadName());
    assertSame(exception, e2.getThrown());
    assertEquals(987654321L, e2.getTimeMillis());

    // use reflection to get value of source field in log event copy:
    // invoking the getSource() method would initialize the field
    final Field fieldSource = Log4jLogEvent.class.getDeclaredField("source");
    fieldSource.setAccessible(true);
    final Object value = fieldSource.get(e2);
    assertNull("source in copy", value);
}
项目:stackify-log-log4j2    文件:LogEventAdapter.java   
/**
 * Gets properties from the event's MDC and MDC
 * @param event The logging event
 * @return Map assembled from the event's MDC and NDC
 */
public Map<String, String> getProperties(final LogEvent event) {

    Map<String, String> properties = new HashMap<String, String>();

    // unload the MDC

    Map<String, String> mdc = event.getContextMap();

    if (mdc != null) {
        Iterator<Map.Entry<String, String>> mdcIterator = mdc.entrySet().iterator();

        while (mdcIterator.hasNext()) {
            Map.Entry<String, String> entryPair = (Map.Entry<String, String>) mdcIterator.next();

            String key = entryPair.getKey();
            String value = entryPair.getValue();

            properties.put(key, value != null ? value.toString() : null);
        }
    }

    // unload the NDC

    ContextStack contextStack = event.getContextStack();

    if (contextStack != null) {
        String ndc = contextStack.peek();

        if (ndc != null) {
            if (!ndc.isEmpty()) {
                properties.put("NDC", ndc);
            }
        }
    }

    // return the properties

    return properties;      
}