Objective:
The author has been in the System.out in the log, because the author most of the time is written in the Tomcat container running some small web applications, so it seems that there is no problem: the printed log can be found in the Tomcat's own log directory in some of the logs. However, the author recently contacted a project, need to write a non-dependent on the container can directly run on the system socket server program, so that I need a can hit their own log of the place, so began to learn log4j. By the way, it also compels the author to really learn about the flow, the more underlying TCP than HTTP and its corresponding socket communication, multithreading and other knowledge.
Body Start
LOG4J has released version 2.0, but the most commonly used version of log4j1.2 is still used in this example.
After the Log4j-1.2.17.jar is downloaded and added to the project, the configuration file is added to the SRC root of the Java project log4j.properties
#设置级别log4j. Rootlogger=debug,appender1# output to file (default is append here) log4j.appender.appender1= org.apache.log4j.fileappender# setting file output path Log4j.appender.appender1.File=c:/users/lixin/desktop/ myproject.log# setting file output style Log4j.appender.appender1.layout=org.apache.log4j.ttcclayout
Then test the example in one of the simplest Java programs: write a log to the desktop's Myproject.log
package Com.myproject.test; import Org.apache.log4j.Logger; public class Mytestclass { static Logger Logger = Logger.getlogger (Mytestclass. Class ); public static void main (string[] args) {System.out.println ( "Hello World" ); Logger.info (----transaction log, logging level info-----> "+" Hello World "+" <--------"
Run, display in Myproject.log:
[Main] Info com.myproject.test.mytestclass-----Transaction log, logging level info----->hello world<--------
Log4j Learning (a) The simplest example