Java Logger (Java log)

Source: Internet
Author: User

Directory

1. Introduction
2. Installation
3. log4j Basic Concepts
3.1. Logger
3.2. Appender
3.2.1. Using Consoleappender
3.2.2. Using Fileappender
3.2.3. Using Writerappender
3.3. Layout
3.4. Basic examples
3.4.1. Simplelayout and Fileappender
3.4.2. Htmllayout and Writerappender
3.4.3. Patternlayout and Consoleappender
4. Using an external configuration file
5. References (and some links with reference value)
1. Introduction
The logging in the program development environment consists of statements embedded in the program to output some useful information to the developer. For example, trace statements (trace), structural dumps, and common System.out.println or printf debug statements. LOG4J provides a hierarchical method for embedding logging statements in a program. Log information has multiple output formats and multiple output levels.

With a dedicated logging package, you can mitigate the maintenance costs of thousands of SYSTEM.OUT.PRINTLN statements, because logging can be controlled at run time through configuration scripts. LOG4J maintains the logging statements embedded in the program code. By standardizing the process of logging, some people believe that more use of logging should be encouraged and more efficient.

2. Installation
In order to use the logging tool we are about to install, we must also set the operating environment so that the tool knows where to find it and the operating system knows where to find the tool. So, how to do it? In fact, it requires a change in the operating environment. I have some qualifications in this document. Configuring a Windows working environment and configuring a Unix working environment.

Download the log4j release from Http://jakarta.apache.org/log4j/docs/download.html.

Unzip the archive file into the appropriate directory.

Add the file Dist/lib/log4j-1.2.6.jar to the CLASSPATH environment variable.

The basic concept of 3.log4j
The use of log4j involves about 3 main concepts:

public class Logger

Logger is responsible for most of the operations that log records are processed.

public interface Appender

The Appender is responsible for controlling the output of logging operations.

Public abstract class layout

Layout is responsible for formatting the output of the Appender.

3.1.Logger
The logger (Logger) is the core component of log processing. The log4j has 5 levels of normal (level). The available level of the logger (Logger), excluding the level of customization levels, is excerpted from the log4j API (http://jakarta.apache.org/log4j/docs/api/index.html):

Static level DEBUG

The debug level indicates that fine-grained information events are very helpful for debugging applications.

Static level INFO

The INFO level indicates that the message highlights the application's running process at a coarse-grained scale.

Static level WARN

WARN level indicates a potential error situation.

Static level ERROR

The error level indicates that the system continues to operate without affecting the failure event.

Static level FATAL

FATAL level indicates that each serious error event will cause the application to exit.

In addition, there are two special logging levels available: (The following description is from log4j apihttp://jakarta.apache.org/log4j/docs/api/index.html):

Static level All

All levels are the lowest level and are used to open all log records.

Static level OFF

The off level is the highest grade and is used to turn off all log records.

The behavior of the logger (Logger) is hierarchical. As shown in the following table:

Figure. Log Output level


The logger (Logger) will only output information that is above or equal to its level. If you do not set the level of the Logger (Logger), it inherits the level of the nearest ancestor. Therefore, if you create a logger (Logger) in package Com.foo.bar and no level is set, it inherits the level of the Logger (Logger) created in the package Com.foo. If the logger (Logger) is not created in Com.foo, then the logger (Logger) created in Com.foo.bar inherits the root logger (Logger) level. The root logger (Logger) is often instantiated and available, and its level is debug.

There are many ways to create a logger (Logger), and the following method can retrieve the root logger:

Logger Logger = Logger.getrootlogger ();


You can also create a new logger like this:

Logger Logger = Logger.getlogger ("MyLogger");


A more common use is to instantiate a static global logger from the class name:

static Logger Logger = Logger.getlogger (Test.class);


All these created "logger" loggers can set the level in the following ways:

Logger.setlevel (level) level.warn);


You can use any one of the 7 levels; Level.debug, Level.info, Level.warn, Level.error, Level.fatal, Level.all and Level.off.

3.2.Appender
How the Appender control log is output. Some of the available Appender (http://jakarta.apache.org/log4j/docs/api/index.html described in the Log4j API) are listed below:

Consoleappender: Outputs log events to System.out or system.err using the user-specified layout. The default target is System.out.

Dailyrollingfileappender extends the Fileappender, so multiple log files can be cycled with a user-selected frequency.

Fileappender Write log events to a file

Rollingfileappender extended Fileappender backup capacity up to a certain size log file.

Writerappender writes log events to writer or outputstream according to the user's choice.

Smtpappender when a particular log event occurs, a message is typically sent when an error or a material error occurs.

Socketappender sends a log event (Loggingevent) object to a remote log server (usually a network socket byte point).

Sockethubappender sends a log event (Loggingevent) object to a remote log server group (usually a network socket byte point).

Syslogappender sends a message to the background daemon (daemon) for remote asynchronous logging.

Telnetappender a log4j Appender dedicated to sending messages to read-only network sockets.

You can also implement the Appender interface to create a Appender that logs output in its own way.

3.2.1. Using Consoleappender
Consoleappender can be created in this way:

Consoleappender Appender = new Consoleappender (new Patternlayout ());


A console Appender is created with a default patternlayout. It uses the default System.out output.

3.2.2. Using Fileappender
Fileappender can be created in this way:

Fileappender appender = null;

try {

Appender = new Fileappender (new Patternlayout (), "filename");

} catch (Exception e) {}




The constructor used above:

Fileappender (layout layout, String filename)

Instantiate a fileappender and open the file specified by the variable "filename".




Another useful constructor is:

Fileappender (layout layout, String filename, boolean append)

Instantiate a fileappender and open the file specified by the variable "filename".




This constructor also allows you to choose whether to append the specified file in the output mode. If no value is specified, then the default is append.

3.2.3. Using Writerappender
Writerappender can be created in this way:

Writerappender appender = null;

try {

Appender = new Writerappender (new Patternlayout (), New FileOutputStream ("filename");

} catch (Exception e) {}




This writerappender uses constructors with patternlayout and OutputStream parameters, in which case fileoutputstream is used to output to a file. Of course, it also has other constructors available.

3.3.Layout
Appender must use a Layout associated with it so that it can know how to format its output. Currently, LOG4J has three types of layout:

Htmllayout formatted log output as an HTML table.

The patternlayout formats the log output according to the specified conversion mode, or uses the default conversion mode if no conversion mode is specified.

Simplelayout formats the log output in a very simple way, it prints level levels, followed by a dash "-", and finally the log message.

3.4. Basic examples
3.4.1.SimpleLayout and Fileappender
Here is a very simple example of a program that implements 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 (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");

}

}




You can download: Simpandfile.java. You can also view its output: Output1.txt.

3.4.2.HTMLLayout and Writerappender
Here is a very simple example of a program that implements 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);

} catch (Exception e) {}

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");

}

}




You can download: Simpandfile.java. You can also view its output: Output1.txt.

3.4.3.PatternLayout and Consoleappender
Here is a very simple example of a program that implements 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");

}

}




You can download: Simpandfile.java. You can also view its output: Output2.txt.

4. Using an external configuration file
Often used in conjunction with external log files, so many options do not have to be hard-coded in the software. The advantage of using an external configuration file is that modifying the optional option does not require a recompile program. The only drawback is that the speed is slightly slower due to the use of IO instructions.

There are two methods that you can use to specify an external configuration file: A text file or an XML file. Now that everything is written in an XML file, the tutorial focuses on XML file methods, but also contains examples of relevant text files. First, take a look at the following XML configuration file example:

<?xml version= "1.0" encoding= "UTF-8"?>

<! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" >

<log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/" >



<appender name= "Consoleappender" class= "Org.apache.log4j.ConsoleAppender" >

<layout class= "Org.apache.log4j.SimpleLayout"/>

</appender>

<root>

<priority value = "Debug"/>

<appender-ref ref= "Consoleappender"/>

</root>

</log4j:configuration>




The file starts with a standard XML declaration followed by the DOCTYPE declaration of the DTD (document type definition), which defines the structure of the XML file, for example, what elements can be embedded in other elements, and so on. The above file is in the Src/java/org/apache/log4j/xml directory of the log4j release. Then look at the log4j:configuration element that encapsulates all the elements, which is specified as the root element in the DOCTYPE declaration. There are two structures embedded in the root element:

<appender name= "Consoleappender" class= "Org.apache.log4j.ConsoleAppender" >

<layout class= "Org.apache.log4j.SimpleLayout"/>

</appender>




To create a Appender called "Consoleappender", note that you can choose any name, and the example chooses "Consoleappender" for the design of the example. The Appender class is then given in full name, often using the canonical (fully qualified) class name. The appender must have a specified name and class. Embedded within Appender is the layout element, where it is designated as Simplelayout. Layout must have a class attribute.

<root>

<priority value = "Debug"/>

<appender-ref ref= "Consoleappender"/>

</root>




The root element must be present and not quilt-like. The priority in the example is set to "Debug", and the set Appender is full of a appender-ref element. There are more properties or elements that can be specified. Check out the SRC/JAVA/ORG/APACHE/LOG4J/XML/LOG4J.DTD in the log4j release for more information about the structure of the XML configuration file. You can use this method to read the configuration information file into the Java program:

Domconfigurator.configure ("Configurationfile.xml");




Domconfigurator uses a DOM tree to initialize the log4j environment. Here is the XML configuration file in the example: Plainlog4jconfig.xml. Here is the program that executes the configuration file: Files/externalxmltest.java:

Import Org.apache.log4j.Logger;

Import Org.apache.log4j.xml.DOMConfigurator;

public class Externalxmltest {

static Logger Logger = Logger.getlogger (Filetest.class);

public static void Main (String args[]) {

Domconfigurator.configure ("Xmllog4jconfig.xml");

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");

}

}




Here is an XML configuration file that implements the logger logger with patternlayout Fileappender:

<?xml version= "1.0" encoding= "UTF-8"?>

<! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" >

<log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/" >



<appender name= "Appender" class= "Org.apache.log4j.FileAppender" >

<param name= "File" value= "Indentify-log.txt"/>

<param name= "Append" value= "false"/>

<layout class= "Org.apache.log4j.PatternLayout" >

<param name= "Conversionpattern" value= "%d [%t]%p-%m%n"/>

</layout>

</appender>

<root>

<priority value = "Debug"/>

<appender-ref ref= "Appender"/>

</root>

</log4j:configuration>




You can download the example here: Xmllog4jconfig2.xml. To get more examples of configuring the LOG4J environment with XML files, check out the directory src/java/org/apache/log4j/xml/examples/for the log4j release.

This is the configuration file in the form of the text file discussed above:

# initialise Root logger with level DEBUG and call it blah

Log4j.rootlogger=debug, blah

# Add a consoleappender to the logger blah

Log4j.appender.blah=org.apache.log4j.consoleappender

# Set set that layout to be simplelayout

Log4j.appender.blah.layout=org.apache.log4j.simplelayout




From here you can download: Plainlog4jconfig.txt. This is the program that executes the configuration file:

Import Org.apache.log4j.Logger;

Import Org.apache.log4j.PropertyConfigurator;

public class Externalplaintest {

static Logger Logger = Logger.getlogger (Externalplaintest.class);

public static void Main (String args[]) {

Propertyconfigurator.configure ("Plainlog4jconfig.xml");

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");

}

}




You can download an example that uses this configuration file: Externalplaintest.java. For more examples of configuring the LOG4J environment with text files, see the catalog examples in the log4j release.

An example of using an external configuration file is simply discussed here, and it should now be certain that you have the ability to independently learn more examples of log4j distributions and beta versions.

5. References (and some links with reference value)
Http://jakarta.apache.org/log4j/docs/manual.html

A concise introduction to log4j-Ceki G-March 2002

Http://www.vipan.com/htdocs/log4jhelp.html

Don't use system.out.println!. With Log4j-vipan Singla

http://www.opensymphony.com/guidelines/logging.jsp

Get started with log4j/opensymphony logging

Http://builder.com.com/article.jhtml?id=u00820020124kev01.htm

Java Logger (Java log)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.