Skip to content
Advertisement

create a custom log4j2 rolling file appender

I want to create a custom log4j2 rolling file appender. I need to create this custom appender because I want to wrap the file name with current thread name. We are trying to migrate log4j 1.x to recent log4j2 version and previously we had used DailyRollingFileAppender to log all activities of our application.

please find the below code.

Here we are trying to append the log to a file on daily basis with help of DailyRollingFileAppender based on threadName.

Since DailyRollingFileAppender is deprecated in recent version -so, how to create custom rolling file appender with incorporating our thread based logic.?

Find the below log4j.properties file

JavaScript

Thanks!

JavaScript

Advertisement

Answer

The RollingFileAppender in Log4j 2.x is final, so you can not extend it. However you can obtain the functionality of your custom Log4j 1.x appender using:

For a simple logfile-per-thread appender you can use:

JavaScript

For a more complex configuration both the <Routing> appender and the <Routes> can contain a <Script> (cf. documentation):

  • the script in the <Routing> appender can initialize the staticVariables map and return a default route,
  • the script in the <Routes> component chooses the appropriate route based on staticVariables and the logging event.
Advertisement