Java 类org.apache.logging.log4j.message.Message 实例源码

项目:cas-5.1.0    文件:LoggingUtils.java   
/**
 * Prepare log event log event.
 *
 * @param logEvent the log event
 * @return the log event
 */
public static LogEvent prepareLogEvent(final LogEvent logEvent) {
    final String messageModified = TicketIdSanitizationUtils.sanitize(logEvent.getMessage().getFormattedMessage());
    final Message message = new SimpleMessage(messageModified);
    final LogEvent newLogEvent = Log4jLogEvent.newBuilder()
            .setLevel(logEvent.getLevel())
            .setLoggerName(logEvent.getLoggerName())
            .setLoggerFqcn(logEvent.getLoggerFqcn())
            .setContextMap(logEvent.getContextMap())
            .setContextStack(logEvent.getContextStack())
            .setEndOfBatch(logEvent.isEndOfBatch())
            .setIncludeLocation(logEvent.isIncludeLocation())
            .setMarker(logEvent.getMarker())
            .setMessage(message)
            .setNanoTime(logEvent.getNanoTime())
            .setSource(logEvent.getSource())
            .setThreadName(logEvent.getThreadName())
            .setThrownProxy(logEvent.getThrownProxy())
            .setThrown(logEvent.getThrown())
            .setTimeMillis(logEvent.getTimeMillis())
            .build();
    return newLogEvent;
}
项目:EnderCore    文件:TextureErrorRemover.java   
@Override
public void log(Marker marker, String fqcn, Level level, Message data, Throwable t) {
  if (ConfigHandler.textureErrorRemover != 0) {
    if (t instanceof FileNotFoundException) {
      if (ConfigHandler.textureErrorRemover == 1) {
        super.log(marker, fqcn, level, data, null);
      }
      removed++;
    } else {
      super.log(marker, fqcn, level, data, t);
    }
    if (data.getFormat().startsWith("Created:")) {
      EnderCore.logger.info(ConfigHandler.textureErrorRemover == 1 ? new FormattedMessage("Removed %d missing texture stacktraces. Tada!", removed)
          : new FormattedMessage("There were %d missing texture errors here. They're gone now.", removed));
      removed = 0;
    }
    return;
  }
  super.log(marker, fqcn, level, data, t);
}
项目:solr-log4j2    文件:Log4j2Watcher.java   
@Override
public SolrDocument toSolrDocument(LogEvent event) {
  SolrDocument doc = new SolrDocument();
  doc.setField("time", new Date(event.getTimeMillis()));
  doc.setField("level", event.getLevel().toString());
  doc.setField("logger", event.getLoggerName());
  Message message = event.getMessage();
  doc.setField("message", message.getFormattedMessage());
  Throwable t = message.getThrowable();
  if (t != null)
    doc.setField("trace", Throwables.getStackTraceAsString(t));

  Map<String,String> contextMap = event.getContextMap();
  if (contextMap != null) {
    for (String key : contextMap.keySet())
      doc.setField(key, contextMap.get(key));
  }

  if (!doc.containsKey("core"))
    doc.setField("core", ""); // avoids an ugly "undefined" column in the UI

  return doc;
}
项目:stackify-log-log4j2    文件:LogEventAdapterTest.java   
/**
 * testGetStackifyError
 */
@Test
public void testGetStackifyError() {
    Message message = Mockito.mock(Message.class);
    Mockito.when(message.getFormattedMessage()).thenReturn("Exception message");

    LogEvent event = Mockito.mock(LogEvent.class);
    Mockito.when(event.getMessage()).thenReturn(message);

    Throwable exception = Mockito.mock(Throwable.class);

    LogEventAdapter adapter = new LogEventAdapter(Mockito.mock(EnvironmentDetail.class));
    StackifyError error = adapter.getStackifyError(event, exception);

    Assert.assertNotNull(error);
}
项目:stackify-log-log4j2    文件:LogEventAdapterTest.java   
/**
 * testGetStackifyErrorServletContext
 */
@Test
public void testGetStackifyErrorServletContext() {
    String user = "user";
    ServletLogContext.putUser(user);

    WebRequestDetail webRequest = WebRequestDetail.newBuilder().build();
    ServletLogContext.putWebRequest(webRequest);

    Message message = Mockito.mock(Message.class);
    Mockito.when(message.getFormattedMessage()).thenReturn("Exception message");

    LogEvent event = Mockito.mock(LogEvent.class);
    Mockito.when(event.getMessage()).thenReturn(message);

    Throwable exception = Mockito.mock(Throwable.class);

    LogEventAdapter adapter = new LogEventAdapter(Mockito.mock(EnvironmentDetail.class));
    StackifyError error = adapter.getStackifyError(event, exception);

    Assert.assertNotNull(error);

    Assert.assertEquals(user, error.getUserName());
    Assert.assertNotNull(error.getWebRequestDetail());
}
项目:stackify-log-log4j2    文件:LogEventAdapterTest.java   
/**
 * testGetStackifyErrorWithoutException
 */
@Test
public void testGetStackifyErrorWithoutException() {
    StackTraceElement source = new StackTraceElement("class", "method", null, 123);

    Message message = Mockito.mock(Message.class);
    Mockito.when(message.getFormattedMessage()).thenReturn("Exception message");

    LogEvent event = Mockito.mock(LogEvent.class);
    Mockito.when(event.getMessage()).thenReturn(message);
    Mockito.when(event.getSource()).thenReturn(source);

    LogEventAdapter adapter = new LogEventAdapter(Mockito.mock(EnvironmentDetail.class));
    StackifyError error = adapter.getStackifyError(event, null);

    Assert.assertNotNull(error);
    Assert.assertEquals("StringException", error.getError().getErrorType());
}
项目:daikon    文件:Log4j2JSONLayoutTest.java   
@Override
protected Object newEvent(LogDetails logDetails) {
    final Message message = new SimpleMessage(logDetails.getLogMessage());
    final StringMap contextData;
    if (!logDetails.getMdc().isEmpty()) {
        contextData = ContextDataFactory.createContextData();
        logDetails.getMdc().entrySet().forEach(it -> contextData.putValue(it.getKey(), it.getValue()));
    } else {
        contextData = null;
    }
    Log4jLogEvent.Builder builder = Log4jLogEvent.newBuilder().setLoggerName(logDetails.getClassName())
            .setTimeMillis(logDetails.getTimeMillis()).setLevel(Level.DEBUG).setContextData(contextData)
            .setIncludeLocation(logDetails.isLocationInfo()).setLoggerFqcn(logDetails.getClassName()).setMessage(message);
    if (logDetails.isLocationInfo()) {
        builder.setSource(new StackTraceElement(logDetails.getClassName(), logDetails.getMethodName(),
                logDetails.getFileName(), logDetails.getLineNumber()));
    }
    if (logDetails.getException() != null) {
        builder.setThrown(logDetails.getException());
    }
    return builder.build();
}
项目:SocialDataImporter    文件:SdiReportAppender.java   
/**
     * @see org.apache.logging.log4j.core.Appender#append(org.apache.logging.log4j.core.LogEvent)
     */
    @Override
    public void append( LogEvent aEvent )
    {
        Message m = aEvent.getMessage();

//        LOGGER.error( "Received Event: " + m.getClass().getSimpleName() );
        if ( ! ( m instanceof ReportMsg ) )
        {
            return;
        } // if ! ( m instanceof ReportMsg )

        SdiReporter reporter = getReporter();

        if ( reporter == null )
        {
            LOGGER.error( "Bean SdiReporter is null" );
            return;
        } // if reporter == null


        myReporter.add( (ReportMsg) m );
    }
项目:societies    文件:LoggerWrapper.java   
public void logMessage(String string, Level level, Marker marker, Message message, Throwable t) {
    String msg = message.getFormattedMessage();

    msg = MessageFormat.format(msg, message.getParameters());

    if (level == Level.ALL) {
        logger.log(java.util.logging.Level.ALL, msg, t);
    } else if (level == Level.DEBUG) {
        logger.log(java.util.logging.Level.FINEST, msg, t);
    } else if (level == Level.ERROR) {
        logger.log(java.util.logging.Level.SEVERE, msg, t);
    } else if (level == Level.FATAL) {
        logger.log(java.util.logging.Level.SEVERE, msg, t);
    } else if (level == Level.INFO) {
        logger.log(java.util.logging.Level.INFO, msg, t);
    } else if (level == Level.OFF) {
        logger.log(java.util.logging.Level.OFF, msg, t);
    } else if (level == Level.TRACE) {
        logger.log(java.util.logging.Level.SEVERE, msg, t);
    } else if (level == Level.WARN) {
        logger.log(java.util.logging.Level.WARNING, msg, t);
    } else {
        logger.log(java.util.logging.Level.INFO, msg, t);
    }
}
项目:syncope    文件:MemoryAppender.java   
@Override
public void append(final LogEvent event) {
    LogStatementTO statement = new LogStatementTO();

    statement.setLevel(LoggerLevel.fromLevel(event.getLevel()));
    statement.setLoggerName(event.getLoggerName());

    Message msg = event.getMessage();
    statement.setMessage((msg instanceof ReusableMessage
            ? ((ReusableMessage) msg).memento()
            : msg).getFormattedMessage());

    statement.setTimeMillis(event.getTimeMillis());

    if (event.getThrown() != null) {
        statement.setStackTrace(ExceptionUtils2.getFullStackTrace(event.getThrown()));
    }

    statement.setThreadId(event.getThreadId());
    statement.setThreadName(event.getThreadName());
    statement.setThreadPriority(event.getThreadPriority());

    this.statements.add(statement);
}
项目:log4j-systemd-journal-appender    文件:SystemdJournalAppenderTest.java   
@Test
public void testAppend_Simple() {
    SystemdJournalAppender journalAppender = new SystemdJournalAppender("Journal", null, null, false, journalLibrary,
            false, false, false, false, false, false, null, null);

    Message message = mock(Message.class);
    when(message.getFormattedMessage()).thenReturn("some message");
    LogEvent event = new Log4jLogEvent.Builder().setMessage(message).setLevel(Level.INFO).build();

    journalAppender.append(event);

    List<Object> expectedArgs = new ArrayList<>();
    expectedArgs.add("some message");
    expectedArgs.add("PRIORITY=%d");
    expectedArgs.add(6);
    expectedArgs.add(null);

    verify(journalLibrary).sd_journal_send("MESSAGE=%s", expectedArgs.toArray());
}
项目:log4j-systemd-journal-appender    文件:SystemdJournalAppenderTest.java   
@Test
public void testAppend_DoNotLogException() {

    SystemdJournalAppender journalAppender = new SystemdJournalAppender("Journal", null, null, false, journalLibrary,
            false, false, false, false, false, false, null, null);

    Message message = mock(Message.class);
    when(message.getFormattedMessage()).thenReturn("some message");

    LogEvent event = new Log4jLogEvent.Builder() //
            .setMessage(message)//
            .setLoggerFqcn(journalAppender.getClass().getName())//
            .setThrown(new Throwable()) //
            .setLevel(Level.INFO).build();
    event.setIncludeLocation(true);

    journalAppender.append(event);

    List<Object> expectedArgs = new ArrayList<>();
    expectedArgs.add("some message");
    expectedArgs.add("PRIORITY=%d");
    expectedArgs.add(6);
    expectedArgs.add(null);

    verify(journalLibrary).sd_journal_send("MESSAGE=%s", expectedArgs.toArray());
}
项目:jline-log4j2-appender    文件:JLineConsoleAppender.java   
@Override
public void append(LogEvent event) {
    Message msg = event.getMessage();
    if (msg instanceof ConsoleSetupMessage) {
        ConsoleReader reader = ((ConsoleSetupMessage) msg).getReader();
        Listener listener = new ConsoleReaderListener(reader);
        switch (((ConsoleSetupMessage) msg).getAction()) {
        case ADD:
            this.manager.addListener(listener);
            break;
        case REMOVE:
            this.manager.removeListener(listener);
        }
    }
    super.append(event);
}
项目: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;
}
项目:log4j2-to-jul    文件:JULLogger.java   
/**
 * Logs a message with location information by redirecting it to the underlaying {@link java.util.logging.Logger}.
 *
 * @param marker the Marker
 * @param fqcn   the fully qualified class name of the <b>caller</b>
 * @param level  the logging level
 * @param data   the Message.
 * @param t      a Throwable or null.
 */
@Override
public void log(Marker marker, String fqcn, Level level, Message data, Throwable t) {
    final String msg;
    String mkName = (marker == null) ? "" : marker.getName();
    if (this.format == null) {
        if (mkName.isEmpty()) {
            msg = data.getFormattedMessage();
        } else {
            msg = String.format(DEFAULT_FORMAT, data.getFormattedMessage(), mkName);
        }
    } else {
        msg = String.format(this.format, data.getFormattedMessage(), mkName);
    }
    LogRecord record = new LogRecord(Util.levelToJUL(level), msg);
    record.setThrown(t);
    record.setSourceClassName(fqcn);
    record.setLoggerName(this.jul.getName());
    this.jul.log(record);
}
项目:logging-log4j2    文件:AbstractStringLayoutStringEncodingBenchmark.java   
private static LogEvent createLogEvent(final Message message) {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final org.apache.logging.log4j.Level level = org.apache.logging.log4j.Level.DEBUG;
    final Throwable t = null;
    final StringMap mdc = null;
    final ThreadContext.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();
}
项目:log4j2    文件:Log4jLogEvent.java   
/**
 * Constructor.
 * @param loggerName The name of the Logger.
 * @param marker The Marker or null.
 * @param fqcn The fully qualified class name of the caller.
 * @param level The logging Level.
 * @param message The Message.
 * @param t A ThrowableProxy or null.
 * @param mdc The mapped diagnostic context.
 * @param ndc the nested diagnostic context.
 * @param threadName The name of the thread.
 * @param location The locations of the caller.
 * @param timestamp The timestamp of the event.
 */
private Log4jLogEvent(final String loggerName, final Marker marker, final String fqcn, final Level level,
                     final Message message, final ThrowableProxy t,
                     final Map<String, String> mdc, final ThreadContext.ContextStack ndc, final String threadName,
                     final StackTraceElement location, final long timestamp) {
    name = loggerName;
    this.marker = marker;
    this.fqcnOfLogger = fqcn;
    this.level = level;
    this.message = message;
    this.throwable = t;
    this.mdc = mdc;
    this.ndc = ndc;
    this.timestamp = message instanceof TimestampMessage ? ((TimestampMessage) message).getTimestamp() : timestamp;
    this.threadName = threadName;
    this.location = location;
    if (message != null && message instanceof LoggerNameAwareMessage) {
        ((LoggerNameAwareMessage) message).setLoggerName(name);
    }
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@Test
public void testConverterFullSingle() {
    ThreadContext.clearMap();
    ThreadContext.put("foo", "bar");
    final Message msg = new SimpleMessage("Hello");
    final MdcPatternConverter converter = MdcPatternConverter.newInstance(null);
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg) //
            .build();
    final StringBuilder sb = new StringBuilder();
    converter.format(event, sb);
    final String str = sb.toString();
    final String expected = "{foo=bar}";
    assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
项目:logging-log4j2    文件:Rfc5424Layout.java   
private void appendMessage(final StringBuilder buffer, final LogEvent event) {
    final Message message = event.getMessage();
    // This layout formats StructuredDataMessages instead of delegating to the Message itself.
    final String text = (message instanceof StructuredDataMessage || message instanceof MessageCollectionMessage)
            ? message.getFormat() : message.getFormattedMessage();

    if (text != null && text.length() > 0) {
        buffer.append(' ').append(escapeNewlines(text, escapeNewLine));
    }

    if (exceptionFormatters != null && event.getThrown() != null) {
        final StringBuilder exception = new StringBuilder(LF);
        for (final PatternFormatter formatter : exceptionFormatters) {
            formatter.format(event, exception);
        }
        buffer.append(escapeNewlines(exception.toString(), escapeNewLine));
    }
    if (includeNewLine) {
        buffer.append(LF);
    }
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@Test
public void testConverterWithExistingData() {
    final Message msg = new SimpleMessage("Hello");
    final MdcPatternConverter converter = MdcPatternConverter.newInstance(null);
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg) //
            .build();
    final StringBuilder sb = new StringBuilder();
    sb.append("prefix ");
    converter.format(event, sb);
    final String str = sb.toString();
    final String expected = "prefix {object=Log4j, subject=I, verb=love}";
    assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
项目:logging-log4j2    文件:LevelPatternConverterTest.java   
@Test
public void testLevelMapWithLengthAndLowerCase() {
    final Message msg = new SimpleMessage("Hello");
    LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg).build();
    final StringBuilder sb = new StringBuilder();
    LevelPatternConverter converter = LevelPatternConverter.newInstance(null);
    converter.format(event, sb);
    assertEquals(Level.DEBUG.toString(), sb.toString());
    final String[] opts = new String[] { "WARN=Warning, length=2, lowerCase=true" };
    converter = LevelPatternConverter.newInstance(opts);
    sb.setLength(0);
    converter.format(event, sb);
    assertEquals("de", sb.toString());
    event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.WARN) //
            .setMessage(msg).build();
    sb.setLength(0);
    converter.format(event, sb);
    assertEquals("Warning", sb.toString());
}
项目:logging-log4j2    文件:AsyncAppender.java   
/**
 * Actual writing occurs here.
 *
 * @param logEvent The LogEvent.
 */
@Override
public void append(final LogEvent logEvent) {
    if (!isStarted()) {
        throw new IllegalStateException("AsyncAppender " + getName() + " is not active");
    }
    final Log4jLogEvent memento = Log4jLogEvent.createMemento(logEvent, includeLocation);
    InternalAsyncUtil.makeMessageImmutable(logEvent.getMessage());
    if (!transfer(memento)) {
        if (blocking) {
            if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-1518, LOG4J2-2031
                // If queue is full AND we are in a recursive call, call appender directly to prevent deadlock
                final Message message = AsyncQueueFullMessageUtil.transform(logEvent.getMessage());
                logMessageInCurrentThread(new Log4jLogEvent.Builder(logEvent).setMessage(message).build());
            } else {
                // delegate to the event router (which may discard, enqueue and block, or log in current thread)
                final EventRoute route = asyncQueueFullPolicy.getRoute(thread.getId(), memento.getLevel());
                route.logMessage(this, memento);
            }
        } else {
            error("Appender " + getName() + " is unable to write primary appenders. queue is full");
            logToErrorAppenderIfNecessary(false, memento);
        }
    }
}
项目:logging-log4j2    文件:LoggerTest.java   
@Test
public void flowTracingString_SupplierOfObjectMessages() {
    final EntryMessage msg = logger.traceEntry("doFoo(a={}, b={})", new Supplier<Message>() {
        @Override
        public Message get() {
            return new ObjectMessage(1);
        }
    }, new Supplier<Message>() {
        @Override
        public Message get() {
            return new ObjectMessage(2);
        }
    });
    logger.traceExit(msg, 3);
    assertEquals(2, results.size());
    assertThat("Incorrect Entry", results.get(0), startsWith("ENTER[ FLOW ] TRACE Enter"));
    assertThat("Missing entry data", results.get(0), containsString("doFoo(a=1, b=2)"));
    assertThat("Incorrect Exit", results.get(1), startsWith("EXIT[ FLOW ] TRACE Exit"));
    assertThat("Missing exit data", results.get(1), containsString("doFoo(a=1, b=2): 3"));
}
项目:hygene    文件:ConsoleMessageTest.java   
@BeforeEach
void setUp() {
    consoleMessage = new ConsoleMessage("The message");
    logEvent = mock(LogEvent.class);
    message = mock(Message.class);
    when(logEvent.getMessage()).thenReturn(message);
}
项目:log4j2-elasticsearch    文件:ElasticsearchAppenderTest.java   
@Test
public void appenderUsedFormattedMessageDirectlyWhenMessageOnlyIsSetToTrue() {

    // given
    BatchDelivery<String> batchDelivery = mock(BatchDelivery.class);

    ElasticsearchAppender.Builder builder = ElasticsearchAppenderTest.createTestElasticsearchAppenderBuilder();
    builder.withMessageOnly(true);
    builder.withBatchDelivery(batchDelivery );

    String testMessageString = "formattedTestMessage";

    Message message = mock(Message.class);
    when(message.getFormattedMessage()).thenReturn(testMessageString);

    LogEvent logEvent = mock(LogEvent.class);
    when(logEvent.getMessage()).thenReturn(message);

    ElasticsearchAppender appender = builder.build();

    // when
    appender.append(logEvent);

    // then
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(batchDelivery, times(1)).add(anyString(), captor.capture());
    assertEquals(testMessageString, captor.getValue());
}
项目:wizards-of-lua    文件:Log4j2ForgeEventBridge.java   
@Override
public void append(LogEvent event) {
  Message message = event.getMessage();
  String text = message.getFormattedMessage();
  MinecraftForge.EVENT_BUS
      .post(new ServerLog4jEvent(text));
}
项目:ColorConsole    文件:ColorPluginAppender.java   
@Override
public LogEvent onAppend(LogEvent logEvent) {
    String oldMessage = logEvent.getMessage().getFormattedMessage();
    String prefix = "[" + logEvent.getLoggerName() + "] ";
    if (!oldMessage.contains(prefix)
            && !disabledPrefix.stream().anyMatch(disabled -> logEvent.getLoggerName().startsWith(disabled))) {
        oldMessage = prefix + oldMessage;
    }

    Message newMessage = new SimpleMessage(formatter.colorizePluginTag(oldMessage, logEvent.getLevel().name()));
    return clone(logEvent, logEvent.getLoggerName(), newMessage);
}
项目:ColorConsole    文件:ColorAppender.java   
protected LogEvent clone(LogEvent oldEvent, String loggerName, Message message) {
    String className = null;
    if (!disabled) {
        try {
            className = (String) loggerClassGetter.invoke(oldEvent);
        } catch (ReflectiveOperationException refEx) {
            //if this method cannot be found then the other methods wouldn't work neither
            disabled = true;
        }
    }

    return new Log4jLogEvent(loggerName, oldEvent.getMarker(), className
            , oldEvent.getLevel(), message, oldEvent.getThrown());
}
项目:Poseidon    文件:AccessLogPatternConverter.java   
/**
 * Formats LogEvent into a string builder.
 *
 * @param logEvent      event to format, may not be null.
 * @param stringBuilder string builder to which the formatted event will be appended.
 */
@Override
public void format(LogEvent logEvent, StringBuilder stringBuilder) {
    Message message = logEvent.getMessage();
    if (message instanceof IAccessLog) {
        format((IAccessLog) message, stringBuilder);
    }
}
项目:stackify-log-log4j2    文件:LogEventAdapter.java   
/**
 * Gets the log message from the event
 * @param event The event
 * @return The log message
 */
public String getMessage(final LogEvent event) {

    Message message = event.getMessage();

    if (message != null) {
        return message.getFormattedMessage();
    }

    return null;
}
项目:stackify-log-log4j2    文件:LogEventAdapterTest.java   
/**
 * testGetLogMsg
 */
@Test
public void testGetLogMsg() {
    String msg = "msg";
    StackifyError ex = Mockito.mock(StackifyError.class);
    String th = "th";
    String level = "debug";
    String srcClass = "srcClass";
    String srcMethod = "srcMethod";
    Integer srcLine = Integer.valueOf(14);

    Map<String, String> properties = new HashMap<String, String>();
    properties.put("key", "value");

    StackTraceElement source = new StackTraceElement(srcClass, srcMethod, null, srcLine);

    Message message = Mockito.mock(Message.class);
    Mockito.when(message.getFormattedMessage()).thenReturn(msg);

    LogEvent event = Mockito.mock(LogEvent.class);
    Mockito.when(event.getMessage()).thenReturn(message);
    Mockito.when(event.getThreadName()).thenReturn(th);
    Mockito.when(event.getLevel()).thenReturn(Level.DEBUG);
    Mockito.when(event.getSource()).thenReturn(source);
    Mockito.when(event.getContextMap()).thenReturn(properties);

    LogEventAdapter adapter = new LogEventAdapter(Mockito.mock(EnvironmentDetail.class));
    LogMsg logMsg = adapter.getLogMsg(event, ex);

    Assert.assertNotNull(logMsg);
    Assert.assertEquals(msg, logMsg.getMsg());
    Assert.assertEquals("{\"key\":\"value\"}", logMsg.getData());
    Assert.assertEquals(ex, logMsg.getEx());        
    Assert.assertEquals(th, logMsg.getTh());        
    Assert.assertEquals(level, logMsg.getLevel());          
    Assert.assertEquals(srcClass + "." + srcMethod, logMsg.getSrcMethod());     
    Assert.assertEquals(srcLine, logMsg.getSrcLine());      
    Assert.assertEquals(srcLine, logMsg.getSrcLine());      
}
项目:Redux    文件:ReduxLogger.java   
@Override
public void log(Marker marker, String fqcn, Level level, Message data, Throwable t) {
    if (t != null) {
        t.printStackTrace(System.out.format("[%s] %s: %s. Throwable Exception:\n", level.toString(), prefix, data.getFormattedMessage()));
    } else {
        System.out.format("[%s] %s: %s. Caller: %s\n", level.toString(), prefix, data.getFormattedMessage(), fqcn);
    }
}
项目:owasp-security-logging    文件:MaskingRewritePolicy.java   
/**
 * Rewrite the event.
 * 
 * @param source
 *            a logging event that may be returned or used to create a new
 *            logging event.
 * @return The LogEvent after rewriting.
 */
       @Override
public LogEvent rewrite(LogEvent source) {
    // get the markers for the log event. If no markers, nothing can be
    // tagged confidential and we can return
    Marker sourceMarker = source.getMarker();
    if (sourceMarker == null)
        return source;

    // get the message. If no message we can return
    final Message msg = source.getMessage();
    if (msg == null || !(msg instanceof ParameterizedMessage))
        return source;

    // get the parameters. If no params we can return
    Object[] params = msg.getParameters();
    if (params == null || params.length == 0)
        return source;

    // check if this event is actually marked as confidential. If not,
    // return
    Log4jMarker eventMarker = new Log4jMarker(sourceMarker);
    if (!eventMarker.contains(SecurityMarkers.CONFIDENTIAL))
        return source;

    // we have a message, parameters, a marker, and it is confidential.
    // Process
    for (int i = 0; i < params.length; i++) {
        params[i] = MASKED_PASSWORD;
    }
    Message outMessage = new ParameterizedMessage(msg.getFormat(), params,
            msg.getThrowable());
    LogEvent output = new Log4jLogEvent(source.getLoggerName(),
            source.getMarker(), source.getLoggerFqcn(), source.getLevel(),
            outMessage, source.getThrown(), source.getContextMap(),
            source.getContextStack(), source.getThreadName(),
            source.getSource(), source.getTimeMillis());

    return output;
}
项目:owasp-security-logging    文件:MaskingRewritePolicyTest.java   
@Test
public void testRewriteMultiMarker() {
    System.out.println("running testRewriteMultiMarker()");
    org.slf4j.Marker multiMarker = SecurityMarkers.getMarker(SecurityMarkers.CONFIDENTIAL, SecurityMarkers.SECURITY_FAILURE);

    // test a logging event with the multi-marker
    LOGGER.info(multiMarker, "ssn={}", SSN);
    LogEvent failEvent = appender.getEvents().get(0);
    Message message = failEvent.getMessage();

    System.out.println("Formatted message: " + message.getFormattedMessage());
    assertTrue(message.getFormattedMessage().contains("ssn=" + MaskingRewritePolicy.MASKED_PASSWORD));
}
项目:owasp-security-logging    文件:MaskingRewritePolicyTest.java   
/**
 * This test case has the CONFIDENTIAL marker so the results should be masked
 */
@Test
public void testRewriteConfidentialWithParams() {
    System.out.println("running testRewriteConfidentialWithParams()");

    // test a logging event with the CONFIDENTIAL marker
    LOGGER.info(SecurityMarkers.CONFIDENTIAL, "ssn={}", SSN);
    LogEvent failEvent = appender.getEvents().get(0);
    Message message = failEvent.getMessage();

    System.out.println("Formatted message: " + message.getFormattedMessage());
    assertTrue(message.getFormattedMessage().contains("ssn=" + MaskingRewritePolicy.MASKED_PASSWORD));
}
项目:owasp-security-logging    文件:MaskingRewritePolicyTest.java   
/**
 * This test case has the CONFIDENTIAL marker, but it is not parameterized 
 * so masking cannot take place.
 */
@Test
public void testRewriteConfidentialNoParams() {
    System.out.println("running testRewriteConfidentialNoParams()");

    // test a logging event with the CONFIDENTIAL marker
    LOGGER.info(SecurityMarkers.CONFIDENTIAL, "ssn=" + SSN);
    LogEvent failEvent = appender.getEvents().get(0);
    Message message = failEvent.getMessage();

    System.out.println("Formatted message: " + message.getFormattedMessage());
    assertTrue(message.getFormattedMessage().contains("ssn=" + SSN));
}
项目:owasp-security-logging    文件:MaskingRewritePolicyTest.java   
/**
 * This test case is parameterized, but does not have the CONFIDENTIAL 
 * marker, so it should not be masked
 */
@Test
public void testRewriteNotConfidential() {
    System.out.println("running testRewriteSingleMarker()");

    // test a logging event with the CONFIDENTIAL marker
    LOGGER.info(SecurityMarkers.SECURITY_SUCCESS, "ssn={}", SSN);
    LogEvent failEvent = appender.getEvents().get(0);
    Message message = failEvent.getMessage();

    System.out.println("Formatted message: " + message.getFormattedMessage());
    assertTrue(message.getFormattedMessage().contains("ssn=" + SSN));
}
项目:owasp-security-logging    文件:MaskingRewritePolicyTest.java   
@Test
public void testRewriteNoMarker() {
    System.out.println("running testRewriteNoMarker()");

    // test a logging event with no marker
    LOGGER.info("ssn={}", SSN);
    LogEvent failEvent = appender.getEvents().get(0);
    Message message = failEvent.getMessage();

    System.out.println("Formatted message: " + message.getFormattedMessage());
    assertTrue(message.getFormattedMessage().contains("ssn=" + SSN));
}
项目:owasp-security-logging    文件:MaskingRewritePolicyTest.java   
@Test
       public void testRewriteConfidentialNoMessage() {
           System.out.println("running testRewriteConfidentialNoMessage()");

           // test a logging event with null marker
           LOGGER.info(null);
           LogEvent failEvent = appender.getEvents().get(0);
           Message message = failEvent.getMessage();

           System.out.println("Formatted message: " + message.getFormattedMessage());
           assertTrue(message.getFormattedMessage() == null);
}