How to Create a Custom Appender in log4j2 ?

By | January 14, 2022

In this post, We will learn How to Create a Custom Appender in log4j 2?

In log4j 2, We usually create a plugin for creating a custom appender.

When we annotate our custom Appender class with @Plugin(name = “MyCustomAppender”, category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true) the plugin name becomes the configuration element name.

Below is the complete source code:

pom.xml

We have added log4j2  log4j-apilog4j-core dependency in the dependencies section.

log4j2.xml

In the log4j2.xml file don’t forget to specify the packages attribute here you have to configure your custom appender packages. If you have multiple packages then each package should separate with a semicolon(;)

MyCustomAppender.java

Now we are creating a plugin for a custom appender.

ClientTest.java

Now we are going to test our custom appender. For this, I’ve written below test class.

If you run ClientTest.java as java application then you’ll find below output:

Custom Log: 22:36:11.538 [main] INFO com.kkjavatutorials.client.ClientTest – This is info message
Custom Log: 22:36:11.540 [main] WARN com.kkjavatutorials.client.ClientTest – This is warn message
Custom Log: 22:36:11.540 [main] ERROR com.kkjavatutorials.client.ClientTest – This is error message

You May Also Like:
Why Logging?
Log4j 2 simple example

That’s All about How to Create a Custom Appender in log4j 2?

One thought on “How to Create a Custom Appender in log4j2 ?

  1. sinh

    I run that code on IntelliJ this work but when i build jar file this not work, it out problems:
    2023-01-26 15:14:53,436 main ERROR Error processing element MyCustomAppender ([Appenders: null]): CLASS_NOT_FOUND
    2023-01-26 15:14:53,506 main ERROR Unable to locate appender “customAppender” for logger config “root”

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *