Log4j2 not working with json config file

2019-06-13 16:37发布

问题:

It seems like log4j is trying to parse .json config file by XML parser, but why?

I set log4j config file by command line argument:

-Dlog4j.configurationFile=src/log4j2.json

file content:

{
    "configuration": {
        "appenders": {
            "Console": {
                "name": "Console",
                "target": "SYSTEM_OUT",
                "PatternLayout": {
                    "pattern": "%date %thread %logger %message"
                }
            }
        },
        "loggers": {
            "root": {
                "level": "debug",
                "appender-ref": {
                    "ref": "Console"
                }
            }
        }
    }
}

What I get:

[Fatal Error] log4j2.json:1:1: Content is not allowed in prolog.
ERROR StatusLogger Error parsing D:\Dev\HDelphiCrawler\src\log4j2.json org.xml.sax.SAXParseException; systemId: file:///D:/Dev/HDelphiCrawler/src/log4j2.json; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348)
    at org.apache.logging.log4j.core.config.xml.XmlConfiguration.<init>(XmlConfiguration.java:140)
    at org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory.getConfiguration(XmlConfigurationFactory.java:44)
    at org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:410)
    ....and so on...
ERROR StatusLogger No logging configuration

Jars in my lib folder:

  • hamcrest-junit-2.0.0.0.jar
  • jackson-annotations-2.6.1.jar
  • jackson-core-2.6.1.jar
  • jackson-databind-2.6.1.jar
  • java-hamcrest-2.0.0.0.jar
  • junit-4.12.jar
  • kotlin-reflect.jar
  • kotlin-runtime-sources.jar
  • kotlin-runtime.jar
  • log4j-api-2.3.jar
  • log4j-core-2.3.jar
  • log4j-slf4j-impl-2.3.jar

回答1:

You can use the system property log4j.configurationFactory:

-Dlog4j.configurationFactory=org.apache.logging.log4j.core.config.json.JsonConfigurationFactory


回答2:

Even though there is already an accepted answer I'll post my solution too. Maybe this helps someone else in the future...

The reason why it didn't work for me was that I didn't have the jackson-core and jackson-databind library available. After I added

compile 'com.fasterxml.jackson.core:jackson-core:2.8.7'
compile 'com.fasterxml.jackson.core:jackson-databind:2.6.2'

to my build.gradle file everything worked fine.