Log operations with log4j

xiaoxiao2021-03-06  18

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

*

Description: a sample with log4j

* @version 1.0

* /

Public class clientwithoutlog4j {

/ **

*

* @Param Args

* /

Public static void main (string args []) {

String welcome = null;

String response = NULL;

BufferedReader Reader = NULL;

PrintWriter Writer = NULL;

InputStream in = NULL;

OutputStream 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 (New InputStreamReader (in);

Writer = New PrintWriter (New OutputStreamWriter (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

*

Description: a sample with log4j

* @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 (ioexception e) {

System.out.println ("Error: IOException 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 Package

Import org.apache.log4j.propertyConfigurator;

Import org.apache.log4j.logger;

Import org.apache.log4j.level;

/ **

*

*

Client with log4j

*

Description: a sample with log4j

* @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 the crete 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;

BufferedReader Reader = NULL;

PrintWriter Writer = NULL;

InputStream in = NULL;

OutputStream 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) Level.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 (ioexception e) {

// Add for log4j: log a message with the error level

Logger.Error ("IOEXCEPTION:" E); System.exit (0);

}

Try {

Reader = New Bufferedreader (New InputStreamReader (in);

Writer = New PrintWriter (New OutputStreamWriter (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 debug level

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 Package

Import org.apache.log4j.propertyConfigurator;

Import org.apache.log4j.logger;

Import org.apache.log4j.level;

/ **

*

*

server with log4j

*

Description: a sample with log4j

* @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 the crete 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) Level.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 IOExce:" E);

System.exit (0);

}

Reader = New BufferedReader (NEW INPUTSTREAMREADER (IN)); Writer = New PrintWriter (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 (ioexception e) {

// Add for log4j: log a message with the error level

Logger. Error ("IOEXCEPTION IN Server" E);

System.exit (0);

}

}

}

}

2.2.3. Profile

2.2.3.1. Client 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.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% N2.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, its syntax is: log4j.rootlogger = [level], appendername, appendername, ... where Level is the priority of log record, divided into OFF, Fatal, Error, Warn, INFO, Debug, All, or you define 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. Configuring the log information output Destination Appender, its syntax is log4j.qualified.Appendername = full.qualified.name.of.Appender.class

Log4j.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 (Generate a log file per day), org.apache.log4j.rollingFileAppender generates a new file when specified by the specified size, org.apache.log4j.writraPpender (send log information to any specified place in the flow format) ) Configure the format (layout) of log information, its syntax is: log4j.Appender.Appendername.Layout = Fully.qualified.Name.Of.Layout.classlog4j.Appender.Appendername.Layout.Option1 = Value1

...

Layout provided by log4j.Appender.Appendername.Layout.Option = VALUEN, Layout provided by log4j: org.apache.log4j.htmlLayout (layout in HTML form), org.apache.log4j.patternlayout (you can flexibly designate the layout Mode), org.apache.log4j.simplelayout (level, 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 (Object Message);

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.

转载请注明原文地址:https://www.9cbs.com/read-40020.html

New Post(0)