Search code examples
javalogginglogback

Reading values from java class in Logback


I have a log entry that looks like this

{"logVersion":"1","timestamp":"2020-05-21T06:35:09.021Z","labels":{},"event":{"severity":"INFO","message":”hello world”}}

I want field "labels" to contain keys and values from map that are in Labels class and those values can change during runtime depending on services and controllers called. However reading through https://github.com/logstash/logstash-logback-encoder i did not find possibility to do so.

end result should be like this. Data taken from Map that is in labels Class.

Map<String, String> labels = new HashMap<>();
        labels.put("x", "label1");
        labels.put("y", "label2");

log.info("hello world");

and result

{"logVersion":"1","timestamp":"2020-05-21T06:35:09.021Z","labels":{"x", "label1", "y": "label2"},"event":{"severity":"INFO","message":”hello world”}}

I've also tried adding those values from map to MDC and print them out however issue there is that while I can exclude the known MDC keys, any other MDC's that are added will still show up in that label field

also serializing that map with jackson is also not option as then result will look like this-

{"logVersion":"1","timestamp":"2020-05-21T07:01:07.604Z","labels":"{\”label1\":\”label1Value\",\”label2\":\”label2Value\"}","event":{"severity":"INFO","message":"hello world”}}

Solution

  • Not exactly how i first asked my question but nevertheless managed to resolve my issue so output looks as it should

    public void setLabels(Map<String, String> labels) throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            String labelJson = mapper.writeValueAsString(labels);
            MDC.put("labels", labelJson);
        }
    

    and into logback.xml I added

    <pattern>
        <pattern>
            {
                "labels": "#asJson{%mdc{labels}}"
            }
        </pattern>
    </pattern>