Reading Time: < 1 minute
At work I needed an immediate Log4J configuration which only writes error messages to file, and displays everything in console. The reason behind this need was there all the info debug messages should not be stored in log files which will gain maximum capacity and bigger file in size. So when an error occurred that is something we need to see in log files.
MainApp
public class MainApp { public static void main(String[] args) throws IOException { // Initialize logging BasicConfigurator.configure(); logger.info("info message"); logger.error("error message"); logger.debug("debug message"); logger.warn("warn message"); } }
log4j.properties
# Define the root logger log4j.rootLogger = INFO, stdout, file # Define the file appender log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.Threshold=error #Unix file location log4j.appender.file.File=/home/sampleuser/MainApp.log #Windows file location log4j.appender.file.File=C:\\MainApp.log log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Define the stdout appender log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Screen output
2015-09-09 14:19:11 INFO MainApp:30 - info message 0 [main] INFO com.tugrulaslan.MainApp - info message 2015-09-09 14:19:11 ERROR MainApp:31 - error message 3 [main] ERROR com.tugrulaslan.MainApp - error message 2015-09-09 14:19:11 WARN MainApp:33 - warn message 3 [main] WARN com.tugrulaslan.MainApp - warn message
File Output
2015-09-09 14:26:40 ERROR MainApp:31 - error message