This article describes how to use the org.apache.log4j package in Eclipse to allow log output to both the file and the console.
Before reading this article, if you do not have an environment that can output logs using the log4j package, you need to create an environment by referring to the link below. Reference article: https://qiita.com/toolate32/items/538f3a99d23a7a1f29bd
package test.project; import org.apache.log4j.Logger;
public class TestClass { public static void main(String[] args) { Logger logger = Logger.getLogger(TestClass.class.getName()); // Log output logger.info("This is info."); } }
For the time being, it is output to the console. Console output: 2017/XX/XX 14:56:09 781 INFO main TestClass - This is info.
The contents of the current log4j.xml are as follows. 1:< ?xml version="1.0" encoding="UTF-8" ?> 2:< !DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> 3:< log4j:configuration xmlns:log4j="" class="autolink">http://jakarta.apache.org/log4j/" > 4:< appender name="stdout" class="org.apache.log4j.ConsoleAppender"> 5:< param name="Target" value="System.out" /> 6:< layout class="org.apache.log4j.PatternLayout"> 7:< param name="ConversionPattern" value="%d{yyyy/MM/dd HH: mm:ss SSS} %5p %5t %c{1} - %m%n" /> 8:< /layout> 9:< /appender> 10:< category name="test.project" > 11:< appender-ref ref="stdout" /> 12:< /category> 13:< /log4j:configuration>
1:< ?xml version="1.0" encoding="UTF-8" ?> 2:< !DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> 3:< log4j:configuration xmlns:log4j="" class="autolink">http://jakarta.apache.org/log4j/" > 4:< appender name="stdout" class="org.apache.log4j.ConsoleAppender"> 5:< param name="Target" value="System.out" /> 6:< layout class="org.apache.log4j.PatternLayout"> 7:< param name="ConversionPattern" value="%d{yyyy/MM/dd HH: mm:ss SSS} %5p %5t %c{1} - %m%n" /> 8:< /layout> 9:< /appender> 4-1:< appender name="fileout" class="org.apache.log4j.FileAppender"> 5-1:< param name="File" value="logTest.log" /> 6-1:< layout class="org.apache.log4j.PatternLayout"> 7-1:< param name="ConversionPattern" value="%d{yyyy/MM/dd HH: mm:ss SSS} %5p %5t %c{1} - %m%n" /> 8-1:< /layout> 9-1:< /appender> 10:< category name="test.project" > 11:< appender-ref ref="stdout" /> 11-1:< appender-ref ref="fileout" /> 12:< /category> 13:< /log4j:configuration>
The added parts are 4-1 to 9-1, 11-1. Since the file output definition is set in 4-1 to 9-1 and the apender-ref is set to "fileout" in the 11-1st line, the log output of the 4-1 to 9-1 line definition is performed.
Now, when I try to run the above source, it is output to both the console and the log file this time.
Console output 2017/XX/XX 20:37:17 689 INFO main TestClass - This is info.
Log file output (logTest.log) 2017/XX/XX 20:26:59 660 INFO main TestClass - This is info. 2017/XX/XX 20:37:17 689 INFO main TestClass - This is info.
Recommended Posts