replace the use of log4j system.out.print

I. Introduction output in the program has three purposes: First, operation monitoring program; First the operation of the program record to the log file for future view; first as a debugger. But the information output means is not limited to System.out.println () or System.out.print (), also logging tools to choose from. And System.out.pringln () and System.out.print () compared to control the output logging tools level, and can be in the configuration file to set the output level, so that the information in the program development phase can be released after by setting the output level to eliminate the out, but not if the code were amended. Now many of the popular logging tool, Log4J is one of the best.
Log4J is organized by the famous Apache open-source release of a logging tool, for Java coders to do with the log output can be obtained for free from the Web http://logging.apache.org/log4j, the latest version 1.2.11. Access logging-log4j-1.2.11.zip file, unzip, needed is one of the log4j-1.2.11.jar file, the file into a specific folder backup, I put my machine G: \ YPJCCK \ Log4J \ lib folder.
Here is the Eclipse IDE and selected JBuilder. Eclipse 3.0.1 with the additional language packs can be downloaded to the www.eclipse.org Web site; JBuilder with the JBuilder 2005.
Second, configure the library opens the following Eclipse or JBuilder.
If you are using Eclipse, then Eclipse opens, click the menu "File" -> "New" -> "project", open the "New Project" dialog box:

Please select "Java Project", click "Next" and enter "New Java Project" dialog box:

In this dialog box, set the name of the project need and project directory, I named my project Log4JTest, directory G: \ YPJCCK \ Log4J \ Eclipse \ Log4JTest. Set up click on "Next" to enter the next window. In this window, select the named "Library" tab, then click on "Add External JAR" button to save a specific folder log4j-1.2.11.jar file references come.

Set up, click "Done", thus, already use Log4J in Eclipse environment.
If you are using JBuilder, then JBuilder opens, click the menu "Tools" -> "Configure" -> "Libraries", open the "Configure Libraries" dialog box:

Click "New" button, open the "New Library Wizard" dialog box:

Use the "Add" button to save a specific folder log4j-1.2.11.jar file reference in, and set the Name, the name of the library, I will Name set to Log4J. Set up and click "OK" button to return to "Configure Libraries" dialog box, then click "OK" button, then the JUnit class library which has been added to JBuilder.
The following continue to create a project in JBuilder. Click on the menu "File" -> "New Project", open the "Project Wizard" dialog box:

In this window, set the project name and storage directory, my project name is still Log4JTest, the path is G: / YPJCCK/log4J / JBuilder/Log4JTest. Click "Next" to enter the next window:

In this window, select "Required Libraries" tab, click the "Add" button, just set the JUnit library reference come. Then click "Next" button to enter the next window:

In this window using the mouse click Encoding drop-down list box, then click the "G" key, select the appropriate option, then the project was set character set GBK up. If you do domestic projects, this is definitely a good habit. Finally click "Finish", the project created.
Third, write a simple example to use in understanding the Log4J before writing a simple example, in order to have perceptual knowledge of the Log4J.
If you are using Eclipse, please click on the "File" -> "New" -> "Class", open the "New Java Class" dialog box, set the package to piv.zheng.log4j.test, the name Test, and to ensure that "public static void main (String [] args) "option is selected; If you are using JBuilder, please click the" File "->" New Class ", open the" Class Wizard "dialog box, set the Package to piv.zheng.log4j. test, Class name for the Test, and to ensure that "Generate main method" option is selected. Set is complete, click "OK". Code:
package piv.zheng.log4j.test;

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.ConsoleAppender;

public class Test (

public static void main (String [] args) (
SimpleLayout layout = new SimpleLayout ();

ConsoleAppender appender = new ConsoleAppender (layout);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.setLevel (Level.FATAL);

log.debug ("Here is DEBUG");
log.info ("Here is INFO");
log.warn ("Here is WARN");
log.error ("Here is ERROR");
log.fatal ("Here is FATAL");
)
)
Thus, the sample prepared. Click the Run button next to the inverted triangle, select "Run as" -> "2 Java applications" (Eclipse), or in the Test category tab and click on the shortcut menu in tune out, click "Run using defaults "(JBuilder), run the program, observe the information output from the console.
4, Log4J entry effects seen after running the program may wonder why the console output only a "FATAL - Here is FATAL" such a message, and program code log.debug (), log.info () and other methods also set up similar content, but not out? The answer is simple, but before they are published, the first to know about the use of Log4J.
Please see front of the sample code, you will find the sample used in the Logger, Level, ConsoleAppender, SimpleLayout four categories. Most of them use the Logger class, or even the output log information is also the fatal object in its set method, then the Logger what exactly is it? In fact Logger is the legendary logger (in the Log4J called Category), created in several ways:
1. Root Category, created by default, access methods:

Logger log = Logger.getRootLogger ();

2. User-created Category, method:

Logger log = Logger.getLogger ("test");

Where the string test for the Category set name. Category name allows the use of any characters, but case-sensitive, for example:

Logger l1 = Logger.getLogger ("x");
Logger l2 = Logger.getLogger ("X");

l1 and l2 are two Category; and if the name is identical, for example:

Logger l1 = Logger.getLogger ("x");
Logger l2 = Logger.getLogger ("x");

l1 and l2 is the same Category. In addition, the symbol "." In the Category's name has a special role, this will be introduced in the behind.
3. And Method 2 is similar only parameter replaced by the string class object, its purpose is to get through the class object class's full name. This method is commonly used, the sample is used in this method.
Category is how to output information so it? In fact, the sample used in debug, info, warn, error, fatal and other five methods are used to output information. What, how much? The reason is simple, Log4J support the classification output. Log4J output level five, from low to high followed DEBUG (debug), INFO (information), WARN (warning), ERROR (error) and FATAL (fatal), respectively, corresponding with the above method. When the output level set to DEBUG, the above methods can be output when the output level set to INFO, then the method can not only debug output, and so on, when the output level is set to FATAL, the method can only fatal output of the. Now look back, front, why is only set to fatal method of information is not difficult to understand the output, and examples in this line of code:

log.setLevel (Level.FATAL);

It is this line of code to log the output level of the object set into FATAL. For the log object is used to set the output level when a Level class that defines DEBUG, INFO, WARN, ERROR, FATAL static objects such as five, with five output levels correspond. In addition, Level there are two special static object ALL and OFF, the former method allows all output, its level in fact lower than the DEBUG; which will ban all the way to output, its level is higher than FATAL. In addition to the example in front of the five methods used, Logger also provides five methods of overload to the output, while an exception to fatal method example:

log.fatal ("Here is FATAL", new Exception ("Exception"));

After the implementation of output:
FATAL - Here is FATAL
java.lang.Exception: Exception
at piv.zheng.log4j.test.Test.main (Test.java: 24)
Similar to other methods. In addition, Logger also provides a log method, which is not targeted at any output level, need to call settings, such as:

log.log (Level.FATAL, "Here is FATAL");
log.log (Level.FATAL, "Here is FATAL", new Exception ("Exception"));

Although the general log convenient method than other methods, but allow you to set levels, the log method instead of the often more flexible than other methods, even when the output level for the OFF output. But log method is to output to the user-defined level of use, and the purpose of the establishment OFF the output level is also in order not to export any information, so please do not use the log method to output OFF.
In addition, Category of the output level is not to be, If not set, child Category Category will default to the output level of the parent if the parent did not set the Category, and then on a Category on the use of setting, up until the root Category. Root Category default output level is DEBUG, so in the example that if "log.setLevel (Level.FATAL);" comment out a line, all methods will be output.
The following outlines the Log4J in the Category of inheritance. In fact, the existence of Log4J in Category inheritance relationship between the root Category created by default, is the highest level of Category, user-created Category are inherited from it. Category created between the user there are inheritance, for example:

Logger lx = Logger.getLogger ("x");
Logger lxy = Logger.getLogger ("xy");
Logger lx_y = Logger.getLogger ("xy");
Logger lx_z = Logger.getLogger ("xz");
Logger lx_y_z = Logger.getLogger ("xyz");

One lx_y, lx_z is lx sub Category, but lx_y_z is lx_y sub Category. But lxy not lx sub Category. Maybe a bit messy and the following one by one to see. First look and lx_y, lx_z the name of the corresponding Category "xy" and "xz ","." what is ahead," x ", which shows with the name" x "in the Category corresponding to lx is their parent Category; and with the corresponding Category lx_y_z name "xyz", the last one "." ahead of what is, "xy", which shows the parent lx_y is lx_y_z Category; As lxy, as corresponding Category name "xy" is not between ".", so it is a lx at the same level of Category, his father is the root Category Category device. There is also a situation, such as a name for the "ab" in the Category, if there is no name for the "a" of the Category, then its parent Category is the root Category. Front said, "." In the Category name has a special role, in fact, the role is inherited. At this point, why use the class object to create a Category it is not hard to understand.
However, the only Category is unable to complete the information output, but also for the Category Add Appender, the Category of the output source. Examples of using front ConsoleAppender, which will be designated Category information output to the console. In fact, there are many Log4J Appender provided, where a few commonly used options are described.
1. org.apache.log4j.WriterAppender, the user can select the information output to the Writer or OutputStream.
Sample code:
SimpleLayout layout = new SimpleLayout ();

/ / Output to the file, OutputStream sample WriterAppender appender1 = null;
try (
appender1 = new WriterAppender (layout, new FileOutputStream ("test.txt"));
)
catch (Exception ex) ()

/ / Output to the console, Writer example WriterAppender appender2 = null;
try (
appender2 = new WriterAppender (layout, new OutputStreamWriter (System.out));
)
catch (Exception ex) ()

/ / Category support multiple targets simultaneously output Logger log = Logger.getLogger (Test.class);
log.addAppender (appender1);
log.addAppender (appender2);

log.debug ("output");
This example comes from the first example of modification, not set the output level, and added to the Category two output sources, running in the console output "DEBUG - output", and the project directory generated test.txt file The document also records the "DEBUG - output". To test.txt file into the other path, such as f:, will be "test.txt" to "f: / test.txt", and if e: under the temp folder, it changed to "e : / temp / test.txt ". Behind FileAppender, RollingFileAppender and DailyRollingFileAppender set targets file can also be written in this way.
2. org.apache.log4j.ConsoleAppender, the console output, inherited WriterAppender, front of the sample is that it uses.
3. org.apache.log4j.FileAppender, output to the file, but also inherited WriterAppender.
Sample code:
SimpleLayout layout = new SimpleLayout ();

/ / If the file does not exist, create the file, if the file already exists append to file information FileAppender appender = null;
try (
appender = new FileAppender (layout, "test.txt");
) Catch (Exception e) ()

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
This example also comes from the first example of modification to run the project directory will generate test.txt file, the file record with "DEBUG - output". Re-run the program, view the file, then "DEBUG - output" has two lines.
In addition, FileAppender there is a structure:

FileAppender (Layout layout, String filename, boolean append)

And examples of similar, but more of a boolean type parameter append. append parameter is a switch used to set when the program restart, and the target file already exists, additional information to the target file or overwrite the original message, when the value is true, the additional, which is FileAppender default, when the value is false, are covered. In addition, FileAppender also provides setAppend way to set the append switch.
4. org.apache.log4j.RollingFileAppender, inherited FileAppender, is output to the file, but file size can be restricted. When the file size exceeds the limit, the file will be converted to a backup file or delete, then re-generate. Change or delete files and set the maximum number of backup files, and when the number is greater than 0 on to the backup file, otherwise the (less than or equal to 0) to delete, the default number of backup files is 1. Convert the backup file is very simple to modify the file name, in the original file name after ".1", such as file test.txt, after the file name to backup file "test.txt.1". However, if the backup file the same name already exists, it will first delete or rename the backup file, which also set the maximum number of backup files, if the maximum number of the deleted or renamed. If the backup file name change when they encounter the same situation, same approach is used, and so on, until it reaches the set maximum number of backup files. Backup file name change is also very simple to add an extension, such as test.txt.1 file renamed into test.txt.2, test.txt.2 file renamed into test.txt.3.
Sample code:
SimpleLayout layout = new SimpleLayout ();

/ / If the file does not exist, create the file, if the file already exists append the contents of the file RollingFileAppender appender = null;
try (
appender = new RollingFileAppender (layout, "test.txt");
) Catch (Exception e) ()
/ / Limit the number of backup files, in this case two appender.setMaxBackupIndex (2);
/ / Restrict the target file size, bytes, in this case is 10 bytes appender.setMaximumFileSize (10);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);

log.debug ("output0");
log.debug ("output1");
log.debug ("output2");
Program runs, it will generate the project directory test.txt, test.txt.1 and test.txt.2 three documents, including the contents of test.txt is empty, then two files were recorded "DEBUG - output2" and "DEBUG - output1", this is how it? Since the original target file size is limited to 10 bytes, while the three methods used log.debug information output by more than 10 bytes, thus leading to three backup file conversion, so the contents of test.txt is empty. The maximum number of backup files is set to 2, so the first backup file conversion was deleted, then two is preserved. In addition, the backup file test.txt is first converted into test.txt.1, and then to test.txt.2, so the content of the final test.txt.2 "DEBUG - output1", and test.txt. 1 is "DEBUG - output2", Do not confuse this point.
In addition, RollingFileAppender also provides two methods:
(1) setMaxFileSize, function and setMaximumFileSize the same, but the parameters are strings, there are two situations: First, only by numbers, by default, in bytes, for example, "100" means that restrictions on file size is 100 bytes; 1 by the numbers and storage units, such as "1KB", "1MB", "1GB", in which units are not case sensitive, respectively limit the file size is 1K, 1M, 1G.
(2) rollOver, manually target files to the backup file, to use more flexible and applicable to complex situations.
Sample code:
SimpleLayout layout = new SimpleLayout ();

RollingFileAppender appender = null;
try (
appender = new RollingFileAppender (layout, "test.txt");
) Catch (Exception e) ()
appender.setMaxBackupIndex (2);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);

log.debug ("output0");
appender.rollOver ();
log.debug ("output1");
appender.rollOver ();
log.debug ("output2");
appender.rollOver ();
Where no restrictions on the target file size, but the program runs, the effect is the same as the previous example.
5. org.apache.log4j.DailyRollingFileAppender, also inherited FileAppender, and is also output to the file, but will set the time according to the frequency generated backup files.
Time and Frequency Format Description:
'.' Yyyy-MM, monthly production, generation time after midnight the last day of each month, for example, test.txt in the July 31, 2005 after midnight will be renamed test.txt.2005-07, and then rebuilt.
'.' Yyyy-ww, according to Zhou Shengcheng generate time every Saturday after midnight, for example, test.txt in the August 13, 2005 after midnight will be renamed test.txt.2005-33, 33, said 33 year weeks.
'.' Yyyy-MM-dd, by day generation, generation time is after midnight every day, such as August 16, 2005 after midnight, test.txt will be renamed test.txt.2005-08-16.
'.' Yyyy-MM-dd-a, is generated by the day, but generates twice daily, once after 12:00, after midnight once, such as test.txt in at 12 o'clock on the August 16, 2005 after will be renamed test.txt.2005-8-16-AM, will be renamed after midnight test.txt.2005-8-16-PM.
'.' Yyyy-MM-dd-HH, generated by the hour, for example, test.txt in at 12 o'clock on the August 16, 2005 after being renamed test.txt.2005-8-16-11.
'.' Yyyy-MM-dd-HH-mm, according to minutes to generate, for example, test.txt in at 12 o'clock on the August 16, 2005 after being renamed test.txt.2005-8-16-11-59.
Sample code:
SimpleLayout layout = new SimpleLayout ();

DailyRollingFileAppender appender = null;
try (
appender = new DailyRollingFileAppender (layout, "test.txt", "'.' yyyy-MM-dd-HH-mm");
) Catch (Exception e) ()

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Upon completion of running the program code, such as running again after a minute, because I was in at 3:42 p.m. on the 17 August, 2005 points for the first time run the program, so the project directory, and finally there are two files test.txt test.txt. 2005-08-17-15-42.
6. org.apache.log4j.AsyncAppender, for managing different types of Appender, can simultaneously output to multiple sources, but its implementation is asynchronous.
Sample code:
SimpleLayout layout = new SimpleLayout ();

/ / To the console output ConsoleAppender appender1 = null;
try (
appender1 = new ConsoleAppender (layout);
) Catch (Exception e) ()

/ / To the file output FileAppender appender2 = null;
try (
appender2 = new FileAppender (layout, "test.txt");
) Catch (Exception e) ()

/ / Use AsyncAppender simultaneously to multiple target output AsyncAppender appender = new AsyncAppender ();
appender.addAppender (appender1);
appender.addAppender (appender2);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
In addition, AsyncAppender and Logger offer more ways to manage the Appender, such as getAppender, getAllAppenders, removeAppender and removeAllAppenders, were used to obtain the specified Appender, get all the Appender, remove and remove all of the specified Appender Appender.
7. org.apache.log4j.jdbc.JDBCAppender, the information output to the database.
Sample code:
JDBCAppender appender = new JDBCAppender ();
appender.setDriver ("com.mysql.jdbc.Driver");
appender.setURL ("jdbc: mysql: / / localhost: 3306/zheng");
appender.setUser ("root");
appender.setPassword ("11111111");
appender.setSql ("insert into log4j (msg) values ('% m')");

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
The database used here is the MySQL 5.0.4beta, the user name root, password 11111111, I built a library in which the zheng, including table log4j, the table has only one field msg, type varchar (300). In addition, in this case the JDBC driver can be used to download from http://dev.mysql.com/downloads/connector/j/3.1.html, version 3.1.8a, download mysql-connector-java-3.1.8a.zip file After decompression, requires one of the mysql-connector-java-3.1.8-bin.jar file. Next, look at the code. As JDBCAppender PatternLayout internal default output format, so here is useless to SimpleLayout, but appender.setSql the set of SQL statements that PatternLayout required format string, which therefore only "% m" such a character, the PatternLayout behind the introduction of specific content. After the implementation, adding a record table log4j, says "output".
8. org.apache.log4j.nt.NTEventLogAppender, the Windows NT system log output.
Sample code:
SimpleLayout layout = new SimpleLayout ();

NTEventLogAppender appender = new NTEventLogAppender ("Java", layout);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Note To complete this sample, needed to the C: \ WINNT \ system32 folder (my operating system installed in the C: \) to copy a file named NTEventLogAppender.dll. If you like me to use the Log4J 1.2.11, it really does not live, Log4J 1.2.11 did not provide the file. Although the logging-log4j-1.2.11.zip file extracted, under which the src \ java \ org \ apache \ log4j \ nt folder to have a make.bat file can be compiled out after the execution of the file, but also need to configure too much trouble. Fortunately, there are many roads to Rome, 1.2.11 is not, for 1.2.9, you can download from the http://apache.justdn.org/logging/log4j/1.2.9, download extract the logging-log4j-1.2 .9. zip file, in the under src \ java \ org \ apache \ log4j \ nt folder to find NTEventLogAppender.dll, copied in the past on it. Program execution, open the "Event Viewer", select "Application Log", which records a Java source, this record is just the output of the information.
9. org.apache.log4j.lf5.LF5Appender, implementation will pop up a window, the information in the window display in tabular form.
Sample code:
LF5Appender appender = new LF5Appender ();
Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Layout to format the output as LF5Appender need information, so there are no settings. In addition LF5Appender setMaxNumberOfRecords also provides a method to limit the information displayed in the table rows.
10. org.apache.log4j.net.SocketAppender, to send the log to the server socket mode, then the information output from the server.
Sample code:
/ / Specify the server address and port to connect, here is the machine using port 9090 SocketAppender appender = new SocketAppender ("localhost", 9090);
Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
SocketAppender without setting Layout, because SocketAppender not responsible for output. So how do you see the message output effect? This requires a SocketServer and SimpleSocketServer.
Sample Code 1:
package piv.zheng.log4j.test;

import org.apache.log4j.net.SocketServer;

public class TestServer (
public static void main (String [] args) (
SocketServer.main (new String [] ("9090", "test.properties", "G: / YPJCCK/Log4J"));
)
)
This is SocketServer example. SocketServer only a static method main, this approach means that SocketServer can not only be called in the code, you can also use the java command. main method is only one parameter is a string array, but requires the existence of three elements: element 1 is used to specify the port, in this case 9090; element 2 is used to specify the output when the configuration file, the file on the project directory , in this case the use of test.properties as follows:
log4j.rootLogger =, console
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout = org.apache.log4j.SimpleLayout
The configuration specifies the format SocketServer use ConsoleAppender to SimpleLayout output; element 3 is used to specify a path to store. Lcf file, I specified that the machine G: / YPJCCK/Log4J folder. . Lcf file is used when the output of the configuration file, format and elements of two as specified configuration file, but test.properties is the default configuration file, or when. Lcf file not found when using the. So. Lcf file to name it? In fact. Lcf file name is not arbitrary since, when SocketAppender and SocketServer establish a connection, SocketServer will get SocketAppender where the IP address of the computer and network ID, and format it into a "network ID / IP address" such a string , then get one of the network ID for. lcf file name of the Lord, such as "zhengyp / 127.0.0.1", which "zhengyp" is the main file name, and then under the file name to invoke the appropriate. lcf file. This means that different computers can provide different configuration files, so that the information have different effects on output. In addition, SocketServer also called generic.lcf a default file, used to handle network ID for less than or other circumstances, this case is that this document is as follows:
log4j.rootLogger =, console
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern =% m% n
The configuration specifies the format SocketServer use ConsoleAppender to PatternLayout output. Please run the program to run SocketServer, then run SocketAppender. SocketAppender after running, you can see the output from the console SocketServer information was.
Sample Code 2:
package piv.zheng.log4j.test;

import org.apache.log4j.net.SimpleSocketServer;

public class TestServer (
public static void main (String [] args) (
SimpleSocketServer.main (new String [] ("9090", "test.properties"));
)
)
This is SimpleSocketServer example, compared with SocketServer only allows you to specify a default configuration file, which can not be used on different computers with different configuration files.
11. org.apache.log4j.net.SocketHubAppender, is also send the log to a socket, but SocketAppender contrary, SocketHubAppender is a server-side, not the client.
Sample code:
/ / Specify the server port, used here is the native 9090 ports SocketHubAppender appender = new SocketHubAppender (9090);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
while (true) (
Thread.sleep (1000);
log.debug ("output"); / / output)
Once the operation began as SocketHubAppender send a message, regardless of whether or not the recipient, so here a while statement and conditions of use set to true to ensure the program running. However, to ensure the performance, there also used Thread.sleep (1000), this procedure once per cycle are sleep 1 second, if the machine performance is not good, the value can also be re-established bigger. In addition, SocketHubAppender not responsible for the output, so also do not need to set the Layout. So how do you see the message output effect? Here I wrote a client program, the code is as follows:
package piv.zheng.log4j.test;

import java.net.Socket;
import java.lang.Thread;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.net.SocketNode;

public class TestClient (
public static void main (String [] args) throws Exception (
/ / Create the client socket object Socket s = new Socket ("localhost", 9090);
/ / Call the configuration file PropertyConfigurator.configure ("test.properties");
/ / From the socket to restore Logger, and output new Thread (new SocketNode (s, LogManager.getLoggerRepository ())). start ();
)
)
As SocketHubAppender and SocketAppender like to send is SocketNode object, so the preparation of the program SocketServer reference source. In addition, the configuration file directly here, using the example of test.properties file. Please run the program to run SocketHubAppender, then run the client program, then the console from the client can see the effects.
13. org.apache.log4j.net.TelnetAppender, and SocketHubAppender somewhat similar, but also as a server to send information, but not SocketNode TelnetAppender send objects, but the Category the output.
Sample code:
SimpleLayout layout = new SimpleLayout ();

TelnetAppender appender = new TelnetAppender ();
appender.setLayout (layout); / / Set Layout
appender.setPort (9090); / / set the port number appender.activateOptions (); / / apply the settings Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);

while (true) (
java.lang.Thread.sleep (1000);
log.debug ("output"); / / output)
/ / Appender.close ();
Note the last line is commented out code, if the line of code execution, the TelnetAppender resources would be removed, resulting in TelnetAppender can not continue to run. So how do you see the message output effect? Here are two methods: Method 1, using the Telnet tool that I use is Windows built-in Telnet. Run TelnetAppender program, click [Start] menu -> [run], in the "Run" box, enter "telnet", Enter, telnet client that pops up, this is a command line program, enter the command "open localhost 9090", Enter, and then you can see the effects. The second method to write their own procedures, the code is as follows:
package piv.zheng.log4j.test;

import java.net .*;
import java.io. *;

public class TestClient (
public static void main (String [] args) throws Exception (
/ / Create the client socket object Socket s = new Socket ("localhost", 9090);
/ / Bind the BufferedReader and Socket to Socket output information obtained BufferedReader in = new BufferedReader (new InputStreamReader (s.getInputStream ()));
/ / Access to information and output
String line = in.readLine ();
while (line! = null) (
System.out.println (line);
line = in.readLine ();
)
)
)
13. org.apache.log4j.net.SMTPAppender, send a message to the specified e-mail, but can only send ERROR, and FATAL level of information, and not to provide authentication.
Sample code:
SimpleLayout loyout = new SimpleLayout ();

SMTPAppender appender = new SMTPAppender ();
appender.setLayout (loyout); / / Set Layout
appender.setFrom ("zhengyp@126.com"); / / set the sender appender.setSMTPHost ("smtp.126.com"); / / set the sending mail server appender.setTo ("zhengyp@126.com") ; / / Set the recipient appender.setSubject ("Log4J Test"); / / set the message headers appender.activateOptions (); / / apply the settings Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("Here is DEBUG");
log.info ("Here is INFO");
log.warn ("Here is WARN");
log.error ("Here is ERROR");
log.fatal ("Here is FATAL");
To run this example, also need JavaMail and JAF, the former is the Sun launch e-mail class library, available from http://java.sun.com/products/javamail/downloads/index.html download the latest version 1.3.3, download javamail-1_3_3-ea.zip compressed file after the needs of one of the mail.jar; which stands for JavaBeans Activation Framework, provides support to input any data block, and can process it accordingly, available from http: / / www.sun.com / download find the latest version 1.1, download jaf-1_1-ea.zip compressed after the needs of one of the activation.jar file. However, the program will run twice throw exception log.error and log.fatal methods were caused by failure of the reason is very simple, I use the mail server requires authentication.
14. piv.zheng.log4j.test.SMTPAppender, custom, in accordance with Log4J provides SMTPAppender modified from an increase of the authentication function, and removed the restrictions on the level. As the code is too long, so put on another article "Custom SMTPAppender source" in your own interest to see.
Sample code:
SimpleLayout layout = new SimpleLayout ();

SMTPAppender appender = new SMTPAppender (layout);
appender.setFrom ("zhengyp@126.com"); / / From appender.setSMTPHost ("smtp.126.com"); / / send mail server appender.setTo ("zhengyp@126.com"); / / recipient appender.setSubject ("Log4J Test"); / / Message Title appender.setAuth ("true"); / / authentication identity appender.setUsername ("zhengyp"); / / user name appender.setPassword (" 1111111 "); / / password appender.activateOptions (); / / apply the settings Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Also need JavaMail and JAF. Run will send a message, go and check their e-mail it ^ _ ^
In addition, Log4J also provides SyslogAppender, JMSAppender (both under the org.apache.log4j.net package), and more Appender, or Unix operating system used to send messages syslogd service, or send messages through JMS, or otherwise, send a message. As conditions are now, no longer presented.
However, in front of the sample also used SimpleLayout and PatternLayout to format the output of information, here are a brief introduction.
1. org.apache.log4j.SimpleLayout, has been used is that it is relatively simple format of the output is "level - information."
2. org.apache.log4j.HTMLLayout, in HTML format output.
Sample code:
HTMLLayout layout = new HTMLLayout ();
layout.setTitle ("Log4J Test"); / / HTML page title FileAppender appender = null;
try (
appender = new FileAppender (layout, "test.html");
) Catch (Exception e) ()

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Run the project directory will generate an HTML page, you can use your browser to view.
3. org.apache.log4j.xml.XMLLayout, XML-format output.
Sample code:
XMLLayout layout = new XMLLayout ();

FileAppender appender = null;
try (
appender = new FileAppender (layout, "test.xml");
) Catch (Exception e) ()

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Run the project directory will generate a test.xml file.
4. org.apache.log4j.TTCCLayout, output, while output of the log production time, and other information related to the thread, and Category.
Sample code:
TTCCLayout layout = new TTCCLayout ();
/ / Are printed with TTCCLayout Category associated with the name, the default is true, that print layout.setCategoryPrefixing (true);
/ / Whether to print the current thread, the default is true, that print layout.setThreadPrinting (true);
/ / Whether to print the output and NDC information related to the current thread, the default is true, that print layout.setContextPrinting (true);
/ / Set the date and time format layout.setDateFormat ("iso8601");
/ / Set the time zone layout.setTimeZone ("GMT +8:00");
/ / Set the time zone settings need to call the application of this method layout.activateOptions ();

ConsoleAppender appender = new ConsoleAppender (layout);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Note, TTCCLayout output time format and time zone can be set:
(1) setDateFormat, set the date and time format, there are five common values: "NULL", that does not output; "RELATIVE", the output information on the time, in milliseconds, the default use of the value; "ABSOLUTE", only output time part; "DATE", according to the current date and time display area; "ISO8601", according to ISO8601 standard display date and time. These strings are not case sensitive. In addition, you can use the time pattern characters to format date and time, detailed information see J2SE documentation for java.text.SimpleDateFormat class.
(2) setTimeZone, set the time zone, details please refer to the document in the java.util.TimeZone J2SE classes and java.util.SimpleTimeZone class. Note, however, when the date format is "RELATIVE", set the time zone will cause conflict.
5. org.apache.log4j.PatternLayout, with the flexibility to specify the character pattern information output format.
Sample code:
String pattern = "Logger:% c% n"
+ "Date:% d (DATE)% n"
+ "Message:% m% n";
PatternLayout layout = new PatternLayout (pattern);

ConsoleAppender appender = new ConsoleAppender (layout);

Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);
log.debug ("output");
Pattern string Description:
% C: Category name. You can also use% c (n) Category part of the output format of the name, which is a positive integer n, output the name from the Category from the right side of n-search ".", Then the interception of the first n months "." To the right of part of the output, for example, the name of Category "xyz", specifies the format "% c (2)", then output "yz".
% C: output message where the class name of the Category, you can also use the% C (n) format output.
% D: output time, you can also use the% d (FormatString) format output, the value of which FormatString see TTCCLayout the setDateFormat method, but in% d NULL and RELATIVE is not available.
% F: output file when the Category where the class name.
% L: output information Category position, use the "% C.% M (% F:% L)" can produce the same effect.
% L: Category in the class when the output file line number.
% M: the information itself.
% M: when the Category where the output method.
% N: newline, can be interpreted as a carriage return.
% P: log level.
% R: output the time spent, in milliseconds.
% T: current thread.
% X: output and NDC information related to the current thread.
% X: the output of the MDC with the current ready-related information.
%%: Output%.
In addition, with the pattern in the% character can be inserted between the output modifiers to set the minimum width, maximum width and text alignment, such as:
% 30d (DATE): display area according to the current date and time, and specify the minimum width of 30, when the output of less than 30 characters will fill a space and right-aligned.
%-30d (DATE): is shown by the current date and time area, specify the minimum width of 30, and the characters make up less than 30 hours in space, but due to the "-", so the alignment is left on Qi, and the default case.
% .40 D (DATE): is shown by the current date and time area, but specifies the maximum width of 40, when the output of more than 40 characters, more characters will be truncated on the left. In addition, the maximum width of only support the default left alignment, does not support right-aligned.
% 30.40d (DATE): If the output is less than 30 characters to fill spaces and right-aligned, if more than 40 characters, more characters will be truncated on the left.
%-30.40d (DATE): If the output is less than 30 characters and spaces to fill the left-aligned, if more than 40 characters, more characters will be truncated on the left.
5, Log4J Advanced understand the contents of the above, it has basically mastered Log4J, but wants flexibility in the use Log4J, you also need to understand the configuration. Briefly outline.
1. org.apache.log4j.BasicConfigurator, default ConsoleAppender to PatternLayout (use PatternLayout.TTCC_CONVERSION_PATTERN, or "% r [% t]% p% c% x -% m% n" format) output.
Sample code:
BasicConfigurator.configure ();
Logger log = Logger.getLogger (Test.class);
log.debug ("output");
Note, BasicConfigurator and other fact, only the root Category Configurator to configure, but because of user-created root Category Category will inherit the characteristics of (a statement that many information on the relationship between Category inheritance are mainly discussing the output level and, in fact, Category between inherited not only the output level, all features can be inherited), so output will show the effect of BasicConfigurator configuration. In addition, you can use the configure method specified Appender, to customize the output. BasicConfigurator allows also specify multiple Appender.
Sample code:
SimpleLayout layout1 = new SimpleLayout ();
ConsoleAppender appender1 = new ConsoleAppender (layout1);
BasicConfigurator.configure (appender1);

String pattern = "Logger:% c% n"
+ "Date:% d (DATE)% n"
+ "Message:% m% n";
PatternLayout layout2 = new PatternLayout (pattern);
FileAppender appender2 = null;
try (
appender2 = new FileAppender (layout2, "test.log", false);
)
catch (Exception e) ()
BasicConfigurator.configure (appender2);

Logger log = Logger.getLogger (Test.class);
log.debug ("output");
Here designated with BasicConfigurator two Appender, that ConsoleAppender and FileAppender, after the information will be run by SimpleLayout output to the console at the same time to PatternLayout output to test.log file. To remove these Appender, can call BasicConfigurator the resetConfiguration method.
2. org.apache.log4j.PropertyConfigurator, call the text configuration file output, typically used. properties file. Configuration file "key = value" in the form of stored data, notes the "#" at the beginning. PropertyConfigurator and profile in the introduction SocketAppender and SocketHubAppender had mentioned. Use PropertyConfigurator avoid hard-coded.
Sample code:
PropertyConfigurator.configure ("test.properties");
Logger log = Logger.getLogger (Test.class);
log.debug ("output");
To complete the example, also need to create a project directory test.properties file, as follows:
# # Set the root Category, the value specified by the output level and the two-part # Appender output level set to DEBUG here
log4j.rootLogger = DEBUG, appender
# # Output to the console # create a named appender of the Appender, type ConsoleAppender
log4j.appender.appender = org.apache.log4j.ConsoleAppender
# Set the appender to SimpleLayout output log4j.appender.appender.layout = org.apache.log4j.SimpleLayout
In addition, PropertyConfigurator also allows simultaneously specify multiple Appender, for example:
# There are no set output levels, but the two specified Appender
log4j.rootLogger =, appender1, appender2
# Output to the console log4j.appender.appender1 = org.apache.log4j.ConsoleAppender
log4j.appender.appender1.layout = org.apache.log4j.SimpleLayout
# Output information to file log4j.appender.appender2 = org.apache.log4j.FileAppender
log4j.appender.appender2.File = test.log
log4j.appender.appender2.Append = false
log4j.appender.appender2.layout = org.apache.log4j.PatternLayout
log4j.appender.appender2.layout.ConversionPattern = Logger:% c% nDate:% d (DATE)% nMessage:% m% n
For more configuration, online sample a lot, not repeat them here. But one thing to note is that the configuration file key is how come. After the reference to an example, see PropertyConfigurator source, will find "log4j.rootLogger" is defined only according to written; and "log4j.appender" words can also be found, with the specified Appender name appender1, appender2 link, log4j. appender.appender1 and log4j.appender.appender2 it is not hard to understand; take a closer look, but also found "prefix +". layout "", it has also been log4j.appender.appender1.layout; but log4j.appender.appender2. File and log4j.appender.appender2.Append it? Remember when front description FileAppender mentioned setAppend way? In fact, there is a getAppend FileAppender method, indicating that FileAppender with the Append property. File it then? Of course, the properties of the FileAppender. As log4j.appender.appender2.layout.ConversionPattern too, but FileAppender replaced PatternLayout. In fact, the properties of other Appender and Layout are also defined as the key to this set of. In addition, the definition of key, the attributes of the first letter is not case sensitive, such as "File", can also be written as "file".
3. org.apache.log4j.xml.DOMConfigurator, call the XML configuration file output. Definition document is log4j-1.2.11.jar in org \ apache \ log4j \ xml package file under the log4j.dtd. Compared with PropertyConfigurator, DOMConfigurator seems to be the trend.
Sample code:
DOMConfigurator.configure ("test.xml");
Logger log = Logger.getLogger (Test.class);
log.debug ("output");
To complete the example, also need to create a directory in the project test.xml file, as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE log4j: configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<! - Output to the console to create a named appender of the Appender, type ConsoleAppender ->
<appender name="appender">
<! - Set the appender to SimpleLayout output ->
<layout/>
</ Appender>
<! - Set the root Category, and its value specified by the output level of two parts Appender here to set the output level to DEBUG ->
<root>
<priority value ="debug" />
<appender-ref ref="appender"/>
</ Root>
</ Log4j: configuration>
In addition, DOMConfigurator also allows simultaneously specify multiple Appender, for example:
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE log4j: configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<! - Output to the console ->
<appender name="appender1">
<layout/>
</ Appender>
<! - Output to file ->
<appender name="appender2">
<param name="File" value="test.log"/>
<param name="Append" value="false"/>
<layout>
<param name="ConversionPattern" value="Logger: %c %nDate: %d{DATE} %nMessage: %m %n"/>
</ Layout>
</ Appender>
<! - There is no set output level, but specify two Appender ->
<root>
<appender-ref ref="appender1"/>
<appender-ref ref="appender2"/>
</ Root>
</ Log4j: configuration>
As the two examples above are two examples in PropertyConfigurator based on reform, but also wrote a note, so here only a brief <param> tag. <param> tag has two attributes, name and value, the value of the former is Appender or Layout of the property name, such a key role and log4j.appender.appender2.File the same. Setting, the first letter of the same case-insensitive, such as "File" can also be written as "file". In addition, please note that the XML code to use these two notes should be removed will be Chinese, or the <? Xml version = "1.0" encoding = "UTF-8"?> In the UTF-8 into GBK or GB2312, otherwise cause errors. Used here is the XML default UTF-8 character set.
4. org.apache.log4j.lf5.DefaultLF5Configurator, default LF5Appender to output information, call log4j-1.2.11.jar in the org \ apache \ log4j \ lf5 \ config package files under the defaultconfig.properties.
Sample code:
try (
DefaultLF5Configurator.configure ();
)
catch (Exception e) ()
Logger log = Logger.getLogger (Test.class);
log.debug ("output");
Another topic discussed below: Diagnostic Context. Diagnostic Context means diagnostic environment, multi-user concurrent environment Zhendui Yu, in this environment it is normally required for each client provides separate thread to handle its request, Cishi in the log messages to the client to distinguish between, Category were created for each thread is a way. But this is not efficient, it will lead to a lot of resources are occupied. Diagnostic Context to be resolved is the problem. Diagnostic Context will provide a space for the current thread, and then save the information to the space calling for the Category. Compared with creating a Category, the share of this information is much less natural resources.
1. org.apache.log4j.NDC. NDC Nested Diagnostic Context is a shorthand, meaning nested diagnostic environment, use a Stack object to hold information. The characteristics of the data stack LIFO, advanced out after that clean up the stack, the data will be saved after the first cleared away, but after the first save of the data was cleared away.
Sample code:
PatternLayout layout = new PatternLayout ("% m% x% n");
ConsoleAppender appender = new ConsoleAppender (layout);
Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);

String tmp = "zhengyp"; / / simulation information obtained from the client log.debug ("Start");
NDC.push (tmp); / / add information to the stack log.debug ("Before");
NDC.pop (); / / will remove the information from the stack log.debug ("After");
NDC.remove (); / / Remove the current thread, exit the NDC environmental log.debug ("End");
PatternLayout used here to format information, the model character% x is used to output NDC information. Run will output the following:
Start
Before zhengyp
After
End
Can see that when the second line of output because the information has been added to the stack, so "zhengyp" will also output; while the third line of the output of information has been removed, so no re-export "zhengyp". But it is only a simple example demonstrates the use of NDC, NDC did not show characteristics of the stack, so the following provides a further example, the code is as follows:
TTCCLayout layout = new TTCCLayout ();
ConsoleAppender appender = new ConsoleAppender (layout);
Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);

log.debug ("Start");
NDC.push ("zhengyp"); / / add information to the stack log.debug ("Test1");
NDC.push ("192.168.0.1"); / / to stack additional information log.debug ("Test2");
NDC.pop (); / / removed from the stack information, but to remove only the last message log.debug ("Test3");
NDC.pop (); / / once again removed from the stack information log.debug ("Test4");
log.debug ("End");
Here formatted output using TTCCLayout, still remember their setContextPrinting way? Program running, from the output of information to see effects. In addition, NDC also provides other ways:
(1) get, get all the information in the stack. These cases, for example, when the output Test2, the use of the method will be "zhengyp 192.168.0.1".
(2) peek, to obtain information on the stack in the final. Still more cases, for example, when the output Test1 will be "zhengyp", Test2 when "192.168.0.1", the time when the output Test3 as "192.168.0.1" has been removed, "zhengyp" became the last of the information and so was still the "zhengyp".
(3) clear, clear all of the information stack.
(4) setMaxDepth, set the maximum stack depth, that the preservation of current information on the following additional information is not affected. When you need information more than once cleared away, the use of setMaxDepth pop convenient than multiple calls.
2. org.apache.log4j.MDC. MDC is the Mapped Diagnostic Context which stands for the mapping diagnostic environment that provides a Map object to store information. Map objects to use Key, Value in the form of stored value.
Sample code:
PatternLayout layout = new PatternLayout ("% m% X (name)% X (ip)% n");
ConsoleAppender appender = new ConsoleAppender (layout);
Logger log = Logger.getLogger (Test.class);
log.addAppender (appender);

log.debug ("Start");
/ / Add information to the Map of MDC.put ("name", "zhengyp1");
MDC.put ("ip", "192.168.1.1");
log.debug ("Test1");

/ / Add information to the Map, if Key repeat, then cover the value prior to MDC.put ("name", "zhengyp2");
MDC.put ("ip", "192.168.1.2");
log.debug ("Test2");

/ / Remove the information from the Map, then the information is no longer output MDC.remove ("name");
MDC.remove ("ip");
log.debug ("End");
This example demonstrates the basic usage of MDC, formatting information is also used PatternLayout, model character for the "% X", the format must be "% X (Key)". One Key is to add information to the Map object methods used put Key, where the name and ip. Because you can use the "% X (Key)" output, the MDC to use more flexible than the NDC. In addition, MDC also provides a way to get access to the specified Key information.
6, spent nearly two weeks Summary finally probably mastered the Log4J. Since this article to learn while writing the purpose is to record the usage of Log4J, and not to provide a Chinese reference, so the content is not detailed, but try to provide a sample. But in the end only to find, sample problems, in fact, static members of the Logger class as more appropriate, and I am the sake of expedience, actually written directly to the main method, it also please note.
Moreover, here again you recommend "The Complete log4j Manual", is a more detailed description of Log4J, available online only in English.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of replace the use of log4j system.out.print

  • Struts2 Spring Hibernate's easy to integrate

    1. Add Spring 2.0 in Libraries Choose the following four jar, and configure the / WEB-INF/lib under Spring2.0 AOP Libraries Spring2.0 Core Libraries Spring2.0 Persistence Core Libraries Spring2.0 WEb Libraries At the same time, the applicationContext ...

  • J2EE Architect road

    J2EE Architect road Looking casual, working into the fifth year, the discovery came from the Java programmer to architect J2EE course. Found that computer to install a wide range of J2EE tools: JBuilder, WSAD, Eclipse, Rose, Together, Weblogic, Jtest, Opt

  • log4j easy application in java

    JAVA development, frequently used the log output, in a so-called most of the software company will have its own set of configuration style, re-read the configuration file to initialize property of the log, it will be good, but sometimes may not need to fu

  • jboss ejb3 Message Driven Bean

    Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri

  • java read file

    java read documents in two ways: java.io and java.lang.ClassLoader When using the java.io, when java.lang.ClassLoader use it? (Note: If prior to read xml file java read file clearly aware of these two methods have been like! Can take much less to understa

  • hibernate call stored procedure

    hibernate call stored procedure

  • Hibernate configuration parameters hibernate.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries