Skip to content
Advertisement

Log4j2 customize file path with rollingFileAppender (Java)

I am migrating from log4j 1.x to log4j2 in my spring boot application. Being on log4j 1.x I used to define the properties as follows:

log4j.appender.A1=package.CustomRollingFileAppender
log4j.appender.A1.File=<base.path>/company/logs/main.log

in my CustomRollingFileAppender I would extend this class with the DailyRollingFileAppender, and would override the setName() method to change my ‘<base.path>’ to the relevant directory name.

Migrating to log4j 2.x I no longer have the class DailyRollingFileAppender and can’t extend RollingFileAppender because it is declared as a final. I can’t override the writeToName function either.

So, how do I go about changing the <base.path> in my properties file to the relevant directory name based on my environment static properties?

Advertisement

Answer

You typically do not touch the implementation code of log4j2 classes. What you’re trying to do can be done through configuration.

https://logging.apache.org/log4j/2.x/manual/migration.html https://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender

You can do what you’re asking like this

appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${BASE_DIR}/application.log
appender.rolling.filePattern = ${BASE_DIR}/application.%d{dd-MMM}.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5
logger.rolling.name = rollingFile
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile

where BASE_DIR is an environment variable

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement