The difference between Logger.getlogger () and Logfactory.getlog ()

Source: Internet
Author: User
Tags documentation file size html form log log print format rollback socket log4j

First, the difference between Logger.getLogger () and LogFactory.getLog () 

1. Logger.getLogger () uses log4j to record logs;

2.LogFactory.getLog () comes from Apache's common-logging package.

Common-logging component: Jakarta Commons Logging (JCL) provides a log interface, and also considers lightweight and does not depend on specific log implementation tools. It provides a simple log operation abstraction for middleware / log tool developers, allowing program developers to use different specific log implementation tools. To understand the situation in the package, you can view its API documentation: http://www.oschina.net/uploads/doc/commons-logging-1.1.1/index.html, where Log (basic logger) and LogFactory (responsible for creation Log instances) are two base classes. The API directly provides support for the following low-level logging tools: Jdk14Logger, Log4JLogger, LogKitLogger, NoOpLogger (discard all log information directly), and a SimpleLog. It is necessary to explain in detail what happened when calling LogFactory.getLog (). Calling this function will start a discovery process, that is, to find out the necessary implementation of the underlying logging function. The specific discovery process is listed below: (In other words, with so many tools, which one should common-logging use? It depends on the system settings, common-logging will decide which logging tool to use in the following order :)

        (1) .common-logging first find the commons-logging.properties file in the CLASSPATH. This property file defines at least the org.apache.commons.logging.Log property, and its value should be the fully qualified name of any Log interface implementation described above. If the org.apache.commons.logging.Log genus is found, the corresponding log component of the genus is used. End the discovery process.

        (2). If the above steps fail (the file does not exist or the genus does not exist), common-logging then checks the system property org.apache.commons.logging.Log. If the org.apache.commons.logging.Log system property is found, the log component corresponding to the system property is used. End the discovery process. (3). If the org.apache.commons.logging.Log system property cannot be found, common-logging then looks for the log4j class in the CLASSPATH. If found, it is assumed that the application is using log4j. However, at this time, the properties of log4j itself must still be correctly configured through the log4j.properties file. End the discovery process. (4). If none of the above searches can find the proper Logging API, but the application is running on JRE 1.4 or higher, the logging function of JRE 1.4 is used by default. End the discovery process. (5). Finally, if the above operations fail (JRE version is also lower than 1.4), the application will use the built-in SimpleLog. SimpleLog outputs all log information directly to System.err. End the discovery process.

        In order to simplify the configuration of commons-logging, the commons-logging configuration file is generally not used, and the system environment variables related to commons-logging are not set. Instead, only the Log4j Jar package needs to be placed in classpash. In this way, the integration of commons-logging and Log4j is very simple.

        According to different properties, log information is usually divided into different levels, from low to high: "Debug (DEBUG)" "Information (INFO)" "Warning (WARN)" "Error (ERROR)" "Fatal error (FATAL ) ".

   for example:

   Based on common-logging operation mode:

Java code Collection code
package org;
import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
public class Test extends TagSupport {
public static Log log = LogFactory.getLog (Test.class);
public static void test ()
{
log.debug ("111");
log.info ("125");
log.warn ("485");
log.error ("error");
  
}
public static void main (String [] a)
{
Test.test ();
}
}

 

   Running mode based on log4j

Java code Collection code
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class TestLog4j {
  
static Logger logger = Logger.getLogger (TestLog4j.class);
   public static void main (String args []) {
   PropertyConfigurator.configure ("log4j.properties");
   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");
   }
}

 

Second, introduce Log4j in detail

   ① Log4j architecture The three major sections of the Log4j system: log writer, log output terminal, and log layout mode



        The Logger class is the core of the log package. The name of the Logger is case sensitive and there is an inheritance relationship between the names. The child name is prefixed by the parent name, separated by a dot ".", For example, x.y is the father Logger of x.y.z. There is a root logger in the Logger system, which is the ancestor of all loggers. It always exists and cannot be obtained by name. It can be obtained by Logger.getRootLogger (). There are many ways to obtain the Logger object. You can refer to the API documentation. In an object, using the class to which the object belongs as a parameter, calling Logger.getLogger (Class clazz) to obtain the logger object is considered to be the most sensible named logger method currently known .

   ② Log4j log level (Level) Each logger has a log level, used to control the log output. A logger with an unassigned level will automatically inherit the log level of its closest parent logger. The low to high levels of Logger are as follows: ALL <DEBUG <INFO <WARN <ERROR <FATAL <OFF

   ③Log4j output terminal (Appender interface)

       Log4j provides the following implementations:

Java code Collection code


org.apache.log4j.ConsoleAppender (console)
org.apache.log4j.FileAppender (File)
org.apache.log4j.DailyRollingFileAppender (a log file is generated every day)
org.apache.log4j.RollingFileAppender (A new log file is generated when the file size reaches the specified size, and the number serial number will be automatically added to the file name.)
org.apache.log4j.WriterAppender (send log information to any specified place in stream format)
  
org.apache.log4j.ConsoleAppender (console)
org.apache.log4j.FileAppender (File)
org.apache.log4j.DailyRollingFileAppender (a log file is generated every day)
org.apache.log4j.RollingFileAppender (A new log file is generated when the file size reaches the specified size, and the number serial number will be automatically added to the file name.)
org.apache.log4j.WriterAppender (send log information to any specified place in stream format)



      By default, the child logger will inherit all appenders from the parent logger.

    ④Log4j's output layout mode (Layout interface) Log4j provides Layout with the following types:

 

   

Java code Collection code



org.apache.log4j.HTMLLayout (layout in HTML form)
org.apache.log4j.PatternLayout (can flexibly specify the layout mode)
org.apache.log4j.SimpleLayout (contains log information level and information string)
org.apache.log4j.TTCCLayout (including the time, thread, category and other information generated by the log)
  
 org.apache.log4j.HTMLLayout (layout in HTML form)
 org.apache.log4j.PatternLayout (can flexibly specify the layout mode)
 org.apache.log4j.SimpleLayout (contains log information level and information string)
 org.apache.log4j.TTCCLayout (including the time, thread, category and other information generated by the log)


     Log4j uses a print format similar to the printf function in the C language to format the log information. The printing parameters are as follows:

Html code Collection code


% m: output the message specified in the code.
% p: output priority.
% r: Enter the number of milliseconds spent from application startup to output of the log information.
% c: The category to which the output belongs, usually the full name of the category.
% n: Output a carriage return and line feed character. "\ R \ n" for Windows and "\ n" for UNIX.
% d: output the date or time of the log time point, the default format is ISO8601, it is recommended to use "% d {ABSOLUTE}", the output format is like: "2007-05-07 18: 23: 23,500", in line with Chinese habits .
% l: The location where the output log event occurs, including the class name, thread name, and the number of lines of code.
% m: output the message specified in the code.
% c: The category to which the output belongs, usually the full name of the category.
% t: Output the name of the thread that generated the log thread.
% n: Output a carriage return and line feed character. "\ R \ n" for Windows and "\ n" for UNIX.
% d: output the date or time of the log time point, the default format is ISO8601, it is recommended to use "% d {ABSOLUTE}", the output format is like: "2007-05-07 18: 23: 23,500", in line with Chinese habits .
% l: The location where the output log event occurs, including the class name, thread name, and the number of lines of code.
% d outputs the date or time of the log time point. The default format is ISO8601, and the format can be specified afterwards, for example:% d {yyy-MM-dd HH: mm: ss}, the output is similar: 2002-10-18 22:10:28
% f Class name of the class to which the log information belongs
% l The location of the output log event, that is, the statement that outputs the log information is in it 


The first few lines of the class
 

% m outputs the information specified in the code, such as the message in log (message)
% p output priority, namely DEBUG, INFO, WARN, ERROR, FATAL. If it is debug () output, it is DEBUG, and so on
% r Output the number of milliseconds spent from application startup to output of the log information
% t outputs the name of the thread that generated the log event

   

   ⑤Log4j configuration

    In actual use, Log4j is generally configured and used through configuration files. There are two configuration files, Java properties and XML files. Generally, the properties file is used for configuration, because it is concise and easy to read. The following only introduces how to configure Java properties. The configuration of Log4j is the configuration of rootLogger and child Logger. The main configuration items are: rootLogger, output terminal, output layout mode, all configuration items must start with log4j. Examples of configuration files

   

Java code Collection code
## Log4J's simple configuration makes it popular in more and more applications
    
## Log4J configuration file realizes a full set of functions such as output to console, file, rollback file, sending log mail, output to database log table, custom label and so on. It is enough to choose one or two of them.
    
## The content of this file (log4j.properties) comes from the Internet and is not original by the author of this article, liigo.
log4j.rootLogger = DEBUG, CONSOLE, A1
log4j.addivity.org.apache = true
    
# Apply to console
log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender
log4j.appender.Threshold = DEBUG
log4j.appender.CONSOLE.Target = System.out
log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern = [framework]% d-% c-%-4r [% t]%-5p% c% x-% m% n
# log4j.appender.CONSOLE.layout.ConversionPattern = [start]% d {DATE} [DATE]% n% p [PRIORITY]% n% x [NDC]% n% t [THREAD] n% c [CATEGORY]% n% m [MESSAGE]% n% n
    
#Apply to file
log4j.appender.FILE = org.apache.log4j.FileAppender
log4j.appender.FILE.File = file.log
log4j.appender.FILE.Append = false
log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern = [framework]% d-% c-%-4r [% t]%-5p% c% x-% m% n
# Use this layout for LogFactor 5 analysis
    
# Applied to file rollback
log4j.appender.ROLLING_FILE = org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE.Threshold = ERROR
log4j.appender.ROLLING_FILE.File = rolling.log
log4j.appender.ROLLING_FILE.Append = true
log4j.appender.ROLLING_FILE.MaxFileSize = 10KB
log4j.appender.ROLLING_FILE.MaxBackupIndex = 1
log4j.appender.ROLLING_FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE.layout.ConversionPattern = [framework]% d-% c-%-4r [% t]%-5p% c% x-% m% n
    
#Apply to socket
log4j.appender.SOCKET = org.apache.log4j.RollingFileAppender
log4j.appender.SOCKET.RemoteHost = localhost
log4j.appender.SOCKET.Port = 5001
log4j.appender.SOCKET.LocationInfo = true
# Set up for Log Facter 5
log4j.appender.SOCKET.layout = org.apache.log4j.PatternLayout
log4j.appender.SOCET.layout.ConversionPattern = [start]% d {DATE} [DATE]% n% p [PRIORITY]% n% x [NDC]% n% t [THREAD]% n% c [CATEGORY]% n% m [MESSAGE]% n% n
    
# Log Factor 5 Appender
log4j.appender.LF5_APPENDER = org.apache.log4j.lf5.LF5Appender
log4j.appender.LF5_APPENDER.MaxNumberOfRecords = 2000
    
# Send log to email
log4j.appender.MAIL = org.apache.log4j.net.SMTPAppender
log4j.appender.MAIL.Threshold = FATA
log4j.appender.MAIL.BufferSize = 10
log4j.appender.MAIL.From = web@www.wuset.com
log4j.appender.MAIL.SMTPHost = www.wusetu.com
log4j.appender.MAIL.Subject = Log4J Message
log4j.appender.MAIL.To = web@www.wusetu.com
log4j.appender.MAIL.layout = org.apache.log4j.PatternLayout
log4j.appender.MAIL.layout.ConversionPattern = [framework]% d-% c-%-4r [% t]%-5p% c% x-% m% n
    
    
# For database
log4j.appender.DATABASE = org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DATABASE.URL = jdbc: mysql: // localhost: 3306 / test
log4j.appender.DATABASE.driver = com.mysql.jdbc.Driver
log4j.appender.DATABASE.user = root
log4j.appender.DATABASE.password =
log4j.appender.DATABASE.sql = INSERT INTO LOG4J (Message) VALUES ('[framework]% d-% c-%-4r [% t]% -5p% c% x-% m% n')
log4j.appender.DATABASE.layout = org.apache.log4j.PatternLayout
log4j.appender.DATABASE.layout.ConversionPattern = [framework]% d-% c-%-4r [% t]%-5p% c% x-% m% n
log4j.appender.A1 = org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File = SampleMessages.log4j
log4j.appender.A1.DatePattern = yyyyMMdd-HH '.log4j'
log4j.appender.A1.layout = org.apache.log4j.xml.XMLLayout
    
#Custom Appender
log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
log4j.appender.im.host = mail.cybercorlin.net
log4j.appender.im.username = username
log4j.appender.im.password = password
log4j.appender.im.recipient = corlin@cybercorlin.net
log4j.appender.im.layout = org.apache.log4j.PatternLayout
log4j.appender.im.layout.ConversionPattern = [framework]% d-% c-%-4r [% t]%-5p% c% x-% m% n
    
# End    

 

 The content of this article comes from the blogs of several netizens, thank them here


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.