Discussion on the use of log4j in Java project _java

Source: Internet
Author: User

One, direct use:

Output to the project folder output1.txt file////////////////////////////////Debug-here is some DEBUG//Info-here is some INFO// Warn-here is some WARN//Error-here are some ERROR//Fatal-here is some FATAL//////////////////////////////p

Ackage Hunnu.sanha.test;

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

  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"); }//Output to item by formatOutput2.html package Hunnu.sanha.test under the target folder;

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

  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"); //Output to console//////////////////////////////////////////////////////////////////////////////////////////////////// Milliseconds since program start:0 Classname of Caller:hunnu.sanha.test.Consandpatt Date in ISO8601 format:2008-07-29 11:02:30,578 Location of Log Eve Nt:hunnu.sanha.test.Consandpatt.main (consandpatt.java:20) message:here is some DEBUG milliseconds since program STA Rt:15 Classname of Caller:hunnu.sanha.test.Consandpatt Date in ISO8601 format:2008-07-29 11:02:30,593 Location of Lo  G Event:hunnu.sanha.test.Consandpatt.main (consandpatt.java:21) message:here is some INFO milliseconds since program Start:15 Classname of Caller:hunnu.sanha.test.Consandpatt Date in ISO8601 format:2008-07-29 11:02:30,593 Location o F log event:hunnu.sanha.test.Consandpatt.main (consandpatt.java:22) message:here is some WARN milliseconds pro Gram start:15 Classname of Caller:hunnu.sanha.test.Consandpatt Date in ISO8601 format:2008-07-29 11:02:30,593 On the log event:hunnu.sanha.test.Consandpatt.main (consandpatt.java:23) message:here is some ERROR milliseconds sinc E Program Start:15 ClaSsname of Caller:hunnu.sanha.test.Consandpatt Date in ISO8601 format:2008-07-29 11:02:30,593 Location of log Event:hu Nnu.sanha.test.Consandpatt.main (consandpatt.java:24) message:here is some FATAL///////////////////////////////////

Package hunnu.sanha.test;

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[]) {//%n. 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);

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

}

Two, using a configuration file (all directly under the project folder)

Xmllog4jconfig.xml <?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=" Inde Ntify-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>

Externalxmltest.java package hunnu.sanha.external;

Import Org.apache.log4j.Logger;

Import Org.apache.log4j.xml.DOMConfigurator;

 public class Externalxmltest {static Logger Logger = Logger.getlogger (Externalxmltest.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"); }//Results output to indentify-log.txt file 2008-07-29 10:48:11,375 [main] debug-here is some DEBUG 2008-07-29 10:48:11,375 [mai  N] Info-here is some INFO 2008-07-29 10:48:11,375 [main] warn-here is some WARN 2008-07-29 10:48:11,375 [main] ERROR -Here's some ERROR 2008-07-29 10:48:11,375 [main] fatal-here is some FATAL//Plainlog4jconfig.txt # Initial Ise root logger with level DEBUG and call it blah log4j.rootlogger=debug blah # Add a consoleappender to the logger H Log4j.appender.blah=org.apache.log4j.consoleappender # Set set that layout to be simplelayout Log4j.appender.BLAH.lay

Out=org.apache.log4j.simplelayout//externalplaintest.java Package hunnu.sanha.external;

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

  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"); }//Results output to console debug-here is some DEBUG info-here is some INFO warn-here are some WARN error-here is some ERR
 OR Fatal-here is some FATAL

Additional:

2.1. Priority of Log information

is divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define.
LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application.
If a log request with a level of p occurs in a logger of level Q, if p>=q, then the request is enabled. This is the core principle of log4j.
For example, if the info level is defined here, all debug-level log information in the application will not be printed;

2.2. Use of the output source

Selective ability to use or disable log requests is only part of the log4j function. LOG4J allows log requests to be exported to multiple output sources. In Log4j's words, an output source is called a appender.
Appender includes console (console), files (file), GUI components (component of graphics), remote socket servers (socket service), JMS (Java Information Service), NT Event Logge RS (event log for NT), and remote Unix Syslog daemons (background log service for remotely Unix). It can also do asynchronous logging.
A logger can be set with more than one appender.
Add a appender to a given logger using the Addappender method. For a given logger, each log request that is in effect is forwarded to the logger of all logger appender and the logger's parents appender.

2.2.1. Consoleappender


If you use Consoleappender, log information is written to the console. The effect is equivalent to printing the information directly to the System.out.

2.2.2. Fileappender

With Fileappender, log information is written to the specified file. This should be a more frequent use of the situation.
Accordingly, the file name of the log output should be specified in the configuration file. The following configuration specifies that the log file name is Dglog.txt
Log4j.appender.a2.file=dglog.txt
Note Replace the A2 with the Appender alias in the specific configuration.

2.2.3. Dailyrollingappender

Use Fileappender to output log information to a file, but it is inconvenient to read if the file is too large. Then you can use Dailyrollingappender. Dailyrollingappender can output log information to a file that is distinguished by date. The profile will generate a log file every day, and each log file records only the log information for the day:
Log4j.appender.a2=org.apache.log4j.dailyrollingfileappender
Log4j.appender.a2.file=dglog
Log4j.appender.a2.datepattern= '. ' Yyyy-mm-dd
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
log4j.appender.a2.layout.conversionpattern=%5r%-5p%c{2}-%m%n

2.2.4. Org.apache.log4j.RollingFileAppender


A new file is generated when the file size reaches the specified size.
Log4j.appender.r=org.apache.log4j.rollingfileappender
Log4j.appender.r.file=.. /logs/dglog.log
# Control the maximum log file size
log4j.appender.r.maxfilesize=100kb
# Archive log files (one backup file here)
Log4j.appender.r.maxbackupindex=1
Log4j.appender.r.layout=org.apache.log4j.patternlayout
log4j.appender.r.layout.conversionpattern=%p%t%c-%m%n
This configuration file specifies the output source R, which is a rotation log file. The largest file is 100KB, when a log file reaches the maximum size, log4j will automatically rename Example.log to Dglog.log.1, and then rebuild a new Dglog.log file, turn the rotation.

2.2.5. Org.apache.log4j.WriterAppender

Sends log information to any specified location in streaming format.

Configuration of 2.3. Layout

layout specifies the style for log information output.

2.3.1. Layout style

Org.apache.log4j.HTMLLayout (layout in HTML form),
Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),
Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)

2.3.2. Format


%M the message specified in the output code
%p output priority, i.e. Debug,info,warn,error,fatal
%r output the number of milliseconds it takes to boot to output the log information
The class to which the%c output belongs, usually the full name of the class in which it is located
%t output The name of the thread that generated the log event
%n output a carriage return line feed, Windows platform "RN", UNIX platform "n"
%d output log point-in-time date or time, the default format is ISO8601, you can also specify the format after, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%l the location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4.main (Test log4.java:10)

2.3.3. Example

Example 1: Display date and log information
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
Log4j.appender.a2.layout.conversionpattern=%d{yyyy-mm-dd Hh:mm:ss,sss}%m%n
The printed information is:
2002-11-12 11:49:42,866 SELECT * from role WHERE 1=1 ORDER BY createdate Desc

Example 2: Display date, log occurrence place and log information
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
Log4j.appender.a2.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:ss,sss}%l "#"%m%n
2002-11-12 11:51:46,313 cn.net.unet.weboa.system.dao.RoleDAO.select (roledao.java:409) "#"
SELECT * FROM role WHERE 1=1 ORDER BY createdate Desc

Example 3: Display log level, time, call method, log information
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.A2.LAYOUT.CONVERSIONPATTERN=[%-5P]%d{yyyy-mm-dd Hh:mm:ss,sss}
method:%l%n%m%n
Log information:
[DEBUG] 2002-11-12 12:00:57,376
Method:cn.net.unet.weboa.system.dao.RoleDAO.select (roledao.java:409)
SELECT * FROM role WHERE 1=1 ORDER BY createdate Desc

2.4. Examples of configuration files:

Log4j.rootlogger=debug
#将DAO层log记录到DAOLog, in Alllog
Log4j.logger.dao=debug,a2,a4
#将逻辑层log记录到BusinessLog, in Alllog
Log4j.logger.businesslog=debug,a3,a4

#A1--Print to the screen
Log4j.appender.a1=org.apache.log4j.consoleappender
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
log4j.appender.a1.layout.conversionpattern=%-5p [%t]%37c%3x-%m%n

#A2--Print to file Daolog--dedicated to DAO layer service
Log4j.appender.a2=org.apache.log4j.dailyrollingfileappender
Log4j.appender.a2.file=daolog
Log4j.appender.a2.datepattern= '. ' Yyyy-mm-dd
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.A2.LAYOUT.CONVERSIONPATTERN=[%-5P]%d{yyyy-mm-dd Hh:mm:ss,sss}
method:%l%n%m%n

#A3--Print to file Businesslog--specifically record the logical processing layer service log information
Log4j.appender.a3=org.apache.log4j.dailyrollingfileappender
Log4j.appender.a3.file=businesslog
Log4j.appender.a3.datepattern= '. ' Yyyy-mm-dd
Log4j.appender.a3.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.A3.LAYOUT.CONVERSIONPATTERN=[%-5P]%d{yyyy-mm-dd Hh:mm:ss,sss}
method:%l%n%m%n

#A4--Print to file Alllog--Log all log information
Log4j.appender.a4=org.apache.log4j.dailyrollingfileappender
Log4j.appender.a4.file=alllog
Log4j.appender.a4.datepattern= '. ' Yyyy-mm-dd
Log4j.appender.a4.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.A4.LAYOUT.CONVERSIONPATTERN=[%-5P]%d{yyyy-mm-dd Hh:mm:ss,sss}
method:%l%n%m%n

This article on the Java project in the use of log4j is a small series to share all the content, I hope to give you a reference, but also hope that we support the cloud habitat community.

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.