log4j - CSV Parameter Layout



If you want to generate your logging information in an CSV-formatted file, then you can use org.apache.logging.log4j.CSVParameterLayout to format your logging information.

The CSVParameterLayout class encodes only the parameters passed in the message of log event.

For example, consider the below log statements −

 LOGGER.info("Record 1 {} {}", "arg1", "arg2"); LOGGER.error("Record 2 {} {} {}", "arg3", "arg4", "arg5", throwable); 

The resulted logs will contain following entries in CSV format −

 arg1,arg2 arg3,arg4,arg5 

CSVParameterLayout Configuration

CSVParameterLayout can be configured with following parameters:

Parameter Type Description
format String A predefined format name (Default, Excel, MySQL, RFC4180, TDF, etc.) accepted by CSVFormat
delimiter Character The field delimiter character
escape Character The escape character
quote Character The quote character
quoteMode String A quote mode name (ALL, ALL_NONE_NULL, MINIMAL, NON_NUMERIC, NONE, etc.) accepted by QuoteMode
nullString String The string to denote null values
recordSeparator String The record separator string
charset Charset The character encoding
header String The header to include when the stream is opened
footer String The footer to include when the stream is closed

We need following jars in the classpath −

Example - Usage of CSVParameterLayout

Following is a simple configuration file for CSVParameterLayout:

log4j2.properties

 # Define the appender appender.0.type = Console appender.0.name = CONSOLE appender.0.layout.type = CsvParameterLayout # Define the root logger with appender Console rootLogger.level = DEBUG rootLogger.appenderRef.0.ref = CONSOLE 

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("Record 1 {} {}", "arg1", "arg2"); LOGGER.info("Record 2 {} {} {}", "arg1", "arg2", "arg3"); } } 

Output

Compile and run the above program. Console will print the following log information:

 arg1,arg2 arg1,arg2,arg3 
Advertisements