Search in sources :

Example 21 with Log4jLogEvent

use of org.apache.logging.log4j.core.impl.Log4jLogEvent in project logging-log4j2 by apache.

the class PatternParserTest method testCustomPattern.

/**
 * Test the custom pattern
 */
@Test
public void testCustomPattern() {
    final List<PatternFormatter> formatters = parser.parse(customPattern);
    assertNotNull(formatters);
    final StringMap mdc = ContextDataFactory.createContextData();
    mdc.putValue("loginId", "Fred");
    final Throwable t = new Throwable();
    final StackTraceElement[] elements = t.getStackTrace();
    final Log4jLogEvent event = // 
    Log4jLogEvent.newBuilder().setLoggerName(// 
    "org.apache.logging.log4j.PatternParserTest").setMarker(// 
    MarkerManager.getMarker("TEST")).setLoggerFqcn(// 
    Logger.class.getName()).setLevel(// 
    Level.INFO).setMessage(// 
    new SimpleMessage("Hello, world")).setContextData(// 
    mdc).setThreadName(// 
    "Thread1").setSource(elements[0]).setTimeMillis(System.currentTimeMillis()).build();
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
        formatter.format(event, buf);
    }
    final String str = buf.toString();
    final String expected = "INFO  [PatternParserTest        :99  ] - Hello, world" + Strings.LINE_SEPARATOR;
    assertTrue(str.endsWith(expected), "Expected to end with: " + expected + ". Actual: " + str);
}
Also used : StringMap(org.apache.logging.log4j.util.StringMap) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Test(org.junit.jupiter.api.Test)

Example 22 with Log4jLogEvent

use of org.apache.logging.log4j.core.impl.Log4jLogEvent in project logging-log4j2 by apache.

the class XmlLayoutTest method testLayoutLoggerName.

@Test
public void testLayoutLoggerName() {
    final XmlLayout layout = XmlLayout.createLayout(false, true, true, false, null, true);
    final Log4jLogEvent event = //
    Log4jLogEvent.newBuilder().setLoggerName(//
    "a.B").setLoggerFqcn(//
    "f.q.c.n").setLevel(//
    Level.DEBUG).setMessage(//
    new SimpleMessage("M")).setThreadName(//
    "threadName").setTimeMillis(1).build();
    final String str = layout.toSerializable(event);
    assertTrue(str, str.contains("loggerName=\"a.B\""));
}
Also used : Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Test(org.junit.Test)

Example 23 with Log4jLogEvent

use of org.apache.logging.log4j.core.impl.Log4jLogEvent in project logging-log4j2 by apache.

the class LogEventFixtures method createLogEvent.

/**
     * @return a log event that uses all the bells and whistles, features, nooks and crannies
     */
static Log4jLogEvent createLogEvent() {
    final Marker cMarker = MarkerManager.getMarker("Marker1");
    final Marker pMarker1 = MarkerManager.getMarker("ParentMarker1");
    final Marker pMarker2 = MarkerManager.getMarker("ParentMarker2");
    final Marker gfMarker = MarkerManager.getMarker("GrandFatherMarker");
    final Marker gmMarker = MarkerManager.getMarker("GrandMotherMarker");
    cMarker.addParents(pMarker1);
    cMarker.addParents(pMarker2);
    pMarker1.addParents(gmMarker);
    pMarker1.addParents(gfMarker);
    final Exception sourceHelper = new Exception();
    sourceHelper.fillInStackTrace();
    final Exception cause = new NullPointerException("testNPEx");
    sourceHelper.fillInStackTrace();
    final StackTraceElement source = sourceHelper.getStackTrace()[0];
    final IOException ioException = new IOException("testIOEx", cause);
    ioException.addSuppressed(new IndexOutOfBoundsException("I am suppressed exception 1"));
    ioException.addSuppressed(new IndexOutOfBoundsException("I am suppressed exception 2"));
    final ThrowableProxy throwableProxy = new ThrowableProxy(ioException);
    final Map<String, String> contextMap = new HashMap<>();
    contextMap.put("MDC.A", "A_Value");
    contextMap.put("MDC.B", "B_Value");
    final DefaultThreadContextStack contextStack = new DefaultThreadContextStack(true);
    contextStack.clear();
    contextStack.push("stack_msg1");
    contextStack.add("stack_msg2");
    final Log4jLogEvent expected = //
    Log4jLogEvent.newBuilder().setLoggerName(//
    "a.B").setMarker(//
    cMarker).setLoggerFqcn(//
    "f.q.c.n").setLevel(//
    Level.DEBUG).setMessage(//
    new SimpleMessage("Msg")).setThrown(//
    ioException).setThrownProxy(//
    throwableProxy).setContextMap(//
    contextMap).setContextStack(//
    contextStack).setThreadName(//
    "MyThreadName").setSource(//
    source).setTimeMillis(1).build();
    // validate event?
    return expected;
}
Also used : HashMap(java.util.HashMap) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Marker(org.apache.logging.log4j.Marker) IOException(java.io.IOException) ThrowableProxy(org.apache.logging.log4j.core.impl.ThrowableProxy) IOException(java.io.IOException) DefaultThreadContextStack(org.apache.logging.log4j.spi.DefaultThreadContextStack) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent)

Example 24 with Log4jLogEvent

use of org.apache.logging.log4j.core.impl.Log4jLogEvent in project xian by happyyangyuan.

the class GelfLogAppender method createAppender.

@PluginFactory
public static GelfLogAppender createAppender(@PluginConfiguration final Configuration config, @PluginAttribute("name") String name, @PluginElement("Filter") Filter filter, @PluginElement("Field") final GelfLogField[] knownFields, @PluginElement("DynamicMdcFields") final GelfDynamicMdcLogFields[] dynamicMdcFieldArray, @PluginAttribute("graylogHost") String graylogHost, @PluginAttribute("host") String host, @PluginAttribute("graylogPort") String graylogPort, @PluginAttribute("port") String port, @PluginAttribute("version") String version, @PluginAttribute("extractStackTrace") String extractStackTrace, @PluginAttribute("originHost") String originHost, @PluginAttribute("includeFullMdc") String includeFullMdc, @PluginAttribute("facility") String facility, @PluginAttribute("filterStackTrace") String filterStackTrace, @PluginAttribute("mdcProfiling") String mdcProfiling, @PluginAttribute("maximumMessageSize") String maximumMessageSize, @PluginAttribute("additionalFieldTypes") String additionalFieldTypes, @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) boolean ignoreExceptions, @PluginAttribute("layout") String layoutString, @PluginAttribute("messageFormat") MessageFormatEnum jsonOrPlainOrDefault) {
    RuntimeContainer.initialize(ERROR_REPORTER);
    MdcGelfMessageAssembler mdcGelfMessageAssembler;
    if (Objects.equals(MessageFormatEnum.json, jsonOrPlainOrDefault))
        mdcGelfMessageAssembler = new MdcGelfJsonMessageAssembler();
    else
        mdcGelfMessageAssembler = new MdcGelfMessageAssembler();
    if (name == null) {
        LOGGER.error("No name provided for " + GelfLogAppender.class.getSimpleName());
        return null;
    }
    if (Strings.isEmpty(host) && Strings.isEmpty(graylogHost)) {
        LOGGER.error("No host provided for " + GelfLogAppender.class.getSimpleName(), new Throwable());
        return null;
    }
    if (Strings.isNotEmpty(host)) {
        mdcGelfMessageAssembler.setHost(host);
    }
    if (Strings.isNotEmpty(graylogHost)) {
        mdcGelfMessageAssembler.setHost(graylogHost);
    }
    if (Strings.isNotEmpty(port)) {
        mdcGelfMessageAssembler.setPort(Integer.parseInt(port));
    }
    if (Strings.isNotEmpty(graylogPort)) {
        mdcGelfMessageAssembler.setPort(Integer.parseInt(graylogPort));
    }
    if (Strings.isNotEmpty(version)) {
        mdcGelfMessageAssembler.setVersion(version);
    }
    if (Strings.isNotEmpty(originHost)) {
        PatternLayout patternLayout = newBuilder().withPattern(originHost).withConfiguration(config).withNoConsoleNoAnsi(false).withAlwaysWriteExceptions(false).build();
        mdcGelfMessageAssembler.setOriginHost(patternLayout.toSerializable(new Log4jLogEvent()));
    }
    if (facility != null) {
        mdcGelfMessageAssembler.setFacility(facility);
    }
    if (extractStackTrace != null) {
        mdcGelfMessageAssembler.setExtractStackTrace(extractStackTrace);
    }
    if (filterStackTrace != null) {
        mdcGelfMessageAssembler.setFilterStackTrace("true".equals(filterStackTrace));
    }
    if (mdcProfiling != null) {
        mdcGelfMessageAssembler.setMdcProfiling("true".equals(mdcProfiling));
    }
    if (includeFullMdc != null) {
        mdcGelfMessageAssembler.setIncludeFullMdc("true".equals(includeFullMdc));
    }
    if (maximumMessageSize != null) {
        mdcGelfMessageAssembler.setMaximumMessageSize(Integer.parseInt(maximumMessageSize));
    }
    if (additionalFieldTypes != null) {
        ConfigurationSupport.setAdditionalFieldTypes(additionalFieldTypes, mdcGelfMessageAssembler);
    }
    Layout layout = null;
    if (layoutString != null) {
        layout = PatternLayout.newBuilder().withPattern(layoutString).build();
    }
    configureFields(mdcGelfMessageAssembler, knownFields, dynamicMdcFieldArray);
    return new GelfLogAppender(name, filter, layout, mdcGelfMessageAssembler, ignoreExceptions);
}
Also used : Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) Layout(org.apache.logging.log4j.core.Layout) PatternLayout(org.apache.logging.log4j.core.layout.PatternLayout) PatternLayout(org.apache.logging.log4j.core.layout.PatternLayout)

Example 25 with Log4jLogEvent

use of org.apache.logging.log4j.core.impl.Log4jLogEvent in project logging-log4j2 by apache.

the class Log4j1XmlLayoutTest method testWithPropertiesAndLocationInfo.

@Test
public void testWithPropertiesAndLocationInfo() {
    final Log4j1XmlLayout layout = Log4j1XmlLayout.createLayout(true, true);
    final StringMap contextMap = ContextDataFactory.createContextData(2);
    contextMap.putValue("key1", "value1");
    contextMap.putValue("key2", "value2");
    final Log4jLogEvent event = Log4jLogEvent.newBuilder().setLoggerName("a.B").setLevel(Level.INFO).setMessage(new SimpleMessage("Hello, World")).setTimeMillis(System.currentTimeMillis() + 17).setIncludeLocation(true).setSource(new StackTraceElement("pack.MyClass", "myMethod", "MyClass.java", 17)).setContextData(contextMap).build();
    final String result = layout.toSerializable(event);
    final String expected = "<log4j:event logger=\"a.B\" timestamp=\"" + event.getTimeMillis() + "\" level=\"INFO\" thread=\"main\">\r\n" + "<log4j:message><![CDATA[Hello, World]]></log4j:message>\r\n" + "<log4j:locationInfo class=\"pack.MyClass\" method=\"myMethod\" file=\"MyClass.java\" line=\"17\"/>\r\n" + "<log4j:properties>\r\n" + "<log4j:data name=\"key1\" value=\"value1\"/>\r\n" + "<log4j:data name=\"key2\" value=\"value2\"/>\r\n" + "</log4j:properties>\r\n" + "</log4j:event>\r\n\r\n";
    assertEquals(expected, result);
}
Also used : StringMap(org.apache.logging.log4j.util.StringMap) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Test(org.junit.Test)

Aggregations

Log4jLogEvent (org.apache.logging.log4j.core.impl.Log4jLogEvent)37 SimpleMessage (org.apache.logging.log4j.message.SimpleMessage)15 Test (org.junit.Test)15 AbstractJacksonLayout (org.apache.logging.log4j.jackson.AbstractJacksonLayout)14 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)6 MutableLogEvent (org.apache.logging.log4j.core.impl.MutableLogEvent)5 Log4jJsonObjectMapper (org.apache.logging.log4j.jackson.json.Log4jJsonObjectMapper)5 KeyValuePair (org.apache.logging.log4j.core.util.KeyValuePair)4 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)4 StringMap (org.apache.logging.log4j.util.StringMap)4 Serializable (java.io.Serializable)3 ThrowableProxy (org.apache.logging.log4j.core.impl.ThrowableProxy)3 Message (org.apache.logging.log4j.message.Message)3 ObjectMessage (org.apache.logging.log4j.message.ObjectMessage)3 Test (org.junit.jupiter.api.Test)3 Benchmark (org.openjdk.jmh.annotations.Benchmark)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Marker (org.apache.logging.log4j.Marker)2 Log4jJsonObjectMapper (org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper)2