Log4j is a log record tool that can replace information such as System.out.Println, and you can define the level of information. You can display the desired information as needed. More importantly, reasonable use of this tool is a good programming good habit This is also a little experience in recent projects:
1) We use the cumbersome WSAD, if we use debug mode to develop, develop the habit of watching the log, can accelerate the speed of development, of course, I mean not to replace the debugging tool, this depends on the log The detailed extent of writing, and especially complex procedures, it has to be debugged (unless you willing to spend time on the log log, or put the simple design is simple), but in any case, it should be used in conjunction with both. 90% of time look at the log, 10% of the time debugging mode
2) The number is not only used for debugging. We developed the basic class developed by others. All are packaged into JAR. If you don't look at the log information during the development process, you may say that you can see the original Document, but after all, it has limited time, which also gives us some prompt information. When we develop API to use it, write a good log information, provide convenience for others.
Said so much nonsense, start entering the topic
A) installation
Download the log4j distribution from http://jakarta.apache.org/log4j/docs/download.html. Unzip the archive file to the appropriate directory. Add files DIST / lib / log4j-1.2.9.jar to the ClassPath environment variable. (In the eclipse, you copied the lib directory under your works in your work, then reference it in the build path of the project)
B) 3 core concepts of log4j
B1) Logger: Log Writer
The Logger object is used to replace the log writing device for SYSTEM.OUT or System.ERR to output log information for programmers.
Logger output method
Logger class objects provide a range of methods for programmers output log information.
// Printing methods: public void debug (Object msg); public void debug (Object msg, Throwable t); public void info (Object msg); public void info (Object msg, Throwable t); public void warn (Object msg) ; public void warn (Object msg, Throwable t); public void error (Object msg); public void error (Object msg, Throwable t); public void fatal (Object msg); public void fatal (Object msg, Throwable t); // Generic Printing Method: Public Void Log (Level L, Object MSG);
// Printing methods: public void debug (Object msg); public void debug (Object msg, Throwable t); public void info (Object msg); public void info (Object msg, Throwable t); public void warn (Object msg) ; public void warn (Object msg, Throwable t); public void error (Object msg); public void error (Object msg, Throwable t); public void fatal (Object msg); public void fatal (Object msg, Throwable t); // Generic printing method: public void log (Level l, Object msg); // Printing methods: public void debug (Object msg); public void debug (Object msg, Throwable t); public void info (Object msg); public Void Info (Object Msg, Throwable T); Public Void Warn (Object MSG); Public Void Warn (Object MSG, Throwable T); Public Void Error (Object MSG); Public Voi D Error (Object Msg, Throwable T); Public Void Fatal (Object MSG); Public Void Fatal (Object Msg, Throwable T); // Generic Printing Method: Public Void Log (Level L, Object MSG);
Logger naming rules
Logger is identified by a String class, and the name of the logger is sensitive, and the relationship between the names between the names, the child name has a parent name as a prefix, separated by the order. Such as: x.y is the father of x.y.z.
Root logger (root logger) is all ancestors of the Logger, which has the following properties: 1) It always exists; 2) It is not available through the name.
Get root logger by calling public static logger.getrootLogger; obtains a named logger by calling public static logger logger.getlogger or public static logger logger.getlogger (Class Clazz). The latter is equivalent to calling Logger.getLogger (Clazz.getName ()).
In an object, the class belonging to the object belongs as a parameter, calling the Logger.getLogger (Class Clazz) to get the Logger's method for named Logger, which is known. Log Level
Each Logger is assigned a log level to control the output of log information. The Logger that is unassigned will inherit it will inherit its nearest parent Logger.
Each output to the logger log request also has a Level, if the Request's Level is greater than equals the Logger's level, the request will be processed (called Enabled); otherwise the request will be ignored. Therefore, you can know:
The lower the Logger's Level, the higher the Logging Request's Level, the higher the Logging Request, and the, the better the logger (Logger), then it will inherit the nearest ancestral level. Therefore, if you create a logger (Logger) in the package com.foo.bar and there is no level, it will inherit the level of the logger (Logger) created in the package com.foo. If you do not create a logger (Logger) in com.foo, the logger (Logger) created in com.foo.bar will inherit the level of the root logger (Logger), root logger (Logger ) Is often instantiated, and its level is Debug.
Five levels are predefined in the Level class, and their size relationships are as follows:
Level.all There are many ways to create a logger (Logger). The following method can retrieve the root logging device: logger logger = logger.getrootlogger (); You can also create a new log recorder: Logger logger = logger.getlogger ("MyLogger"); Comparative usage is to instantify a static global log recorder based on the class name: static logger logger = logger.getlogger; All of these logists called "Logger" can be set by the following method: Logger.Setlevel ((Level) Level.warn; The lower code will use the class you belong to the parameters, create a logger, enable the default configuration, set its Level and output a number of logging requests to it. Import org.apache.log4j.logger; import org.apache.log4j.basicconfigurator; import org.apache.log4j.level; public class Log4jTest {public static void main (String argv []) {// Create a logger by the name of class Log4jTest Logger logger = Logger.getLogger (Log4jTest.class);. // Use the default configuration BasicConfigurator.configure (. ); // set the logger level to level.info logger.Setlevel (Level.info); // this request will be disabled Since Level.debug 1) Call the logger.getlogger (String Name) with the same name parameters will return references to the same Logger. Therefore, you can configure the logger in one place, get a configuration in another place, without passing the Logger reference. 2) The creation of Logger can be created after the parent Logger can be created after any order, ie, the parent Logger can be created. Log4j will automatically maintain the inheritance tree of Logger. B2) Appender: log destination Each Logger can have one or more appenders, each Appender represents an output destination of a log, such as Console or a file. You can add an appender to logger using Logger.AddaPpender (Appender App); you can use Logger.RemoveAppender (Appender App) to remove an Appender for Logger. By default, the Logger's Additive flag is set to True, indicating that the sub-logger will inherit all Appenders of the parent Logger. This option can be reset, indicating that the sub-logger will no longer inherit the Appenders of the father's Logger. Root Logger has a consolerapnder for the target for System.out, so all Loggers will inherit the appender by default. 1) ConsoleAppender: Use the user-specified layout (Layout) output log event to System.out or System.err. The default goal is System.out. 2) DailyRollingFileAppender Extend FileAppender, so multiple log files can be loop logging in a user selected frequency. 3) FileAppender writes a log event into a file 4) RollingFileAppender Extended FileAppender backup capacity reaches a certain size log file. 5) WriteraPpender writes the log event to Writer or OutputStream according to the user's choice. 6) SMTPAPPENDER When a specific log event occurs, it is generally meant to send an email when an error or major error occurs. 7) SocketAppender Sends a log event (usually the network socket node) to the remote log server. 8) SocketHubappenders Send a log event (usually the network socket by network socket by network socket by network socket.). 9) Syslogappender sends a message to the background Elves program (Daemon) of the remote asynchronous log. 10) TelNetAppender Log4j appender dedicated to read-only network sockets. You can also implement the Appender interface, create an Appender that logs in your own way. ConsoleAppender ConsoleAppender can be created in this way: ConsoleAppender appender = new configuration (new pattern); Created a console appender with a default PatternLayout. It uses the default system.out output. FileAppender FileAppender can be created in this way: FileAppender appender = null; try {appender = new fileappender (new pattern ");} catch (exception e) {} The constructor used above: FileAppender (Layout Layout, String FileName) instantizes a FileAppender and opens the file specified by the Variable "FileName". Another useful constructor is: FileAppender (Layout Layout, String FileName, Boolean Append) instantizes a FileAppender and opens the file specified by the variable "filename". This constructor can also choose whether to add a specified file. If there is no value, then the default method is to append. Writerappender WriteraPpender can be created in this way: Writerappender appender = null; try {appender = new Writerappender (new pattern ");} catch (exception e) {} This WRITERAPPENDER uses the constructor with PatternLayout and OutputStream parameters. In this case, FileOutputStream is used to output a file. Of course, it also has other available constructor. B3) LAYOUT: Log formatter Every appender is connected to a Layout; the task of layout is to format the user's logging request, and the Appender task is to send the Layout's formatted output content to the specified destination. Currently, Log4j has three types of layout: 1) HTMLLAYOUT format log output is an HTML form. 2) PatternLayout format the log output according to the specified conversion mode, or use the default conversion mode if no conversion mode is specified. 3) SimpleLayout format the log output in a very simple way, it prints the level Level, followed by a dash "-", and finally the log message SIMPLELAYOUT and FILEAPPENDER import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.apache.log4j.FileAppender; public class simpandfile {static Logger logger = Logger.getLogger (simpandfile. class); public static void main (String args []) {SimpleLayout layout = new SimpleLayout (); FileAppender appender = null; try {appender = new FileAppender (layout, "output1.txt", false);} catch (Exception e ) {} Logger.addappender; logger.setlevel ((Level) Level.debug; logger.debug ("Here Is Some Debug"; Logger.info ("Here Is Some Info"); Logger.warn "Here Is Some Warn"; Logger.Error ("Here Is Some Error"; Logger.FATAL ("Here Is Some Fatal");}} HTMLLAYOUT and WRITERAPPENDER import java.io *;. import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.HTMLLayout; import org.apache.log4j.WriterAppender; public class htmlandwrite {static Logger logger = Logger.getLogger (htmlandwrite.class); public static void main (String args []) {HTMLLayout layout = new HTMLLayout (); WriterAppender appender = null; try {FileOutputStream output = new FileOutputStream ( "output2.html"); appender = New Writerappender (Layout, Output); (Exception E) {} Logger.Addappender; Logger.Setlevel ((Level) Level.debug; Logger.debug ("Here Is Some Debug"; Logger. INFO ("Here Is Some Info"); Logger.warn ("Here Is Some Warn"); Logger.Error ("Here Is Some Error"); Logger.Fatal ("Here Is Some Fatal");}} Patternlayout and ConsoleAppender import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.ConsoleAppender; public class consandpatt {static Logger logger = Logger.getLogger (consandpatt. Class); public static void main (string args []) {// Note,% N IS newline string pattern = "MilliseConds Since Program Start:% R% N"; Pattern = "ClassName of Caller:% C% N" Pattern = "DATE IN ISO8601 FORMAT:% D {ISO8601}% N"; Pattern = "Location of Log Event:% L% N"; Pattern = "Message:% M% N% N"; PatternLayout Layout = new PatternLayout (pattern); ConsoleAppender appender = new ConsoleAppender (layout); logger.addAppender (appender); logger.setLevel ((Level) Level.DEBUG); logger.debug ( "Here is some DEBUG"); logger.info ("Here Is Some Info"); Logger.Warn ("Here Is Some Warn"); Logger.Error ("Here Is Some Error"); Logger.FATAL ("Here Is Some Fatal");}} : The code in B2) and B3) and B1) All related code in the configuration, generally unnecessary in actual development, can be customized by the configuration file, so that it is convenient for maintenance, the above example is mainly used for understanding Not finished, to be renewed ... See the next article about the configuration file