Search code examples
javalog4jlog4j2

Used Json Layout template but getting parameters missing in logs [log4j2]


I used Json layout template in my project but I am getting the logs with few parameters missing. I have tried to mention those missing parameters in pattern itself but I guess that was not a right approach to get those parameters in my logs. Any suggestion on that?

rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT


logger.rolling.name = SD
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RALLog

status = error
dest = err

filter.threshold.type = ThresholdFilter
filter.threshold.level = trace

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern =%C{0}.%M:(%L) - %m%n
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = error

#File Appender for JSON log file.
appender.rolling.type = RollingFile
appender.rolling.name = RALLog
appender.rolling.fileName = SD/sac.log
appender.rolling.filePattern = SD/sac/sac-{yyyyMMdd}.log.gz
appender.rolling.layout.type = JsonTemplateLayout
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy

Solution

  • Remark: JsonLayout is considered deprecated. You should use JsonTemplateLayout instead. The latter is the equivalent of PatternLayout for JSON-based layouts.

    If you are referring to the missing location info (the equivalent of the %C, %M and %L patterns, cf. documentation), it is an expensive operation and it is not generated by default, because it decreases logging performance considerably.

    To enable it use:

    appender.rolling.layout.type = JsonLayout
    appender.rolling.layout.locationInfo = true
    

    Edit: If you switch to JsonTemplateLayout, you need to set locationInfoEnabled to true:

    appender.rolling.layout.type = JsonTemplateLayout
    appender.rolling.layout.locationInfoEnabled = true
    

    Moreover the default template does not contain any location information, so you need to add it using EventTemplateAdditionalFields:

    appender.rolling.layout.0.type = EventTemplateAdditionalField
    appender.rolling.layout.0.key = log.origin.file.name
    appender.rolling.layout.0.value = {"$resolver": "source", "field": "fileName"}
    appender.rolling.layout.0.format = JSON
    appender.rolling.layout.1.type = EventTemplateAdditionalField
    appender.rolling.layout.1.key = log.origin.function
    appender.rolling.layout.1.value = {"$resolver": "source", "field": "methodName"}
    appender.rolling.layout.1.format = JSON
    appender.rolling.layout.2.type = EventTemplateAdditionalField
    appender.rolling.layout.2.key = log.origin.file.line
    appender.rolling.layout.2.value = {"$resolver": "source", "field": "lineNumber"}
    appender.rolling.layout.2.format = JSON