3

In the example I am following, there is a line that goes like this in the log4j configuration file:

<Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">

I understood everything in this line except for follow="true", I have read the description of this particular parameter on the official website: This Website. I also tried searching in other websites, but to no avail.

The description goes like this: follow parameter

This description got me confused, What do they mean by "honors reassignments....." , what is its purpose, what happens if I change it to false.

SpaceSloth
  • 85
  • 7

1 Answers1

4

The System.out property is not read-only and can be reassigned through System#setOut. With follow="true" the appender will send the message to the current value of System.out, whereas with follow="false" logs will be sent to the original value of System.out.

You can test the two behaviors with:

      // This performs automatic initialization
      final Logger logger = LogManager.getLogger(Log4j2Test.class);
      // System.out is attached to the JVM's `stdout`
      logger.warn("Sent to 'stdout'");
      // Reassignement of System.out
      System.setOut(new PrintStream(new File("file.log")));
      // System.out is attach to the file 'file.log'
      logger.warn("Sent to 'file.log'");

From a practical perspective performance with follow="true" is worse than with follow="false" and System.out is rarely reassigned.

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43
  • So, I tried your example, and this is the behavior that I saw: with `follow="false":` The `logger.warn("Sent to 'file.log'");` was thrown in the console, and the log file was empty. with `follow="true"`: The `logger.warn(.....)` was thrown in the file, after being created. So, if I have to make `follow=false`, how am I supposed to write to a file, using Rolling File Appender, or, is the purpose of setting `follow="true"` is to write to a file, in xml syntax. – SpaceSloth Feb 18 '22 at 10:25
  • @SpaceSloth: in the example above I redirect `System.out` to a file only for demonstration purposes (so you can see what happends if `System.setOut` is called). It is not a good practice. If you want to log to a console (terminal), use the `ConsoleAppender`. If you want to log to a file, use the `(Rolling)FileAppender`. As you can see in the documentation the latter does not have a `follow` property, this is characteristic to the console appender. – Piotr P. Karwasz Feb 18 '22 at 15:08
  • My problem here is that most examples use console appender like this ` ` And I actually have Rolling file appender `` – SpaceSloth Feb 21 '22 at 08:12
  • With a rolling file appender there is no `follow` attribute. It opens a file for writing and always sends messages to that file until rollover occurs. – Piotr P. Karwasz Feb 23 '22 at 06:45