Java Code Examples for ch.qos.logback.classic.spi.ILoggingEvent#getMDCPropertyMap()

The following examples show how to use ch.qos.logback.classic.spi.ILoggingEvent#getMDCPropertyMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoDBAppender.java    From heimdall with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(ILoggingEvent e) {
       ZoneId zoneId = ZoneId.of(this.zoneId);

       // Offset in milliseconds based on the informed Zone
       long offset = zoneId.getRules().getOffset(Instant.now()).getTotalSeconds() * 1000;

	Map<String, Object> objLog = new HashMap<>();
	objLog.put("ts", new BsonDateTime(e.getTimeStamp() + offset));
	objLog.put("trace", BasicDBObject.parse(e.getFormattedMessage()));
	objLog.put("level", e.getLevel().toString());
	objLog.put("logger", e.getLoggerName());
	objLog.put("thread", e.getThreadName());

	if (e.hasCallerData()) {
		StackTraceElement st = e.getCallerData()[0];
		String callerData = String.format("%s.%s:%d", st.getClassName(), st.getMethodName(), st.getLineNumber());
		objLog.put("caller", callerData);
	}
	Map<String, String> mdc = e.getMDCPropertyMap();
	if (mdc != null && !mdc.isEmpty()) {
		objLog.put("mdc", new BasicDBObject(mdc));
	}
	collection.insertOne(new Document(objLog));
}
 
Example 2
Source File: IrisMdcConverter.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public String convert(ILoggingEvent event) {
   Map<String, String> properties = event.getMDCPropertyMap();
   if(properties == null) {
      return "";
   }
   String value = properties.get(key);
   if(value == null) {
      return defaultValue;
   }
   
   StringBuilder sb = 
         new StringBuilder(30)
            .append(prefix)
            .append(value)
            .append(">");
   
   return sb.toString();
}
 
Example 3
Source File: JobMessageLogAppender.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(final ILoggingEvent eventObject) {
    Map<String, String> mdcMap = eventObject.getMDCPropertyMap();
    // TODO: check for JOB marker:
    if (mdcMap.containsKey("job_id") && eventObject.getMarker() != null && JobMarker.JOB.contains(eventObject.getMarker())) {
        String jobId = mdcMap.get("job_id");
        Level level = eventObject.getLevel();
        de.otto.edison.jobs.domain.Level edisonLevel = logLevelToEdisonLevel(level);

        String message = eventObject.getFormattedMessage();

        try {
            final JobMessage jobMessage = jobMessage(edisonLevel, message, OffsetDateTime.now());
            jobService.appendMessage(jobId, jobMessage);
        }
        catch(final RuntimeException e) {
            addError("Failed to persist job message (jobId=" + jobId + "): " + message, e);
        }
    }
}
 
Example 4
Source File: RequestContextExportingAppender.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(ILoggingEvent eventObject) {
    if (exporter == null) {
        exporter = builder.build();
    }
    final Map<String, String> contextMap = exporter.export();
    if (!contextMap.isEmpty()) {
        final Map<String, String> originalMdcMap = eventObject.getMDCPropertyMap();
        final Map<String, String> mdcMap;

        if (!originalMdcMap.isEmpty()) {
            mdcMap = new UnionMap<>(contextMap, originalMdcMap);
        } else {
            mdcMap = contextMap;
        }
        eventObject = new LoggingEventWrapper(eventObject, mdcMap);
    }
    aai.appendLoopOnAppenders(eventObject);
}
 
Example 5
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testMdcPropertyPreservation() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> a.addBuiltIn(BuiltInProperty.REQ_DIRECTION));

    MDC.put("some-prop", "some-value");
    final ServiceRequestContext ctx = newServiceContext("/foo", null);
    try (SafeCloseable ignored = ctx.push()) {
        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("req.direction", "INBOUND")
                       .containsEntry("some-prop", "some-value")
                       .hasSize(2);
    } finally {
        MDC.remove("some-prop");
    }
}
 
Example 6
Source File: DbAppender.java    From semagrow with Apache License 2.0 6 votes vote down vote up
Map<String, String> mergePropertyMaps(ILoggingEvent event) {
    Map<String, String> mergedMap = new HashMap<String, String>();
    // we add the context properties first, then the event properties, since
    // we consider that event-specific properties should have priority over
    // context-wide properties.
    Map<String, String> loggerContextMap = event.getLoggerContextVO()
            .getPropertyMap();
    Map<String, String> mdcMap = event.getMDCPropertyMap();
    if (loggerContextMap != null) {
        mergedMap.putAll(loggerContextMap);
    }
    if (mdcMap != null) {
        mergedMap.putAll(mdcMap);
    }

    return mergedMap;
}
 
Example 7
Source File: LoggingEventToStringImpl.java    From cloudwatch-logback-appender with Apache License 2.0 5 votes vote down vote up
@Override
public String map(ILoggingEvent event) {

    Map<String,Object> values = new HashMap<>();

    values.put("message", event.getFormattedMessage());
    values.put("level", event.getLevel().levelStr);
    values.put("logger-name", event.getLoggerName());
    values.put("thread-name", event.getThreadName());

    Marker marker = event.getMarker();
    if(marker!=null)
        values.put("marker", marker);

    IThrowableProxy exceptionProxy = event.getThrowableProxy();
    if(exceptionProxy!=null) {
        values.put("exception", ExceptionUtil.toString(exceptionProxy));
    }

    // In theory, event.getMDCPropertyMap() should not be null, in practice it can
    if (event.getMDCPropertyMap() != null && !event.getMDCPropertyMap().isEmpty()) {
        values.put("context", event.getMDCPropertyMap());
    }

    try {
        return m.writeValueAsString(values);
    }
    catch(Exception e) {
        return e.getLocalizedMessage();
    }
}
 
Example 8
Source File: ProcessDataLoggingContextTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void assertBpmnStacktraceLogPresent(ProcessInstance instance) {
  List<ILoggingEvent> bpmnStacktraceLog = loggingRule.getFilteredLog("ENGINE-16006");
  assertEquals(2, bpmnStacktraceLog.size());
  for (int i = 0; i < bpmnStacktraceLog.size(); i++) {
    ILoggingEvent logEvent = bpmnStacktraceLog.get(i);
    Map<String, String> mdcPropertyMap = logEvent.getMDCPropertyMap();
    assertTrue(mdcPropertyMap.containsKey("activityId"));
    assertFalse(mdcPropertyMap.containsKey("applicationName"));
    assertTrue(mdcPropertyMap.containsKey("processDefinitionId"));
    assertTrue(mdcPropertyMap.containsKey("processInstanceId"));
    assertTrue(mdcPropertyMap.containsKey("tenantId"));
    if (i == 0) {
      // first BPMN stack trace log corresponds to nested service task
      assertFalse(mdcPropertyMap.containsKey("businessKey"));
      assertEquals("failing_task", mdcPropertyMap.get("activityId"));
      assertNotEquals(instance.getProcessDefinitionId(), mdcPropertyMap.get("processDefinitionId"));
      assertNotEquals(instance.getId(), mdcPropertyMap.get("processInstanceId"));
      assertEquals(instance.getTenantId(), mdcPropertyMap.get("tenantId"));
    } else {
      // second BPMN stack trace log corresponds to outer service task
      assertTrue(mdcPropertyMap.containsKey("businessKey"));
      assertEquals("startProcess", mdcPropertyMap.get("activityId"));
      assertEquals(instance.getBusinessKey(), mdcPropertyMap.get("businessKey"));
      assertEquals(instance.getProcessDefinitionId(), mdcPropertyMap.get("processDefinitionId"));
      assertEquals(instance.getId(), mdcPropertyMap.get("processInstanceId"));
      assertEquals(instance.getTenantId(), mdcPropertyMap.get("tenantId"));
    }
  }
}
 
Example 9
Source File: BugsnagAppender.java    From bugsnag-java with MIT License 5 votes vote down vote up
/**
 * Adds logging context values to the given report meta data
 *
 * @param report The report being sent to Bugsnag
 * @param event The logging event
 */
private void populateContextData(Report report, ILoggingEvent event) {
    Map<String, String> propertyMap = event.getMDCPropertyMap();

    if (propertyMap != null) {
        // Loop through all the keys and put them in the correct tabs

        for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
            report.addToTab("Context", entry.getKey(), entry.getValue());
        }
    }
}
 
Example 10
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testServiceContextWithoutLogs() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> {
        // Export all properties.
        for (BuiltInProperty p : BuiltInProperty.values()) {
            a.addBuiltIn(p);
        }
    });

    final ServiceRequestContext ctx = newServiceContext("/foo", null);
    try (SafeCloseable ignored = ctx.push()) {
        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("local.host", "server.com")
                       .containsEntry("local.ip", "5.6.7.8")
                       .containsEntry("local.port", "8080")
                       .containsEntry("remote.host", "client.com")
                       .containsEntry("remote.ip", "1.2.3.4")
                       .containsEntry("remote.port", "5678")
                       .containsEntry("client.ip", "9.10.11.12")
                       .containsEntry("req.direction", "INBOUND")
                       .containsEntry("req.authority", "server.com:8080")
                       .containsEntry("req.method", "GET")
                       .containsEntry("req.path", "/foo")
                       .containsEntry("scheme", "unknown+h2")
                       .containsEntry("tls.session_id", "0101020305080d15")
                       .containsEntry("tls.proto", "TLSv1.2")
                       .containsEntry("tls.cipher", "some-cipher")
                       .containsKey("req.id")
                       .hasSize(16);
    }
}
 
Example 11
Source File: CustomJsonLayout.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Map toJsonMap(ILoggingEvent event, String fullLogMessage, String loggerNameFilter) {
    Map<String, Object> map = new LinkedHashMap<>();
    addTimestamp(TIMESTAMP_ATTR_NAME, this.includeTimestamp, event.getTimeStamp(), map);
    add(LEVEL_ATTR_NAME, this.includeLevel, String.valueOf(event.getLevel()), map);
    add(THREAD_ATTR_NAME, this.includeThreadName, event.getThreadName(), map);
    add(LOGGER_ATTR_NAME, this.includeLoggerName, event.getLoggerName(), map);
    if (event.getMDCPropertyMap() != null && !event.getMDCPropertyMap().isEmpty()) {
        map.put(contextName, event.getMDCPropertyMap());
    }
    add(FORMATTED_MESSAGE_ATTR_NAME, true, fullLogMessage, map);
    return map;
}
 
Example 12
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testClientContextWithMinimalLogs() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> {
        // Export all properties.
        for (BuiltInProperty p : BuiltInProperty.values()) {
            a.addBuiltIn(p);
        }
    });

    final ClientRequestContext ctx = newClientContext("/foo", "type=bar");
    try (SafeCloseable ignored = ctx.push()) {
        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("local.host", "client.com")
                       .containsEntry("local.ip", "5.6.7.8")
                       .containsEntry("local.port", "5678")
                       .containsEntry("remote.host", "server.com")
                       .containsEntry("remote.ip", "1.2.3.4")
                       .containsEntry("remote.port", "8080")
                       .containsEntry("req.direction", "OUTBOUND")
                       .containsEntry("req.authority", "server.com:8080")
                       .containsEntry("req.method", "GET")
                       .containsEntry("req.path", "/foo")
                       .containsEntry("req.query", "type=bar")
                       .containsEntry("scheme", "unknown+h2")
                       .containsEntry("tls.session_id", "0101020305080d15")
                       .containsEntry("tls.proto", "TLSv1.2")
                       .containsEntry("tls.cipher", "some-cipher")
                       .containsKey("req.id")
                       .hasSize(16);
    }
}
 
Example 13
Source File: RollbarAppender.java    From rollbar-java with MIT License 5 votes vote down vote up
private Map<String, Object> buildMdc(ILoggingEvent event) {
  if (event.getMDCPropertyMap() == null || event.getMDCPropertyMap().size() == 0) {
    return null;
  }
  
  Map<String, Object> custom = new HashMap<>();

  for (Entry<String, String> mdcEntry : event.getMDCPropertyMap().entrySet()) {
    custom.put(mdcEntry.getKey(), mdcEntry.getValue());
  }

  return custom;
}
 
Example 14
Source File: ProcessDataLoggingContextTest.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
protected void assertLogs(ProcessInstance instance, String filter, List<String> expectedActivities, String appName,
    String businessKey, String definitionId, boolean isMdcPresent, Integer numberOfLogs, String activityIdProperty, String appNameProperty,
    String businessKeyProperty, String definitionIdProperty, String instanceIdProperty, String tenantIdProperty) {
  boolean foundLogEntries = false;
  Set<String> passedActivities = new HashSet<>();
  List<ILoggingEvent> filteredLog = loggingRule.getFilteredLog(filter);
  if (numberOfLogs != null) {
    assertEquals(numberOfLogs.intValue(), filteredLog.size());
  }
  for (ILoggingEvent logEvent : filteredLog) {
    Map<String, String> mdcPropertyMap = logEvent.getMDCPropertyMap();
    if (isMdcPresent) {
      // PVM log contains MDC properties
      String activityIdMdc = mdcPropertyMap.get(activityIdProperty);
      String appNameMdc = mdcPropertyMap.get(appNameProperty);
      String businessKeyMdc = mdcPropertyMap.get(businessKeyProperty);
      String definitionIdMdc = mdcPropertyMap.get(definitionIdProperty);
      String instanceIdMdc = mdcPropertyMap.get(instanceIdProperty);
      String tenantIdMdc = mdcPropertyMap.get(tenantIdProperty);

      if (expectedActivities != null) {
        assertNotNull(activityIdMdc);
        assertTrue(expectedActivities.contains(activityIdMdc));
        passedActivities.add(activityIdMdc);
      } else {
        assertNull(activityIdMdc);
      }

      if (appName != null) {
        assertEquals(appName, appNameMdc);
      } else {
        assertNull(appNameMdc);
      }

      if (businessKey != null) {
        assertEquals(businessKey, businessKeyMdc);
      } else {
        assertNull(businessKeyMdc);
      }

      if (definitionId != null) {
        assertEquals(definitionId, definitionIdMdc);
      } else {
        assertNull(definitionIdMdc);
      }

      assertNotNull(instanceIdMdc);
      assertEquals(instance.getId(), instanceIdMdc);

      assertNotNull(tenantIdMdc);
      assertEquals(instance.getTenantId(), tenantIdMdc);

    } else {
      assertTrue(mdcPropertyMap.isEmpty());
    }
    foundLogEntries = true;
  }
  assertTrue(foundLogEntries);
  if (expectedActivities != null) {
    assertTrue(passedActivities.equals(new HashSet<>(expectedActivities)));
  }
}
 
Example 15
Source File: JSONEventLayout.java    From logback-redis-appender with Apache License 2.0 4 votes vote down vote up
/**
 * Formats a {@link ILoggingEvent} in conformity with the log4j.dtd.
 */
public synchronized String doLayout(ILoggingEvent event) {

	// Reset working buffer. If the buffer is too large, then we need a new
	// one in order to avoid the penalty of creating a large array.
	if (buf.capacity() > UPPER_LIMIT) {
		buf = new StringBuilder(DEFAULT_SIZE);
	} else {
		buf.setLength(0);
	}

	Map<String, String> mdc = event.getMDCPropertyMap();
	buf.append("{");
	appendKeyValue(buf, "source", source, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "host", sourceHost, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "path", sourcePath, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "type", type, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "tags", tags, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "message", event.getFormattedMessage(), null);
	buf.append(COMMA);
	appendKeyValue(buf, "@timestamp",
			df.format(new Date(event.getTimeStamp())), null);
	buf.append(COMMA);

	// ---- fields ----
	appendKeyValue(buf, "logger", event.getLoggerName(), null);
	buf.append(COMMA);
	appendKeyValue(buf, "level", event.getLevel().toString(), null);
	buf.append(COMMA);
	appendKeyValue(buf, "thread", event.getThreadName(), null);
	IThrowableProxy tp = event.getThrowableProxy();
	if (tp != null) {
		buf.append(COMMA);
		String throwable = ThrowableProxyUtil.asString(tp);
		appendKeyValue(buf, "throwable", throwable, null);
	}
	if (locationInfo) {
		StackTraceElement[] callerDataArray = event.getCallerData();
		if (callerDataArray != null
				&& callerDataArray.length > callerStackIdx) {
			buf.append(COMMA);
			buf.append("\"location\":{");
			StackTraceElement immediateCallerData = callerDataArray[callerStackIdx];
			appendKeyValue(buf, "class",
					immediateCallerData.getClassName(), null);
			buf.append(COMMA);
			appendKeyValue(buf, "method",
					immediateCallerData.getMethodName(), null);
			buf.append(COMMA);
			appendKeyValue(buf, "file", immediateCallerData.getFileName(),
					null);
			buf.append(COMMA);
			appendKeyValue(buf, "line",
					Integer.toString(immediateCallerData.getLineNumber()),
					null);
			buf.append("}");
		}
	}

	/*
	 * <log4j:properties> <log4j:data name="name" value="value"/>
	 * </log4j:properties>
	 */
	if (properties) {
		Map<String, String> propertyMap = event.getMDCPropertyMap();
		if ((propertyMap != null) && (propertyMap.size() != 0)) {
			Set<Entry<String, String>> entrySet = propertyMap.entrySet();
			buf.append(COMMA);
			buf.append("\"properties\":{");
			Iterator<Entry<String, String>> i = entrySet.iterator();
			while (i.hasNext()) {
				Entry<String, String> entry = i.next();
				appendKeyValue(buf, entry.getKey(), entry.getValue(), null);
				if (i.hasNext()) {
					buf.append(COMMA);
				}
			}
			buf.append("}");
		}
	}

	if(additionalFields != null) {
		for(AdditionalField field : additionalFields) {
			buf.append(COMMA);
			appendKeyValue(buf, field.getKey(), field.getValue(), mdc);
		}
	}

	buf.append("}");

	return buf.toString();
}
 
Example 16
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testClientContextWithFullLogs() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> {
        // Export all properties.
        for (BuiltInProperty p : BuiltInProperty.values()) {
            a.addBuiltIn(p);
        }
        // .. and an attribute.
        a.addAttribute("attrs.my_attr_name", MY_ATTR, new CustomObjectNameStringifier());
        a.addAttribute("attrs.my_attr_value", MY_ATTR, new CustomObjectValueStringifier());
        // .. and some HTTP headers.
        a.addRequestHeader(HttpHeaderNames.USER_AGENT);
        a.addResponseHeader(HttpHeaderNames.DATE);
    });

    final ClientRequestContext ctx = newClientContext("/bar", null);
    try (SafeCloseable ignored = ctx.push()) {
        final RequestLogBuilder log = ctx.logBuilder();
        log.serializationFormat(ThriftSerializationFormats.BINARY);
        log.requestLength(64);
        log.requestHeaders(RequestHeaders.of(HttpMethod.GET, "/bar",
                                             HttpHeaderNames.USER_AGENT, "some-client"));
        log.requestContent(RPC_REQ, THRIFT_CALL);
        log.endRequest();
        log.responseLength(128);
        log.responseHeaders(ResponseHeaders.of(HttpStatus.OK,
                                               HttpHeaderNames.DATE, "some-date"));
        log.responseContent(RPC_RES, THRIFT_REPLY);
        log.endResponse();

        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("local.host", "client.com")
                       .containsEntry("local.ip", "5.6.7.8")
                       .containsEntry("local.port", "5678")
                       .containsEntry("remote.host", "server.com")
                       .containsEntry("remote.ip", "1.2.3.4")
                       .containsEntry("remote.port", "8080")
                       .containsEntry("req.direction", "OUTBOUND")
                       .containsEntry("req.authority", "server.com:8080")
                       .containsEntry("req.method", "GET")
                       .containsEntry("req.path", "/bar")
                       .containsEntry("scheme", "tbinary+h2")
                       .containsEntry("req.name", "hello")
                       .containsEntry("req.content_length", "64")
                       .containsEntry("req.name", "hello")
                       .containsEntry("req.serviceName", Object.class.getName())
                       .containsEntry("req.content", "[world]")
                       .containsEntry("res.status_code", "200")
                       .containsEntry("res.content_length", "128")
                       .containsEntry("res.content", "Hello, world!")
                       .containsEntry("req.headers.user-agent", "some-client")
                       .containsEntry("res.headers.date", "some-date")
                       .containsEntry("tls.session_id", "0101020305080d15")
                       .containsEntry("tls.proto", "TLSv1.2")
                       .containsEntry("tls.cipher", "some-cipher")
                       .containsEntry("attrs.my_attr_name", "some-name")
                       .containsEntry("attrs.my_attr_value", "some-value")
                       .containsKey("req.id")
                       .containsKey("elapsed_nanos")
                       .hasSize(27);
    }
}
 
Example 17
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testServiceContextWithFullLogs() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> {
        // Export all properties.
        for (BuiltInProperty p : BuiltInProperty.values()) {
            a.addBuiltIn(p);
        }
        // .. and an attribute.
        a.addAttribute("attrs.my_attr_name", MY_ATTR, new CustomObjectNameStringifier());
        a.addAttribute("attrs.my_attr_value", MY_ATTR, new CustomObjectValueStringifier());
        // .. and some HTTP headers.
        a.addRequestHeader(HttpHeaderNames.USER_AGENT);
        a.addResponseHeader(HttpHeaderNames.DATE);
    });

    final ServiceRequestContext ctx = newServiceContext("/foo", "bar=baz");
    try (SafeCloseable ignored = ctx.push()) {
        final RequestLogBuilder log = ctx.logBuilder();
        log.serializationFormat(ThriftSerializationFormats.BINARY);
        log.requestLength(64);
        log.requestHeaders(RequestHeaders.of(HttpMethod.GET, "/foo?bar=baz",
                                             HttpHeaderNames.USER_AGENT, "some-client"));
        log.requestContent(RPC_REQ, THRIFT_CALL);
        log.endRequest();
        log.responseLength(128);
        log.responseHeaders(ResponseHeaders.of(HttpStatus.OK,
                                               HttpHeaderNames.DATE, "some-date"));
        log.responseContent(RPC_RES, THRIFT_REPLY);
        log.endResponse();

        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("local.host", "server.com")
                       .containsEntry("local.ip", "5.6.7.8")
                       .containsEntry("local.port", "8080")
                       .containsEntry("remote.host", "client.com")
                       .containsEntry("remote.ip", "1.2.3.4")
                       .containsEntry("remote.port", "5678")
                       .containsEntry("client.ip", "9.10.11.12")
                       .containsEntry("req.direction", "INBOUND")
                       .containsEntry("req.authority", "server.com:8080")
                       .containsEntry("req.method", "GET")
                       .containsEntry("req.name", RPC_REQ.method())
                       .containsEntry("req.serviceName", RPC_REQ.serviceType().getName())
                       .containsEntry("req.path", "/foo")
                       .containsEntry("req.query", "bar=baz")
                       .containsEntry("scheme", "tbinary+h2")
                       .containsEntry("req.content_length", "64")
                       .containsEntry("req.content", "[world]")
                       .containsEntry("res.status_code", "200")
                       .containsEntry("res.content_length", "128")
                       .containsEntry("res.content", "Hello, world!")
                       .containsEntry("req.headers.user-agent", "some-client")
                       .containsEntry("res.headers.date", "some-date")
                       .containsEntry("tls.session_id", "0101020305080d15")
                       .containsEntry("tls.proto", "TLSv1.2")
                       .containsEntry("tls.cipher", "some-cipher")
                       .containsEntry("attrs.my_attr_name", "some-name")
                       .containsEntry("attrs.my_attr_value", "some-value")
                       .containsKey("req.id")
                       .containsKey("elapsed_nanos")
                       .hasSize(29);
    }
}
 
Example 18
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testServiceContextWithMinimalLogs() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> {
        // Export all properties.
        for (BuiltInProperty p : BuiltInProperty.values()) {
            a.addBuiltIn(p);
        }
    });

    final ServiceRequestContext ctx = newServiceContext("/foo", "name=alice");
    try (SafeCloseable ignored = ctx.push()) {
        final RequestLogBuilder log = ctx.logBuilder();
        log.endRequest();
        log.endResponse();

        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("local.host", "server.com")
                       .containsEntry("local.ip", "5.6.7.8")
                       .containsEntry("local.port", "8080")
                       .containsEntry("remote.host", "client.com")
                       .containsEntry("remote.ip", "1.2.3.4")
                       .containsEntry("remote.port", "5678")
                       .containsEntry("client.ip", "9.10.11.12")
                       .containsEntry("req.direction", "INBOUND")
                       .containsEntry("req.authority", "server.com:8080")
                       .containsEntry("req.name", "GET")
                       .containsEntry("req.serviceName", ctx.config().service().getClass().getName())
                       .containsEntry("req.method", "GET")
                       .containsEntry("req.path", "/foo")
                       .containsEntry("req.query", "name=alice")
                       .containsEntry("scheme", "none+h2")
                       .containsEntry("req.content_length", "0")
                       .containsEntry("res.status_code", "0")
                       .containsEntry("res.content_length", "0")
                       .containsEntry("tls.session_id", "0101020305080d15")
                       .containsEntry("tls.proto", "TLSv1.2")
                       .containsEntry("tls.cipher", "some-cipher")
                       .containsKey("elapsed_nanos")
                       .containsKey("req.id")
                       .hasSize(23);
    }
}
 
Example 19
Source File: CustomFieldsConverter.java    From cf-java-logging-support with Apache License 2.0 4 votes vote down vote up
private Map<String, String> getMdcCustomFields(ILoggingEvent event) {
	LogContext.loadContextFields();
	Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
	return customFieldsAdapter.selectCustomFields(mdcPropertyMap);
}
 
Example 20
Source File: LogzioLogbackAppender.java    From logzio-logback-appender with Apache License 2.0 4 votes vote down vote up
private JsonObject formatMessageAsJsonInternal(ILoggingEvent loggingEvent) {
    JsonObject logMessage;

    if (format.equals(FORMAT_JSON)) {
        try {
            JsonElement jsonElement = gson.fromJson(loggingEvent.getFormattedMessage(), JsonElement.class);
            logMessage = jsonElement.getAsJsonObject();
        } catch (Exception e) {
            logMessage = new JsonObject();
            logMessage.addProperty(MESSAGE, loggingEvent.getFormattedMessage());
        }
    } else {
        logMessage = new JsonObject();
        logMessage.addProperty(MESSAGE, loggingEvent.getFormattedMessage());
    }

    // Adding MDC first, as I dont want it to collide with any one of the following fields
    if (loggingEvent.getMDCPropertyMap() != null) {
        loggingEvent.getMDCPropertyMap().forEach(logMessage::addProperty);
    }

    logMessage.addProperty(TIMESTAMP, new Date(loggingEvent.getTimeStamp()).toInstant().toString());
    logMessage.addProperty(LOGLEVEL,loggingEvent.getLevel().levelStr);

    if (loggingEvent.getMarker() != null) {
        logMessage.addProperty(MARKER, loggingEvent.getMarker().toString());
    }

    logMessage.addProperty(LOGGER, loggingEvent.getLoggerName());
    logMessage.addProperty(THREAD, loggingEvent.getThreadName());
    if (line) {
        logMessage.addProperty(LINE, lineOfCallerConverter.convert(loggingEvent));
    }

    if (loggingEvent.getThrowableProxy() != null) {
        logMessage.addProperty(EXCEPTION, throwableProxyConverter.convert(loggingEvent));
    }

    if (additionalFieldsMap != null) {
        additionalFieldsMap.forEach(logMessage::addProperty);
    }

    return logMessage;
}