12

I am trying to migrate a class that extends org.apache.log4j.AppenderSkeleton from an old version of log4j to log4j 2. I was reading the JavaDoc for the class, and I read that,

Appenders constructed using this are ignored in Log4j 2.

on the website for the class.

Does this mean, if I am using Log4j 2, I should extend this class? If yes, what should I use as an alternative? Would ConsoleAppender do the trick?

hell_storm2004
  • 1,401
  • 2
  • 33
  • 66

2 Answers2

6

Appenders in Log4j 2 implement the Appender interface. Most Appenders will extend either AbstractAppender, AbstractOutputStreamAppender, or AbstractWriterAppender. Log4j 2 uses Plugins, which means your appender will have to be annotated with @Plugin and defined as an Appender. Appenders also require a Builder annotated with @PluginBuilderFactory to create the Appender instance from its configuration. You can look at any of Log4j's Appenders, such as FileAppender, for an example.

You will also notice that most of the Appenders use a Manager to perform most of the work. This is because Appenders are always recreated during a reconfiguration, which could lead to problems. The Managers are only recreated if attributes specific to that Manager are changed, otherwise the new Appender instance will reuse the previous Manager.

rgoers
  • 8,696
  • 1
  • 22
  • 24
  • 2
    Thanks for the info. Plugins? That is something new to me. Are there any examples out there that look at? – hell_storm2004 Jan 14 '20 at 10:18
  • 1
    Take a look at the file appender link in my answer and http://logging.apache.org/log4j/2.x/manual/plugins.html – rgoers Jan 14 '20 at 11:34
  • Hello @rgoers, I have a custom appender that is implemented very much like the RollingFileAppender of log4j2 but it keeps restarting after each restart or reconfiguration. I have created a separate question about it, can you please take a look? https://stackoverflow.com/questions/71124877/how-to-retain-log4j2s-plugin-configs-after-server-restart-or-altering-xml-confi?noredirect=1#comment125744077_71124877 – pouyan021 Feb 24 '22 at 07:51
2

The code supporting the accepted answer here is available in the answer by David Lopez Carrasco to another question. This code should be supplemented with clearing the logs List in-between tests and test suites (otherwise the appender would hold messages from previous loggers).

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
oskarryn
  • 170
  • 2
  • 13
  • You do now have the commenting privilege. If this is meant as a comment please delete it. If you think it can be an answer please [edit] according to [answer]. – Yunnosch Sep 09 '22 at 20:51