Log4j and common-logging
I searched for some log4j and common-logging introductions on the Internet and recorded them.
I. log4j
1. Introduction
Log4j is an open source project of Apache.
Using log4j, we can easily record logs.
Download the latest stable version from http://www.apache.org/dist/logging/log4j/1.2.14/
2. Usage
Drop the log4j-1.2.14.jar to the lib directory, You need to define the configuration file before using log4j, you can not use, but configure the log4j environment in the code. But use the configuration file to make the application more flexible.
The log4j configuration file has three main components: logger, appender, and layout, which are respectively the log type, log output destination, and log output format.
Similar to proxool, log4j supports two types of configuration files: XML and properties.
The log4j. properties configuration file is as follows: (you need to put the log4j configuration file under classpath)
Log4j. rootlogger = [level], appendername, appendername,... (level is the error level, appendername is the output destination, and multiple can be defined)
The level priority is fatal, error, warn, info, and debug. by defining the level, you can control the log output in the program. for example, the error level is defined here. logs with only the faral and error levels in the program will be output.
Log4j. appender. appendername = output destination (the appendername is defined previously and can be named randomly)
Log4j provides the following output destinations:
Org. Apache. log4j. leleappender (console)
Org. Apache. log4j. fileappender (file)
Org. Apache. log4j. dailyrollingfileappender (a log file is generated every day)
Org. Apache. log4j. rollingfileappender (a new file is generated when the file reaches the specified size)
Org. Apache. log4j. writerappender (send log information to any place in stream format)
Log4j. appender. mylog. File = dir
Log4j. appender. mylog. maxfilesize = filesize
Log4j. appender. mylog. maxbackupindex = num
Log4j. appender. appendername. layout = layout type (set layout type)
Log4j. appender. appendername. layout = layout type (set layout type)
Log4j provides four layout types: Org. apache. log4j. htmllayout (layout in HTML form) Org. apache. log4j. simplelayout (Level and information string containing log information) Org. apache. log4j. ttcclayout (including the log generation time, thread, category, and so on) Org. apache. log4j. patternlayout (you can flexibly specify the layout mode)
If you use the patternlayout layout, you must specify the specific format of the print information conversionpattern,
The print parameters are as follows:
% M the output priority of the specified message % P in the output code, that is, debug, info, warn, error, fatal % R: The number of milliseconds that the application started to output the log information % C the category of the output, this is usually the full name of the Class % T. The thread name % N that generates the log event outputs a carriage return line break. Windows is "RN", UNIX is "N" % d, and the log output time is, for example: % d {yyyy Mmm dd hh: mm: SS, SSS}, output: 19:30:00, January 1, 000%, where the log event is generated, including the category name and thread, and the number of lines in the Code [QC] is the beginning of log information, can be any character, generally referred to as Project
The simplest and most common configuration file (printed from the console ):
Log4j. rootlogger = info, myloglog4j. appender. mylog = org. apache. log4j. leleappenderlog4j. appender. mylog. layout = org. apache. log4j. patternlayoutlog4j. appender. mylog. layout. conversionpattern = [-] % P % d {yyyy-mm-dd hh: mm: SS} % m % N or log4j. rootlogger = info, myloglog4j. appender. mylog = org. apache. log4j. leleappenderlog4j. appender. mylog. layout = org. apache. log4j. simplelayout
Use of log4j in code:
First, you need to import the log class
Import Org. arache. log4j. logger; static logger = logger. getlogger (your-className.class); # logger is the only place to insert logs. debug (your-message); logger.info (your-message); logger. warn (your-message); logger. error (your-message); logger. fatal (your-message );
When writing a program, a large amount of logger information will be added for debugging. Of course, when the program does not need the output information after debugging, you only need to increase the output level, for example, to the error level, in this way, logger with the following error levels will not output. very simple and convenient.
II. Introduction to commons-logging
Log4j and commons-logging are both log-recorded. Why should they be used together?
Commons-logging provides a unified interface for "All Java log implementations". Its own log functions are usually weak, and log4j functions are very powerful and comprehensive, so they can be used in combination.
How commons-logging works:
1First look for your own configuration file commons-logging.properties under classpath, if found, use the log implementation class defined in it
2If the commons-logging.properties file is not found, you can use the defined log implementation class to find the system environment variable org. Apache. commons. Logging. log that has been defined
3. Check whether the classpath contains a log4j package. If any package is found, log4j is automatically used as the log implementation class.
4. Use JDK's own log implementation class (the log implementation class will be available only after jdk1.4)
5. Use commons-logging to provide a simple log implementation class named simplelog.
(The above sequence is not guaranteed to be completely accurate. Please refer to the official documentation)
Commons-logging can always find a log implementation class and try to find the "most appropriate" log implementation class.
1. You do not need a configuration file.
2. automatically determines whether a log4j package exists. If yes, it is automatically used.
3. In the most pessimistic situations, it is always possible to provide a log implementation (simplelog)
In addition, I always think that the use of log4j is a bit problematic.
static Logger logger = Logger.getLogger(message);
A static logger instance must be created for each Java class that needs to write logs. If there are many Java classes, the overhead for creating these static objects will be very large. Therefore, you can write a log class by yourself, there is a static method to get the logger instance
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class Logs { private static Log log; static{ log=LogFactory.getLog(Logs.class); } public static Log getLogger(){ return log; }}
3. Comprehensive log4j Configuration
The simple configuration of log4j makes log4j more and more applications: the log4j configuration file provides a full set of functions such as output to the console, files, rollback files, sending log emails, output to database log tables, and custom tags. It is enough to choose one or two of them.
Log4j. rootlogger = debug, console, A1, Im
Log4j.addivity.org. Apache = true
# Apply to the 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%
# Apply to files
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
# Apply 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 Logs to emails
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender log4j.appender.MAIL.Threshold=FATAL log4j.appender.MAIL.BufferSize=10 log4j.appender.MAIL.From=[email protected] log4j.appender.MAIL.SMTPHost=www.wusetu.com log4j.appender.MAIL.Subject=Log4J Message log4j.appender.MAIL.To=[email protected] log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
# For Databases
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. DB. SQL = insert into ss_log4j_log (priority, logdate, class, method, MSG) values ('% P',' % d {yyyy-mm-dd hh: mm: SS }', '% C',' % m', '% m') log4j. appender. DB. layout = org. apache. log4j. patternlayout log4j. appender. database. layout = org. apache. log4j. patternlayout log4j. appender. database. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % n <PRE class = Java name = "code "> 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 </PRE> <br> <span style = "color: green "> # custom appender </span> <br> <PRE class = Java name =" code "> 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 = [email protected] log4j. appender. im. layout = org. apache. log4j. patternlayout log4j. appender. im. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % n </PRE> <br>
From: http://www.open-open.com/bbs/view/1318596826374