How to lookup thread context in custom log4j2 jsonlayout plugin












0















I have implemented the following plugin to create custom Json layout for log4j logs. I am not sure how I can implement the context lookup in the Plugin. For example, the application puts certain keys in MDC and with the below configuration in log4j.xml, it must be written in logs.



<KeyValuePair key="customerId" value="$${customerId}" />. 


Plugin



@Plugin(name = "CustomJsonLayout", category = "Core", elementType = "layout", printObject = true)
public class CustomJsonLayout extends AbstractStringLayout {
private final ObjectMapper objectMapper;

CustomJsonLayout(Charset charset) {
super(charset);
SimpleModule module = new SimpleModule();
module.addSerializer(LogEvent.class, new LogEventSerializer());
module.addSerializer(ReadOnlyStringMap.class, new ContextDataSerializer() {
});
objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}

@Override
public String toSerializable(LogEvent logEvent) {
try {
return objectMapper.writeValueAsString(logEvent);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}

private static class LogEventSerializer extends StdSerializer<LogEvent> {
LogEventSerializer() {
super(LogEvent.class);
}

@Override
public void serialize(LogEvent value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date(value.getTimeMillis()));

gen.writeStartObject();
gen.writeStringField("timestamp", date);
gen.writeStringField("component", MicroService.getAppName());
gen.writeStringField("severity", value.getLevel().name());
gen.writeObjectField("msg", value.getMessage().getFormattedMessage());
gen.writeEndObject();
gen.writeRaw("n");
}
}

@PluginBuilderFactory
public static <B extends Builder<B>> B newBuilder() {
return new Builder<B>().asBuilder();
}

public static class Builder<B extends Builder<B>> extends org.apache.logging.log4j.core.layout.AbstractStringLayout.Builder<B> implements org.apache.logging.log4j.core.util.Builder<CustomJsonLayout> {
Builder() {
this.setCharset(StandardCharsets.UTF_8);
}

public CustomJsonLayout build() {
return new CustomJsonLayout(this.getCharset());
}
}
}









share|improve this question























  • Are you saying you have tried using the lookup and it is failing? I ask because I would expect the lookup to be resolved /before/ the parameters are passed into your logic.

    – D.B.
    Nov 13 '18 at 18:42











  • No, I was asking how to implement the KeyValuePair in JsonLayout

    – cppcoder
    Nov 14 '18 at 5:23











  • Have you looked at the source for JsonLayout? Also, you might consider extending JsonLayout or at least using its code as a template for your own.

    – D.B.
    Nov 15 '18 at 0:11
















0















I have implemented the following plugin to create custom Json layout for log4j logs. I am not sure how I can implement the context lookup in the Plugin. For example, the application puts certain keys in MDC and with the below configuration in log4j.xml, it must be written in logs.



<KeyValuePair key="customerId" value="$${customerId}" />. 


Plugin



@Plugin(name = "CustomJsonLayout", category = "Core", elementType = "layout", printObject = true)
public class CustomJsonLayout extends AbstractStringLayout {
private final ObjectMapper objectMapper;

CustomJsonLayout(Charset charset) {
super(charset);
SimpleModule module = new SimpleModule();
module.addSerializer(LogEvent.class, new LogEventSerializer());
module.addSerializer(ReadOnlyStringMap.class, new ContextDataSerializer() {
});
objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}

@Override
public String toSerializable(LogEvent logEvent) {
try {
return objectMapper.writeValueAsString(logEvent);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}

private static class LogEventSerializer extends StdSerializer<LogEvent> {
LogEventSerializer() {
super(LogEvent.class);
}

@Override
public void serialize(LogEvent value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date(value.getTimeMillis()));

gen.writeStartObject();
gen.writeStringField("timestamp", date);
gen.writeStringField("component", MicroService.getAppName());
gen.writeStringField("severity", value.getLevel().name());
gen.writeObjectField("msg", value.getMessage().getFormattedMessage());
gen.writeEndObject();
gen.writeRaw("n");
}
}

@PluginBuilderFactory
public static <B extends Builder<B>> B newBuilder() {
return new Builder<B>().asBuilder();
}

public static class Builder<B extends Builder<B>> extends org.apache.logging.log4j.core.layout.AbstractStringLayout.Builder<B> implements org.apache.logging.log4j.core.util.Builder<CustomJsonLayout> {
Builder() {
this.setCharset(StandardCharsets.UTF_8);
}

public CustomJsonLayout build() {
return new CustomJsonLayout(this.getCharset());
}
}
}









share|improve this question























  • Are you saying you have tried using the lookup and it is failing? I ask because I would expect the lookup to be resolved /before/ the parameters are passed into your logic.

    – D.B.
    Nov 13 '18 at 18:42











  • No, I was asking how to implement the KeyValuePair in JsonLayout

    – cppcoder
    Nov 14 '18 at 5:23











  • Have you looked at the source for JsonLayout? Also, you might consider extending JsonLayout or at least using its code as a template for your own.

    – D.B.
    Nov 15 '18 at 0:11














0












0








0








I have implemented the following plugin to create custom Json layout for log4j logs. I am not sure how I can implement the context lookup in the Plugin. For example, the application puts certain keys in MDC and with the below configuration in log4j.xml, it must be written in logs.



<KeyValuePair key="customerId" value="$${customerId}" />. 


Plugin



@Plugin(name = "CustomJsonLayout", category = "Core", elementType = "layout", printObject = true)
public class CustomJsonLayout extends AbstractStringLayout {
private final ObjectMapper objectMapper;

CustomJsonLayout(Charset charset) {
super(charset);
SimpleModule module = new SimpleModule();
module.addSerializer(LogEvent.class, new LogEventSerializer());
module.addSerializer(ReadOnlyStringMap.class, new ContextDataSerializer() {
});
objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}

@Override
public String toSerializable(LogEvent logEvent) {
try {
return objectMapper.writeValueAsString(logEvent);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}

private static class LogEventSerializer extends StdSerializer<LogEvent> {
LogEventSerializer() {
super(LogEvent.class);
}

@Override
public void serialize(LogEvent value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date(value.getTimeMillis()));

gen.writeStartObject();
gen.writeStringField("timestamp", date);
gen.writeStringField("component", MicroService.getAppName());
gen.writeStringField("severity", value.getLevel().name());
gen.writeObjectField("msg", value.getMessage().getFormattedMessage());
gen.writeEndObject();
gen.writeRaw("n");
}
}

@PluginBuilderFactory
public static <B extends Builder<B>> B newBuilder() {
return new Builder<B>().asBuilder();
}

public static class Builder<B extends Builder<B>> extends org.apache.logging.log4j.core.layout.AbstractStringLayout.Builder<B> implements org.apache.logging.log4j.core.util.Builder<CustomJsonLayout> {
Builder() {
this.setCharset(StandardCharsets.UTF_8);
}

public CustomJsonLayout build() {
return new CustomJsonLayout(this.getCharset());
}
}
}









share|improve this question














I have implemented the following plugin to create custom Json layout for log4j logs. I am not sure how I can implement the context lookup in the Plugin. For example, the application puts certain keys in MDC and with the below configuration in log4j.xml, it must be written in logs.



<KeyValuePair key="customerId" value="$${customerId}" />. 


Plugin



@Plugin(name = "CustomJsonLayout", category = "Core", elementType = "layout", printObject = true)
public class CustomJsonLayout extends AbstractStringLayout {
private final ObjectMapper objectMapper;

CustomJsonLayout(Charset charset) {
super(charset);
SimpleModule module = new SimpleModule();
module.addSerializer(LogEvent.class, new LogEventSerializer());
module.addSerializer(ReadOnlyStringMap.class, new ContextDataSerializer() {
});
objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}

@Override
public String toSerializable(LogEvent logEvent) {
try {
return objectMapper.writeValueAsString(logEvent);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}

private static class LogEventSerializer extends StdSerializer<LogEvent> {
LogEventSerializer() {
super(LogEvent.class);
}

@Override
public void serialize(LogEvent value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date(value.getTimeMillis()));

gen.writeStartObject();
gen.writeStringField("timestamp", date);
gen.writeStringField("component", MicroService.getAppName());
gen.writeStringField("severity", value.getLevel().name());
gen.writeObjectField("msg", value.getMessage().getFormattedMessage());
gen.writeEndObject();
gen.writeRaw("n");
}
}

@PluginBuilderFactory
public static <B extends Builder<B>> B newBuilder() {
return new Builder<B>().asBuilder();
}

public static class Builder<B extends Builder<B>> extends org.apache.logging.log4j.core.layout.AbstractStringLayout.Builder<B> implements org.apache.logging.log4j.core.util.Builder<CustomJsonLayout> {
Builder() {
this.setCharset(StandardCharsets.UTF_8);
}

public CustomJsonLayout build() {
return new CustomJsonLayout(this.getCharset());
}
}
}






java log4j2






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 11:56









cppcodercppcoder

14.1k43468




14.1k43468













  • Are you saying you have tried using the lookup and it is failing? I ask because I would expect the lookup to be resolved /before/ the parameters are passed into your logic.

    – D.B.
    Nov 13 '18 at 18:42











  • No, I was asking how to implement the KeyValuePair in JsonLayout

    – cppcoder
    Nov 14 '18 at 5:23











  • Have you looked at the source for JsonLayout? Also, you might consider extending JsonLayout or at least using its code as a template for your own.

    – D.B.
    Nov 15 '18 at 0:11



















  • Are you saying you have tried using the lookup and it is failing? I ask because I would expect the lookup to be resolved /before/ the parameters are passed into your logic.

    – D.B.
    Nov 13 '18 at 18:42











  • No, I was asking how to implement the KeyValuePair in JsonLayout

    – cppcoder
    Nov 14 '18 at 5:23











  • Have you looked at the source for JsonLayout? Also, you might consider extending JsonLayout or at least using its code as a template for your own.

    – D.B.
    Nov 15 '18 at 0:11

















Are you saying you have tried using the lookup and it is failing? I ask because I would expect the lookup to be resolved /before/ the parameters are passed into your logic.

– D.B.
Nov 13 '18 at 18:42





Are you saying you have tried using the lookup and it is failing? I ask because I would expect the lookup to be resolved /before/ the parameters are passed into your logic.

– D.B.
Nov 13 '18 at 18:42













No, I was asking how to implement the KeyValuePair in JsonLayout

– cppcoder
Nov 14 '18 at 5:23





No, I was asking how to implement the KeyValuePair in JsonLayout

– cppcoder
Nov 14 '18 at 5:23













Have you looked at the source for JsonLayout? Also, you might consider extending JsonLayout or at least using its code as a template for your own.

– D.B.
Nov 15 '18 at 0:11





Have you looked at the source for JsonLayout? Also, you might consider extending JsonLayout or at least using its code as a template for your own.

– D.B.
Nov 15 '18 at 0:11












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280529%2fhow-to-lookup-thread-context-in-custom-log4j2-jsonlayout-plugin%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280529%2fhow-to-lookup-thread-context-in-custom-log4j2-jsonlayout-plugin%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Tangent Lines Diagram Along Smooth Curve

Yusuf al-Mu'taman ibn Hud

Zucchini