Log4j. properties configuration (reproduced)

Source: Internet
Author: User
Tags print format

Log4j configuration file is used to set the recorder level, storage device, and layout. It can be connected to key = value format settings or XML format settings. Through configuration, you can create a log4j runtime environment.

1. Configuration File
The basic format of the log4j configuration file is as follows:

# Configure the root Logger
Log4j. rootlogger = [level], appendername1, appendername2 ,...

# Configure the appender of the log output destination
Log4j. appender. appendername = fully. Qualified. Name. Of. appender. Class
Log4j. appender. appendername. option1 = value1
...
Log4j. appender. appendername. optionn = valuen

# Configure the log information format (layout)
Log4j. appender. appendername. layout = fully. Qualified. Name. Of. layout. Class
Log4j. appender. appendername. layout. option1 = value1
...
Log4j. appender. appendername. layout. optionn = valuen


Where[Level]Is the log output level, with a total of 5 levels:

Fatal 0
Error 3
Warn 4
INFO 6
Debug 7


Appender is the log output destination. log4j provides the following types of appender:

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 size reaches the specified size ),
Org. Apache. log4j. writerappender (send log information to any specified place in stream format)


Layout: Log output format. layout provided by log4j includes the following types:

Org. Apache. log4j. htmllayout (in the form of HTML tables ),
Org. Apache. log4j. patternlayout (you can flexibly specify the layout mode ),
Org. Apache. log4j. simplelayout (including the log information level and information string ),
Org. Apache. log4j. ttcclayout (including the log generation time, thread, category, and so on)


Print parameters:Log4j uses a print format similar to the printf function in C language to format log information, as follows:

% MOutput the specified message in the code
   % POutput priority, that is, debug, info, warn, error, fatal
   % RIt takes several milliseconds to output the log information from application startup to application startup.
   % CThe output category, usually the full name of the class
   % TName of the thread that generates the log event
   % NReturns a line break, which is \ r \ n on Windows and \ n on UNIX"
   % DThe date or time of the log output time point. The default format is iso8601. You can also specify the format later, for example, % d {YYY Mmm dd hh: mm: SS, SSS }, output: October 18, 2002 22: 10: 28,921.
   % LThe location where the output log event occurs, including the category name, the thread that occurs, and the number of lines in the code. Example: testlog4.main (testlog4.java: 10)


2. initialize logger in the Code: 
1) called in a programBasicconfigurator. Configure ()Method: Add a leleappender to the root recorder. The output format is set"%-4r [% T] %-5 p % C % x-% m % N"And the default level of the root recorder isLevel. Debug.
2) Put the configuration in the file, pass the file name through the command line parameterPropertyconfigurator. Configure (ARGs [x])Parse and configure;
3) Put the configuration in the file, pass the file name and other information through the environment variables, and parse and configure the configuration using the default initialization process of log4j;
4) Put the configuration in a file, pass the file name and other information through the application server configuration, and use a special servlet to complete the configuration.

3. Set the log output level for different appender:
When debugging a system, we usually only pay attention to the log output at the exception level, but usually all levels of output are stored in a file. If the log output level is a bug !? Then go and find it.
In this case, we may want to output the exception information to a file separately. Of course, log4j has provided such a function. We only need to modify it in the configuration.AppenderOfThresholdThis can be achieved, for example, the following example:

[Configuration file]

### Set log levels ###
Log4j. rootlogger = debug, stdout, d, e

### Output to the console ###
Log4j. appender. stdout = org. Apache. log4j. leleappender
Log4j. appender. stdout. Target = system. Out
Log4j. appender. stdout. layout = org. Apache. log4j. patternlayout
Log4j. appender. stdout. layout. conversionpattern = % d {absolute} % 5 P % c {1}: % L-% m % N

### Output to a log file ###
Log4j. appender. d = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. D. File = logs/log. Log
Log4j. appender. D. append = true
Log4j. appender. D. Threshold= Debug # Output logs at or above the debug level
Log4j. appender. D. layout = org. Apache. log4j. patternlayout
Log4j. appender. d. layout. conversionpattern = %-d {yyyy-mm-dd hh: mm: SS} [% T: % R]-[% P] % m % N

### Save the exception information to a separate file ###
Log4j. appender. d = org. Apache. log4j. dailyrollingfileappender
Log4j. appender. D. File = logs/error. log # abnormal Log File Name
Log4j. appender. D. append = true
Log4j. appender. D. Threshold= Error # Only logs with error levels and above are output !!!
Log4j. appender. D. layout = org. Apache. log4j. patternlayout
Log4j. appender. d. layout. conversionpattern = %-d {yyyy-mm-dd hh: mm: SS} [% T: % R]-[% P] % m % N


[Used in code] 

Public class testlog4j {
Public static void main (string [] ARGs ){
Propertyconfigurator. Configure ("D:/code/CONF/log4j. properties ");
Logger logger = logger. getlogger (testlog4j. Class );
Logger. debug ("debug ");
Logger. Error ("error ");
}
}


Run the command to check whether the exception information is saved in the error. log file.

Use log4j. Properties
1. Parameter meaning description
Type of the output level
Error, warn, info, debug
Errors are major program errors.
Warn is a general warning, such as session loss
Info is the information to be displayed, such as logging out
Debug indicates the debugging information of the program.
Configure the log output destination
Log4j. appender. appendername = fully. Qualified. Name. Of. appender. Class
1.org. Apache. log4j. leleappender (console)
2.org. Apache. log4j. fileappender (file)
3.org. Apache. log4j. dailyrollingfileappender (a log file is generated every day)
4.org. Apache. log4j. rollingfileappender (a new file is generated when the file size reaches the specified size)
5.org. Apache. log4j. writerappender (send log information to any specified place in stream format)
Configure the log information format
Log4j. appender. appendername. layout = fully. Qualified. Name. Of. layout. Class
1.org. Apache. log4j. htmllayout (in the form of HTML tables ),
2.org. Apache. log4j. patternlayout (you can flexibly specify the layout mode ),
3.org. Apache. log4j. simplelayout (including the log information level and information string ),
4.org. Apache. log4j. ttcclayout (including the log generation time, thread, category, and other information)
Console options
Threshold = Debug: specify the minimum output level of log messages.
Immediateflush = true: the default value is true, meaning that all messages will be output immediately.
Target = system. Err: system. Out by default, which specifies the output Console
Fileappender options
Threshold = debuf: specify the minimum output level of log messages.
Immediateflush = true: the default value is true, meaning that all messages will be output immediately.
File1_mylog.txt: refers to the output to the mylog.txt file.
Append = false: The default value is true. To add a message to a specified file, false means to overwrite the specified file content.
Rollingfileappender Option
Threshold = Debug: specify the minimum output level of log messages.
Immediateflush = true: the default value is true, meaning that all messages will be output immediately.
File1_mylog.txt: refers to the output to the mylog.txt file.
Append = false: The default value is true. To add a message to a specified file, false means to overwrite the specified file content.
Maxfilesize = 100kb: The suffix can be kb, MB, or GB. When the log file reaches this hour, it will automatically scroll, moving the original content to the mylog. log.1 file.
Maxbackupindex = 2: specify the maximum number of rolling files that can be generated.
Log4j. appender. a1.layout. conversionpattern = %-4r %-5 p % d {yyyy-mm-dd hh: mm: SSS} % C % m % N
Meanings of several symbols in the log information format:
-X: left aligned when X information is output;
% P: Priority of output log information, that is, debug, info, warn, error, fatal,
% D: date or time of the log output time point. The default format is iso8601. You can also specify the format after the time point, for example, % d {YYY Mmm dd hh: mm: SS, SSS}, output is similar to: October 18, 2002 22:10:28, 921
% R: The number of milliseconds it takes to output the log information from application startup to application startup.
% C: the category of the output log, usually the full name of the class.
% T: name of the thread that outputs the log event
% L: the location where the output log event occurs. It is equivalent to a combination of % C. % m (% F: % L), including the category name, the thread that occurs, and the number of lines in the code. Example: testlog4.main (testlog4.java: 10)
% X: NDC associated with the current thread (nested Diagnostic Environment), especially used in applications with multiple clients and multithreading such as Java Servlets.
%: Output A "%" Character
% F: name of the file in which the output Log message is generated
% L: the row number in the output code
% M: output the specific log information of the specified message in the code.
% N: returns a line break. For Windows, the line break is \ r \ n, for UNIX, and the line feed is \ n.
You can add modifiers between the % and mode characters to control the alignment of the minimum width, maximum width, and text. For example:
1) % 20c: specify the name of the output category. The minimum width is 20. If the category name is smaller than 20, it is right aligned by default.
2) %-20C: specify the name of the output category. The minimum width is 20. If the category name is smaller than 20, the "-" sign specifies the left alignment.
3) %. 30C: specify the name of the output category. The maximum width is 30. If the category name is greater than 30, the extra characters on the left will be truncated, but there will be no spaces if the value is less than 30.
4) % Category 30C: If the category name is less than 20, fill in spaces and align right. If the category name is longer than 30 characters, it will be truncated from the long-distance output on the left.
Ii. file configuration sample1
Log4j. rootlogger = debug, A1, R
# Log4j. rootlogger = info, A1, R
# Leleappender output
Log4j. appender. A1 = org. Apache. log4j. leleappender
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = %-d {yyyy-mm-dd hh: mm: SS, SSS} [% C]-[% P] % m % N
# File: output one file per day. The output path can be customized. Generally, it is in the root path.
Log4j. appender. r = org. Apache. log4j. dailyrollingfileappender
Log4j.appender.r.file=blog_log.txt
Log4j. appender. R. maxfilesize = 500kb
Log4j. appender. R. maxbackupindex = 10
Log4j. appender. R. layout = org. Apache. log4j. patternlayout
Log4j. appender. r. layout. conversionpattern = % d {yyyy-mm-dd hh: mm: SS, SSS} [% T] [% C] [% P]-% m % N
File configuration sample2
The following 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.
Log4j. rootlogger = debug, console, A1, Im
# Debug, console, file, rolling_file, mail, database
Log4j.addivity.org. Apache = true
###################
# Console appender
###################
Log4j. appender. Console = org. Apache. log4j. leleappender
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] %-5 p % 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
#####################
# File appender
#####################
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] %-5 p % C % x-% m % N
# Use this layout for logfactor 5 Analysis
########################
# Rolling file
########################
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] %-5 p % C % x-% m % N
####################
# Socket appender
####################
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
########################
# Log Factor 5 appender
########################
Log4j. appender. lf5_appender = org. Apache. log4j. lf5.lf5appender
Log4j. appender. lf5_appender.maxnumberofrecords = 2000
########################
# SMTP appender
#######################
Log4j. appender. Mail = org.apache.log4j.net. smtpappender
Log4j. appender. Mail. Threshold = fatal
Log4j. appender. Mail. buffersize = 10
[Email protected]
Log4j. appender. Mail. smtphost = mail.hollycrm.com
Log4j. appender. Mail. Subject = log4j message
[Email protected]
Log4j. appender. Mail. layout = org. Apache. log4j. patternlayout
Log4j. appender. Mail. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % C % x-% m % N
########################
# JDBC appender
#######################
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] %-5 p % C % x-% m % n ')
Log4j. appender. database. layout = org. Apache. log4j. patternlayout
Log4j. appender. database. layout. conversionpattern = [framework] % d-% C-%-4r [% T] %-5 p % 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 = [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
Iii. Advanced use
Purpose:
1. Write a fatal-level error to the 2000nt log
2. Send email notification to administrators for warn, error, and fatal errors
3. Other errors are output directly in the background.
Tutorial steps:
Output to 2000nt log
1. Copy the nteventlogappender. dll in the log4j compressed package to the WINNT \ system32 directory.
2. Write the configuration file log4j. properties.
# System log output in 2000
Log4j. Logger. ntlog = fatal, A8
# Appender A8
Log4j. appender. A8 = org. Apache. log4j. nt. nteventlogappender
Log4j. appender. a8.source = javatest
Log4j. appender. a8.layout = org. Apache. log4j. patternlayout
Log4j. appender. a8.layout. conversionpattern = %-4r %-5 p [% T] % 37C % 3x-% m % N
3. Call code:
Logger logger2 = logger. getlogger ("ntlog"); // The name must be the same as that set in the configuration file.
Logger2.debug ("Debug !!! ");
Logger2.info ("info !!! ");
Logger2.warn ("Warn !!! ");
Logger2.error ("error !!! ");
// Only this error will write the 2000 log
Logger2.fatal ("Fatal !!! ");
Send email notification to the Administrator:
1. First download javamail and JAF,
Http://java.sun.com/j2ee/ja/javamail/index.html
Http://java.sun.com/beans/glasgow/jaf.html
Reference mail. jar and activation. jar in the project.
2. Write the configuration file
# Send Logs to email
Log4j. Logger. maillog = warn, A5
# Appender A5
Log4j. appender. A5 = org.apache.log4j.net. smtpappender
Log4j. appender. a5.buffersize = 5
[Email protected]
[Email protected]
Log4j. appender. a5.subject = errorlog
Log4j. appender. a5.smtphost = smtp.263.net
Log4j. appender. a5.layout = org. Apache. log4j. patternlayout
Log4j. appender. a5.layout. conversionpattern = %-4r %-5 p [% T] % 37C % 3x-% m % N
3. Call code:
// Send Logs to mail
Logger logger3 = logger. getlogger ("maillog ");
Logger3.warn ("Warn !!! ");
Logger3.error ("error !!! ");
Logger3.fatal ("Fatal !!! ");
Output errors of all types in the background:
1. Write the configuration file
# Output in the background
Log4j. Logger. Console = debug, A1
# Appender A1
Log4j. appender. A1 = org. Apache. log4j. leleappender
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = %-4r %-5 p [% T] % 37C % 3x-% m % N
2. Call Code
Logger logger1 = logger. getlogger ("console ");
Logger1.debug ("Debug !!! ");
Logger1.info ("info !!! ");
Logger1.warn ("Warn !!! ");
Logger1.error ("error !!! ");
Logger1.fatal ("Fatal !!! ");
--------------------------------------------------------------------
All configuration files: log4j. Properties
# Output in the background
Log4j. Logger. Console = debug, A1
# Appender A1
Log4j. appender. A1 = org. Apache. log4j. leleappender
Log4j. appender. a1.layout = org. Apache. log4j. patternlayout
Log4j. appender. a1.layout. conversionpattern = %-4r %-5 p [% T] % 37C % 3x-% m % N
# System log output in 2000
Log4j. Logger. ntlog = fatal, A8
# Appender A8
Log4j. appender. A8 = org. Apache. log4j. nt. nteventlogappender
Log4j. appender. a8.source = javatest
Log4j. appender. a8.layout = org. Apache. log4j. patternlayout
Log4j. appender. a8.layout. conversionpattern = %-4r %-5 p [% T] % 37C % 3x-% m % N
# Send Logs to email
Log4j. Logger. maillog = warn, A5
# Appender A5
Log4j. appender. A5 = org.apache.log4j.net. smtpappender
Log4j. appender. a5.buffersize = 5
[Email protected]
[Email protected]
Log4j. appender. a5.subject = errorlog
Log4j. appender. a5.smtphost = smtp.263.net
Log4j. appender. a5.layout = org. Apache. log4j. patternlayout
Log4j. appender. a5.layout. conversionpattern = %-4r %-5 p [% T] % 37C % 3x-% m % N
All code: log4jtest. Java

/*
* Creation date: 2003-11-13
*/
Package edu. BCU. Bean;
Import org. Apache. log4j .*;
// Import org. Apache. log4j. nt .*;
// Import org.apache.log4j.net .*;
/**
* @ Author yanxu
*/
Public class log4jtest
{
Public static void main (string ARGs [])
{
Propertyconfigurator. Configure ("log4j. properties ");
// Output in the background
Logger logger1 = logger. getlogger ("console ");
Logger1.debug ("Debug !!! ");
Logger1.info ("info !!! ");
Logger1.warn ("Warn !!! ");
Logger1.error ("error !!! ");
Logger1.fatal ("Fatal !!! ");
// Output logs in the NT System
Logger logger2 = logger. getlogger ("ntlog ");
// Nteventlogappender NLA = new nteventlogappender ();
Logger2.debug ("Debug !!! ");
Logger2.info ("info !!! ");
Logger2.warn ("Warn !!! ");
Logger2.error ("error !!! ");
// Only this error will write the 2000 log
Logger2.fatal ("Fatal !!! ");
// Send Logs to mail
Logger logger3 = logger. getlogger ("maillog ");
// Smtpappender SA = new smtpappender ();
Logger3.warn ("Warn !!! ");
Logger3.error ("error !!! ");
Logger3.fatal ("Fatal !!! ");
}
}

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.