
- log4j - Home
- log4j - Overview
- log4j - Installation
- log4j - Architecture
- log4j - Configuration
- log4j - Sample Program
- log4j - Logging Methods
- log4j - Logging Levels
- log4j - ConsoleAppender
- log4j - Logging in Database
Log4j - Formatting Layouts
- log4j - Log Formatting
- log4j - CSV Parameter Layout
- log4j - CSV Log Event Layout
- log4j - HTML Layout
- log4j - Pattern Layout
- log4j - Json Template Layout
Log4j - File Appenders
- log4j - Logging in Files
- log4j - FileAppender
- log4j - Separate Folder per Month
- log4j - Daily log File Generation
log4j Resources
log4j - Json Template Layout
If you want to encode your complete logging information in a JSON formatted file, then you can use org.apache.logging.log4j.JsonTemplateLayout to format your logging information.
JsonTemplateLayout is highly customizable, efficient layout. It is a garbage-free JSON generating layout as well. LogEvents are genereated according to the structure described by the JSON template provided in classpath.
CustomLayout.json
{ "instant": { "$resolver": "timestamp", "pattern": { "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "timeZone": "UTC" } }, "aConstant": 1, "message": { "$resolver": "message", "stringified": true } }
log4j2.properties
appender.0.layout.type = JsonTemplateLayout appender.0.layout.eventTemplateUri = classpath:CustomLayout.json
log4j2.xml
<Appenders> <Console name="logFile"> <JsonTemplateLayout eventTemplateUri="classpath:CustomLayout.json"/> </Appenders>
Example - Usage of JsonTemplateLayout
Following is a simple configuration file for JsonTemplateLayout:
log4j2.properties
# Define the appender appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = JsonTemplateLayout appender.0.layout.eventTemplateUri = classpath:CustomLayout.json # Define the root logger with appender Console rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE
Now create a template json in current classpath:
CustomLayout.json
{ "instant": { "$resolver": "timestamp", "pattern": { "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "timeZone": "UTC" } }, "aConstant": 1, "message": { "$resolver": "message", "stringified": true } }
Now consider the following Java Example which would generate logging information:
Log4jDemo.java
package com.tutorialspoint; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4jDemo{ /* Get actual class name to be printed on */ private static final Logger LOGGER = LogManager.getLogger(); public static void main(String[] args) { LOGGER.debug("Hello this is an debug message"); LOGGER.info("Hello this is an info message"); } }
Output
Compile and run the above program. Console will print the following log information:
{"instant":"2025-09-07T14:58:18.268Z","aConstant":1,"message":"Hello this is an debug message"} {"instant":"2025-09-07T14:58:18.273Z","aConstant":1,"message":"Hello this is an info message"}
Advertisements