javalog4j

log4j and JsonTemplateLayout


Recently, I had a problem with log4j that ended up being a dependency conflict, but as part of that, I used the log4j2.xml from https://logging.apache.org/log4j/2.x/manual/getting-started.html

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns="https://logging.apache.org/xml/ns"
               xsi:schemaLocation="
                       https://logging.apache.org/xml/ns
                       https://logging.apache.org/xml/ns/log4j-config-2.xsd">

  <Appenders>
    <Console name="CONSOLE">
      <JsonTemplateLayout/>
    </Console>
  </Appenders>

  <Loggers>
    <Logger name="com.mycompany" level="INFO"/>
    <Root level="WARN">
      <AppenderRef ref="CONSOLE"/>
    </Root>
  </Loggers>

</Configuration>

And when I run it, I get the following message:

2024-12-11T15:13:49.167Z main ERROR Console contains an invalid element or attribute "JsonTemplateLayout"

I am on log4j 2.24.2. What should I use for my console appender since apache can't be depended on to give me the correct answer?


Solution

  • The example on the "Getting started" page uses JSON Template Layout. As most recently-added components, JTL is distributed as a separate Maven module: log4j-layout-template-json.

    The exact dependencies you need to use the example configuration are documented in the How do I install Log4j Core to run my application?. Assuming you use log4j-bom in the dependency management section (which is recommended to prevent mismatched transitive dependencies), you need:

    <!-- Logging implementation (Log4j Core) -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <scope>runtime</scope>
    </dependency>
    
    <!-- Log4j JSON-encoding support -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-layout-template-json</artifactId>
      <scope>runtime</scope>
    </dependency>