Skip to content

Instantly share code, notes, and snippets.

@bcalmac
Last active July 28, 2017 05:40
Show Gist options
  • Save bcalmac/9056bb3a08cede6dab7a16d589d8b92c to your computer and use it in GitHub Desktop.
Save bcalmac/9056bb3a08cede6dab7a16d589d8b92c to your computer and use it in GitHub Desktop.
What happens if stdout is redirected to the same file as a FileAppender?
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DuplicateLogging {
private static final Logger logger = LoggerFactory.getLogger(DuplicateLogging.class);
public static void main(String[] args) throws IOException, InterruptedException {
logger.info("message 1");
logger.debug("message 2");
logger.info("message 3");
logger.debug("message 4");
logger.info("message 5");
logger.debug("message 6");
logger.info("message 7");
logger.debug("message 8");
System.out.println("This goes to the console!");
}
}
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>log.txt</file>
<encoder>
<pattern>[FileAppender] %date %level %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[ConsoleAppender] %date %level %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE"/>
<appender-ref ref="STDOUT"/>
</root>
</configuration>
@bcalmac
Copy link
Author

bcalmac commented Jul 28, 2017

  • Both appenders write to the file using separate pointers (so they overwrite each other).
  • For the section that's overlapped, the console appender wins. Is it because it's slower (or faster)?

Example invocation:

bcalmac$ java -cp .:/Users/bcalmac/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/Users/bcalmac/.m2/repository/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar:/Users/bcalmac/.m2/repository/ch/qos/logback/logback-core/1.1.11/logback-core-1.1.11.jar DuplicateLogging > log.txt; cat log.txt
[ConsoleAppender] 2017-07-27 22:36:58,173 INFO message 1
[ConsoleAppender] 2017-07-27 22:36:58,175 INFO message 3
[ConsoleAppender] 2017-07-27 22:36:58,175 INFO message 5
[ConsoleAppender] 2017-07-27 22:36:58,175 INFO message 7
This goes to the console!
8,175 INFO message 5
[FileAppender] 2017-07-27 22:36:58,175 DEBUG message 6
[FileAppender] 2017-07-27 22:36:58,175 INFO message 7
[FileAppender] 2017-07-27 22:36:58,175 DEBUG message 8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment