log4j JsonTemplateLayout doesn't work when jar file built by shadowJar
Asked Answered
B

1

1

I use shadowJar I use log4j2 and I need to log everything in json format. But once I add 'org.apache.logging.log4j:log4j-layout-template-json:2.17.1' into build.gradle file I'm getting this errors:

ERROR StatusLogger Unrecognized format specifier [d]
ERROR StatusLogger Unrecognized conversion specifier [d] starting at position 16 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [thread]
ERROR StatusLogger Unrecognized conversion specifier [thread] starting at position 25 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [level]
ERROR StatusLogger Unrecognized conversion specifier [level] starting at position 35 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [logger]
ERROR StatusLogger Unrecognized conversion specifier [logger] starting at position 47 in conversion pattern.

if I remove log4j-layout-template-json dependency usual logging become working, but I need logging in json format using JsonTemplateLayout.

here is my build.gradle file:

apply plugin: 'java'
apply plugin: "com.github.johnrengelman.shadow"


shadowJar {
    zip64 = true

}

dependencies {

    compileOnly 'org.projectlombok:lombok:1.18.22'
    annotationProcessor 'org.projectlombok:lombok:1.18.22'
    implementation 'org.apache.logging.log4j:log4j-api:2.17.1'
    implementation 'org.apache.logging.log4j:log4j-core:2.17.1'
    implementation 'org.apache.logging.log4j:log4j-layout-template-json:2.17.1'
    implementation 'org.apache.logging.log4j:log4j-slf4j-impl:2.17.1'
    testImplementation 'org.testng:testng:7.4.0'
}


tasks.named('test') {
    // Use TestNG for unit tests.
    useTestNG()
}

I also use gradle shadowJar plugin to build fat jar. Because I'm need to run my jar file this way: java -cp example-0.0.1-all.jar org.example.Main

Buffington answered 13/3, 2022 at 15:19 Comment(4)
Does this answer your question? log4j2 ERROR Unrecognized format specifier [t]Eskimo
No it does not answerBuffington
You need to use the Log4j2PluginsCacheFileTransformer as suggested in Marian's answer, otherwise the plugins cache from one Log4j's jar overrides the others.Eskimo
Yes! This looks like working solution. Thanks!Buffington
B
2

Answering my question this is what worked for me:

import com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer

shadowJar{
    transform(Log4j2PluginsCacheFileTransformer)
}
Buffington answered 28/4, 2022 at 16:23 Comment(1)
I second this, took me forever to figure out that this was my actual issue. This is particularly relevant if you are building an aws lambda as log4j2 will not work correctly without this. For a similar issue with a bit more of a write up for both gradle and maven check out #75839285. As well as this documentation github.com/aws/aws-lambda-java-libs/blob/main/…Pringle

© 2022 - 2024 — McMap. All rights reserved.