Log4j2

Jars

'org.apache.logging.log4j:log4j-api:2.13.3'
'org.apache.logging.log4j:log4j-core:2.13.3'

Sample Code :

package com.log4j2demo;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Demo {
	private static final Logger LOGGER = LogManager.getLogger(Demo.class);
	public static void main(String[] args) {
		System.out.println("Hello");
		LOGGER.debug("This is a debug statement");
		LOGGER.info("This is Info Log");
		LOGGER.error("This is Error Log", new NullPointerException());
		LOGGER.fatal("This is Fatal Log");
		LOGGER.trace("This is trace Log");
	}
}

Log4j2.properties (on class path)

status = error 
#The level of internal Log4j events that should be logged to the console. 
#"trace", "debug", "info", "warn", "error" and "fatal"

name = PropertiesConfig
#The name of the configuration.
 
property.filename = /home/tyson/Desktop/MoveScript/debug.log
#Make sure to change log file path as per your need
 
filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
#https://logging.apache.org/log4j/log4j-2.3/manual/filters.html (Accept/Deny/Threshold)
#Literally Filtering Logs

#appenders = rolling
 
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.append = true
#  ${filename} will be replaced by property.filename values
appender.rolling.filePattern = /home/tyson/Desktop/MoveScript/debug-backup-%d{yyyy-MM-dd}-%i.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{2}:%L - %m%n
# %d is the date
# %-5p is the priority
# %c{1} Logger name (org.apache.commons.Foo) and reslt (Foo)
# %L for line
# %m for message
# %n for /n
#reference https://logging.apache.org/log4j/2.x/manua%l/layouts.html#PatternLayout
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
#Interval depends on the pattern specified (appender.rolling.filePattern) last value if mm then 1 minutes HH then 1H
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
#appender.rolling.append
 
loggers = rolling
logger.rolling.name = com.log4j2demo
#Make sure to change the package structure as per your application
logger.rolling.level = debug
logger.rolling.additivity = true
#The rolling file appender will be displayed on console as well
logger.rolling.appenderRef.rolling.ref = RollingFile

#Read Me
# https://logging.apache.org/log4j/2.x/manual/configuration.html#ConfigurationSyntax
# Layput https://logging.apache.org/log4j/2.x/manual/layouts.html

Leave a Comment