Kwai Xiangxiang (ChineseMars@hotmail.com) June 2002
1 Overview
1.1. Background
In the application, add the logging in the application, based on three purposes: monitor changes in variables in the code, periodically recorded to files for other applications for statistical analysis, tracking code runtime trajectory, as the basis for future audits The role of the debugger in the integrated development environment, prints the debugging information of the code to the file or console.
The most common approach is to embed a lot of print statements in the code, which can be output to the console or file, which is to construct a log operation class to encapsulate such operations, not let a series of printed statements. Filled the body of the code.
1.2. Log4j Introduction
In today's reusable component development, Apache provides us with a powerful log operation package - Log4j from head to the end.
Log4j is an open source project of Apache. By using log4j, we can control the destination of log information delivery is console, file, GUI component, even set of interface servers, NT event logger, UNIX Syslog daemon, etc .; We can also control the output format of each log; to define the level of each log information, we can control the generation process of the log. What is most interesting is that these can be flexibly configured by a profile without a modification of the code.
In addition, through the log4j other language interface, you can use log4j in C, C ,. Net, PL / SQL programs, its syntax and usage, like the Java program, make multilingual distributed systems to get a uniform log component Module. Moreover, by using a variety of third-party extensions, you can easily integrate log4j to J2EE, JINI, or even SNMP applications.
The LOG4J version introduced herein is 1.2.3. The author attempts to use a simple customer / server Java program example to use and do not use log4j 1.2.3, and explain in detail the method and steps of the most commonly used LOG4J in practice. Today, it is important that log4j will be convenient to the majority of design developers. Join the team of log4j!
2. A simple example
Let's first look at a simple example, it is a client / server network program implemented with Java. Just started to use log4j, but use a series of print statements, then we will use log4j to implement its log function. In this way, everyone can clearly compare the difference between the two codes of the previous rear.
2. No log4j
2.1.1. Customer program
Package log4j;
Import java.io. *; import java.net. *;
/ ****
Client WithOut log4j p> *
Description: a sample with log4j p> * @version 1.0 * / public class clientwithoutlog4j {
/ ** * * @Param args * / public static void main (string args []) {
String Welcome = NULL; string response = null; buffredreader reader = null; printstream in = null; outputstream out = null; setputstream out = null; socket client = NULL;
Try {Client = New Socket ("LocalHost", 8001); System.out.Println ("Info: Client Socket: Client); in = client.getinputStream (); out = client.getOutputStream ();} catch IOEXCEPTION E) {System.out.println ("Error: IOException:" E); System.exit (0);
Try {reader = New BufferedReader (in); Writer = New PrintWriter (out), true
Welcome = reader.readLine (); system.out.println ("Debug: Server Says: '" Welcome "");
System.out.println ("Debug: Hello"); Writer.Println ("Hello"); response = reader.readline (); system.out.println ("debug: server responds: '" response "'" );
System.out.println ("Debug: Help"); Writer.Println ("Help"); response = reader.readLine (); System.out.println ("Debug: Server responds: '" response "'" );
System.out.println ("debug: quit"); Writer.Println ("quit");} catch (ioException e) {system.out.println ("Warn: ioException in client.in.readln ()"); System.out.println (e);} Try {thread.sleep (2000);} catch (exception ignored) {}}}}
2.1.2. Server program
Package log4j;
Import java.util. *; import java.io. *; import java.net. *;
/ ****
server without log4j p> *
description: a sample with log4j p> * @version 1.0 * / public class serverwithoutlog4j {final static int server_port = 8001; // this server's port
/ ** * * @param args * / public static void main (String args []) {String clientRequest = null; BufferedReader reader = null; PrintWriter writer = null; ServerSocket server = null; Socket socket = null; InputStream in = null OutputStream out = null;
Try {server = new serversocket (server_port); System.out.println ("Info: ServerSocket BEFORE Accept: Server); System.out.Println (" Info: Java Server WITHOUT LOG4J, ON-LINE! ");
// Wait for Client's Connection socket = server.accept (); System.out.Println ("Info: ServerSocketAfter Accept:" Server);
IN = socket.getinputStream (); out = socket.getOutputStream ();
} Catch (IOException e) {System.out.println ( "error: Server constructor IOException:" e); System.exit (0);} reader = new BufferedReader (new InputStreamReader (in)); writer = new PrintWriter ( New OutputStreamWriter (out), true
// send Welcome String to Client Writer.println ("Java Server WITHOUT LOG4J," New Date ());
While (True) {Try {// read from client clientRequest = reader.readline (); system.out.println ("debug: client says: clientRequest); if (ClientRequest.startSwith (" Help ") {SYSTEM .out.println ("Debug: OK!"); Writer.println ("Vocabulary: Help Quit");} else {if (ClientRequest.StartSwith ("quit)) {system.out.println (" debug: ok ! "); System.exit (0);} else {system.out.println (" Warn: Command '" ClientRequest " NOT Understood. "); Writer.Println (" Command' " ClientRequest " Not understand. ");}}} catch (ooexception e) {system.out.println (" Error: IException in Server " E); System.exit (0); }}}} 2.2. Migrate to log4j
2.2.1. Customer program
Package log4j;
Import java.io. *; import java.net. *;
// Add for log4j: import some packageimport org.apache.log4j.propertyConfigurator; import org.apache.log4j.logger; import org.apache.log4j.LOG4J.LOG4J.LOG4J.LOG4J.EVEL
/ ****
Client with log4j p> *
description: a sample with log4j p> * @version 1.0 * / public class clientwithlog4j {
/ * Add for log4j: Class Logger is The Central Class in The Log4j Package. We Can do Most Logging Operations by Logger Except Configuration. Getlogger (...): Retrieve A Logger by name, if not kilate for it. * / Static logger logger = logger.getlogger (clientwithlog4j.class.getname ()); / ** * * @Param args: configuration file name * / public static void main (string args [] {
String Welcome = NULL; string response = null; buffredreader reader = null; printstream in = null; outputstream out = null; setputstream out = null; socket client = NULL;
/ * Add for log4j: Class BasicConfigurator CAN Quickly Configure the package .print The information to console. * / PropertyConfigurator.configure ("Clientwithlog4j.properties);
// add for log4j: set the level // logger.setlevel ((level); ly.debug;
Try {Client = New Socket ("LocalHost", 8001);
// add for log4j: log a message with the info level logger.info ("Client Socket:" Client);
IN = client.getinputStream (); out = client.getOutputStream ();} catch (ooException e) {
// Add for log4j: log a message with the error level logger.error ("IOEXCEPTION:" E);
System.exit (0);
Try {reader = New BufferedReader (in); Writer = New PrintWriter (out), true
Welcome = Reader.Readline ();
// add for log4j: log a message with the debug level logger.debug ("Server Says: '" Welcome ""); // add for log4j: log a message with the debugl logger.debug ("Hello ");
Writer.println ("Hello"); response = reader.readline ();
// Add for log4j: log a message with the debug level logger.debug ("Server Responds: '" Response "'");
// Add for log4j: log a message with the debug level logger.debug ("help");
Writer.println ("Help"); response = reader.readline ();
// Add for log4j: log a message with the debug level logger.debug ("Server Responds: '" Response "'");
// Add for log4j: log a message with the debug level logger.debug ("quit");
Writer.println ("quit");} catch (ioexception e) {
// Add for log4j: log a message with the warn level logger.warn ("IOEXCEPTION IN Client.in.Readln ()");
System.out.println (e);} Try {thread.sleep (2000);} catch (exception ignored) {}}}}
2.2.2. Server program
Package log4j;
Import java.util. *; import java.io. *; import java.net. *;
// Add for log4j: import some packageimport org.apache.log4j.propertyConfigurator; import org.apache.log4j.logger; import org.apache.log4j.LOG4J.LOG4J.LOG4J.LOG4J.EVEL
/ ****
server with log4j p> *
description: a sample with log4j p> * @version 1.0 * / public class serverwithlog4j {
Final static int server_port = 8001; // this Server's Port
/ * Add for log4j: Class Logger is The Central Class in The Log4j Package. We Can do Most Logging Operations by Logger Except Configuration. Getlogger (...): Retrieve A Logger by name, if not kilate for it. * / static Logger logger = Logger.getLogger (ServerWithLog4j.class.getName ()); / ** * * @param args * / public static void main (String args []) {String clientRequest = null; BufferedReader reader = null; PrintWriter writer = NULL; Serversocket Server = null; socket socket = null;
InputStream IN = NULL; OUTPUTSTREAM OUT = NULL;
/ * Add for log4j: Class BasicConfigurator CAN Quickly Configure the package. Print The information to console. * / PropertyConfigurator.configure ("Serverwithlog4j.properties);
// add for log4j: set the level // logger.setlevel ((level); ly.debug;
Try {server = new serversocket (server_port);
// Add for log4j: log a message with the info level logger.info ("Serversocket Before Accept: Server);
// Add for log4j: log a message with the info level logger.info ("Java Server with log4j, on-line!");
// Wait for Client's Connection Socket = Server.Accept ();
// Add for log4j: log a message with the info level logger.info ("ServersocketAfter ACCEPT: Server);
IN = socket.getinputStream (); out = socket.getOutputStream ();
} catch (ioexception e) {
// add for log4j: log a message with the error level logger.error ( "Server constructor IOException:" e); System.exit (0);} reader = new BufferedReader (new InputStreamReader (in)); writer = new PrintWriter (New OutputStreamWriter (out), true); // send Welcome String to Client Writer.Println ("Java Server with log4j," new date ());
While (True) {Try {// read from client clientRequest = reader.readline ();
// Add for log4j: log a message with the debug level logger.debug ("Client Says:" ClientRequest);
IF (ClientRequest.startSwith ("Help")) {
// Add for log4j: log a message with the debug level logger.debug ("ok!");
Writer.println ("vocabulary: help quit");} else {if (ClientRequest.StartSwith ("quit)) {
// Add for log4j: log a message with the debug level logger.debug ("ok!");
System.exit (0);} else {
// Add for log4j: log a message with the warn level logger.warn ("Command '" ClientRequest "NOT UNDERSTOOD.");
Writer.println ("Command '" ClientRequest "' NOT Understood.");}}} catch (ooexception e) {
// Add for log4j: log a message with the error Logger.Error ("IOException in Server";
System.exit (0);}}}}
2.2.3. Profile
2.2.3.1. Client Profile
Log4j.rootlogger = info, a1log4j.appender.a1 = org.apache.log4j.consoleappender
Log4j.Appender.a1.Layout = Org.apache.log4j.patternlayout
Log4j.Appender.a1.Layout.ConversionPattern =% - 4R% -5P [% T]% 37C% 3X -% M% N
2.2.3.2. Server Program Profile
Log4j.rootlogger = info, A1
Log4j.Appender.a1 = org.apache.log4j.consoleAppender
Log4j.Appender.a1.Layout = Org.apache.log4j.patternlayout
Log4j.Appender.a1.Layout.ConversionPattern =% - 4R% -5P [% T]% 37C% 3X -% M% N
2.3. Comparison
It can be seen that the entire process of log operations using log4j is quite simple, and it is basically no increasing code quantity compared to the log information output using the system.out.println statement. Understand the importance of each log information. By controlling the configuration file, we can also flexibly modify the format, output destination, etc. of log information, and simply rely on system.out.println statement, clearly need to do more work.
Below we will use the application of log4j in front as an example, detail the main steps using LOG4J.
3. Log4j Basic Usage
LOG4J consists of three important components: the priority of log information, output destination of log information, and output format of log information. The priority of the log information is from high to Error, Warn, INFO, DEBUG, and is used to specify the importance of this log information. The output destination of log information specifies the log to print to the console or in the file; The format controls the display of log information.
3.1. Define the profile
In fact, you can also use the profile at all, but configure the log4j environment in your code. However, using the profile will make your application more flexible.
Log4j supports two configuration file formats, one is a file in XML format, one is a Java feature file (key = value). Below we describe how to use the Java feature file as a configuration file:
Configure root Logger, whose syntax is:
Log4j.rootlogger = [level], appendername, appendername, ... where Level is the priority of log records, divided into OFF, Fatal, Error, Warn, INFO, DEBUG, ALL, or your defined level. Log4J is recommended to use only four levels, priority from high to low, Error, Warn, Info, Debug. By the level defined here, you can control the switch to the corresponding level of log information in the application. For example, the INFO level is defined here, and all the DEBUG level log information in the application will not be printed. Appendername is where the specified log information is output to which place. You can specify multiple output destinations at the same time.
Configure the log information output Destination Appender, its syntax is
log4j.appender.appenderName = fully.qualified.name.of.appender.classlog4j.appender.appenderName.option1 = value1 ... log4j.appender.appenderName.option = valueN wherein, appender Log4j provided are the following: org.apache. Log4j.consoleAppender (console), org.apache.log4j.fileappender (file), org.apache.log4j.dailyrollingFileAppender (a log file is generated), org.apache.log4j.rollingFileAppender (file size is generated when the specified size is generated) A new file), org.apache.log4j.writerappender (sends log information to any specified place to any specified place), whose syntax is:
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.classlog4j.appender.appenderName.layout.option1 = value1 ... log4j.appender.appenderName.layout.option = valueN which, layout Log4j provided are the following Amount: org.apache.log4j.htmlLayout (layout in HTML table), org.apache.log4j.patternlayout (can be flexibly specified), org.apache.log4j.sImpleLayout (level and information string containing log information) ), Org.apache.log4j.ttccLayout (including information, thread, category, etc.)
3.2. Use log4j in the code
The following will describe how Log4j is used in the program code.
3.2.1. Get recorder
Using log4j, the first step is to obtain a logging device, which will be responsible for control log information. Its syntax is:
Public Static Logger getLogger (String Name), get a logger by the specified name, if necessary, create a new recorder for this name. Name generally takes the name of this class, such as:
Static logger logger = logger.getlogger (ServerWithlog4j.class.getname ()); 3.2.2. Read the configuration file
After the log recorder is obtained, the second step will configure the log4j environment, whose syntax is: BasicConfigurator.configure (): Automatically quickly uses the default Log4j environment. PropertyConfigurator.configure (String configFileName): Read the configuration file written by using the characteristic file using Java. Domconfigurator.configure (String FileName): Read the configuration file in the XML form.
3.2.3. Insert the record information (format log information)
When the top two necessary steps are performed, you can easily use different priority logging statements into any place you want to log log, whose syntax is as follows: Logger.Debug (Object Message); logger.info (Object Message ); Logger.warn; Logger.Error (Object Message);
4. Reference
If you want to know more about Log4j, visit the links mentioned below. Log4J project homepage --------------------------------------------- ------- www.log4j.orglog4j FAQ ------------------------------------- ------------------www.log4j.org/log4j/faq.html
With regard to the author of Kwai Xiangxiang, SCJP (Sun Certified Java 2 Programmer) has 7 years of well-known domestic well-known corporate work experience. The current interest is concentrated on Java's C / S, B / S large applications, you can via Chinesemars @ Hotmail. CoM and he contact him.