JAVA-Elegant logging (log4j combat)

Source: Internet
Author: User
Tags log4j

    • Write in front

In project development, logging error logs has the following benefits:

    1. Easy Commissioning
    2. Easy to find errors during system operation
    3. Store business data for post-analysis purposes

In Java, there are many ways to log logs:

    • Own implementation

Write your own class, log data to IO operation, write data to a text file, a database.

    • Using log4j

LOG4J can output the log to the console window, text files, databases, etc., powerful!

    • Using SLFJ

SLFJ is also a very powerful feature, SLFJ is designed to eminence, provides Logging.jar and log4j interfaces, can be SLFJ to invoke log4j, can also invoke the JDK logging.

    • Methods in Logging.jar using the JDK's own

1, log4j need to import the package

General use of log4j needs to be used in conjunction with logging:

    • Commons-logging-1.0.4.jar
    • Log4j-1.2.15.jar
2. Adding configuration Files

Under SRC, add the log4j configuration file into the Log4j.properties

Standard properties file (properties file operation)

3. Set up class file + main function

4, modify the configuration file, the log output to the consolelog4j profile is: # # # Set level and destination (here multiple Destinations) # # #
Log4j.rootlogger = Debug,console
# # # Here's me is the package, that is, in this package logging, is only the debug and above the level of logging
Log4j.logger.me=debug
# # # Output to console # # #
Log4j.appender.CONSOLE = Org.apache.log4j.ConsoleAppender
Log4j.appender.CONSOLE.Target = System.out
Log4j.appender.CONSOLE.layout = Org.apache.log4j.PatternLayout
Log4j.appender.CONSOLE.layout.ConversionPattern =%d{absolute}%5p%c{1}:%l-%m%n main function call: Import Org.apache.log4j.Logger;

public class Log4jtest {
public static Logger Logger1 = Logger.getlogger (Log4jtest.class);
public static void Main (string[] args) {
Logger1
Logger1.trace ("I am Logger1,trace");
Logger1.debug ("I am Logger1,debug");
Logger1.info ("I am Logger1,info");
Logger1.warn ("I am Logger1,warn");
Logger1.error ("I am Logger1,error");
Logger1.fatal ("I am Logger1,fatal");
}
You can see the output from the console: 16:51:16,575 DEBUG log4jtest:15 [main:0]-I'm Logger1,debug
16:51:16,578 INFO log4jtest:16 [main:3]-I'm Logger1,info
16:51:16,578 WARN log4jtest:17 [main:3]-I'm Logger1,warn
16:51:16,578 ERROR log4jtest:18 [main:3]-I am logger1,error
16:51:16,578 FATAL log4jtest:19 [main:3]-I'm Logger1,fatal

5, set the format of the output

In Heading 4, you see the output of the console, which is output in a certain format, or from a configuration file log4j.properties

Log output format, the parameters used are as follows, add as needed:%p: Output log information priority, that is, Debug,info,warn,error,fatal,
%d: the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%r: The number of milliseconds to output the log information from the application boot to output
%c: The class in which the output log information 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
%l: The location of the output log event, which corresponds to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)
%x: The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications such as Java Servlets.
Percent: Output a "%" character
%F: The name of the file where the output log message was generated
%l: Line numbers in the output code
%M: The specified message in the output code, resulting in the log specific information
%n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform for "\ n" Output log information line-wrapping
You can add modifiers between% and pattern characters to control their minimum width, maximum width, and text alignment. Such as:
1)%20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the default is the right alignment.
2)%-20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-aligned.
3)%.30c: Specify the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more than the character of the cut off, but less than 30, there will be no spaces.
4)%20.30c: If the category name is less than 20, fill in the blanks, and right-aligned, if its name is longer than 30 characters, it is exported from the left hand, the characters are cut off.
1
6. Output the log to a text file log4j profile: # # # Set level and destination (multiple destinations here) # # #
Log4j.rootlogger = Trace,console,zhangsanlog
Log4j.logger.me=debug

# # # Output to console # # #
Log4j.appender.CONSOLE = Org.apache.log4j.ConsoleAppender
Log4j.appender.CONSOLE.Target = System.out
Log4j.appender.CONSOLE.layout = Org.apache.log4j.PatternLayout
Log4j.appender.CONSOLE.layout.ConversionPattern =%d{absolute}%5p%c{1}:%l [%t:%r]-%m%n

# # # Output to log file # # #
Log4j.appender.zhangsanLog = Org.apache.log4j.DailyRollingFileAppender
Log4j.appender.zhangsanLog.File =g\:\\var\\alldata\\zhenduan\\debug.log
#log4j. Appender.zhangsanLog.File =/var/alldata/zhenduan/debug.log
Log4j.appender.zhangsanLog.Append = True
# # Output Only logs above the debug level
Log4j.appender.zhangsanLog.Threshold = DEBUG
#‘.‘ YYYY-MM-DD: Generate a new file every day
Log4j.appender.zhangsanLog.DatePattern = '. ' Yyyy-mm-dd
Log4j.appender.zhangsanLog.layout = Org.apache.log4j.PatternLayout
Log4j.appender.zhangsanLog.layout.ConversionPattern =%-d{yyyy-mm-dd HH:mm:ss} [%t:%r]-[%p] [%c{1}:%l] [%M]%m%n
Log4j.additivity.zhangsanLog = Falsemain function call: public static Logger logger1 = Logger.getlogger (Log4jtest.class);
public static void Main (string[] args) {
Logger1
Logger1.trace ("I am Logger1,trace");
Logger1.debug ("I am Logger1,debug");
Logger1.info ("I am Logger1,info");
Logger1.warn ("I am Logger1,warn");
Logger1.error ("I am Logger1,error");
Logger1.fatal ("I am Logger1,fatal");
}

7, every hour, every day, every half born into a file

Continue with the configuration of heading 6 , but you need to modify several places.

In heading 6 , there's this sentence

Log4j.appender.zhangsanLog = Org.apache.log4j.DailyRollingFileAppender

Append the log to the file, how often does the problem generate a file?

Need to modify

Log4j.appender.zhangsanLog.DatePattern = '. ' Yyyy-mm-dd

datepattern= '. ' YYYY-WW: Scrolls a file once a week, which results in a new file every week. Of course, you can specify the month, week, day, time, and minute, which corresponds to the following format:

1)'. ' YYYY-MM: Monthly

2)'. ' YYYY-WW: Weekly

3)'. ' YYYY-MM-DD: Every day

4)'. ' Yyyy-mm-dd-a: two times a day

5)'. ' YYYY-MM-DD-HH: Per hour

6)'. ' YYYY-MM-DD-HH-MM: Per minute

8. Create a new file when the text file is 3KB large

Also use the code for heading 6 :

Log4j.appender.zhangsanLog = Org.apache.log4j.RollingFileAppender
Log4j.appender.zhangsanLog.File =g\:\\var\\alldata\\zhenduan\\debug.log
#log4j. Appender.zhangsanLog.File =/var/alldata/zhenduan/debug.log
Log4j.appender.zhangsanLog.Append = True
# # Output Debug levels above the log
Log4j.appender.zhangsanLog.Threshold = DEBUG
#‘.‘ YYYY-MM-DD: Generate a new file every day
Log4j.appender.zhangsanLog.MaxFileSize = 2KB
Log4j.appender.zhangsanLog.MaxBackupIndex = 5
Log4j.appender.zhangsanLog.layout = Org.apache.log4j.PatternLayout
Log4j.appender.zhangsanLog.layout.ConversionPattern =%-d{yyyy-mm-dd HH:mm:ss} [%t:%r]-[%p] [%c{1}:%l] [%M]%m%n
Log4j.additivity.zhangsanLog = False?
1

The change here is

Log4j.appender.zhangsanLog = Org.apache.log4j.RollingFileAppender

MaxFileSize, a new file Maxbackupindex is created when the file reaches a large storage space .

9, log4j the log output to the database

Follow-up supplement

10. log4j the log output to HBase in the Hadoop framework

Follow-up supplement

Log level for log4j

From low to high, you can associate the error level with Windows or UNIX:

Trace: Is tracking, is the program to push the following, you can write a trace output, so the trace should be very much, but it doesn't matter, we can set the minimum log level does not let him output.

debug: Debug, I generally only use this as the lowest level, trace is not used at all. Is it OK to use eclipse or idea's debug function in no way?

Info: Output The information you are interested in or important, which is the most used.

warn: Some of the information is not an error message, but also some hints to the programmer, similar to the code validation in eclipse is not error and warn (not errors but also note, such as the following depressed methods).

ERR: Error message. It's more used.

Fatal: The level is relatively high. Major error, this level you can directly stop the program, is not supposed to appear error! Not so nervous, in fact, is a degree of problem.

log4j Configuration, Description:

LOG4J supports two configuration file formats, one in XML format and one in the properties format. What I usually use is the properties file.

1, Log4j.rootlogger = [level], Appendername, Appendername, ...

Level: Is the log4j log, priority from high to low is error, WARN, INFO, DEBUG.

Appendername: Specifies where the log information is to be exported. Multiple output destinations can be specified at the same time.

2, the configuration log information output destination Appender, its syntax is: Log4j.appender.appenderName = Fully.qualified.name.of.appender.class

Log4j.appender.appenderName.option1 = value1
...
Log4j.appender.appenderName.option = Valuen
Among them, LOG4J provides the following types of Appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (generates a log file every day),
Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size),
Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)

3, set the Appender, the configuration for Appender

The other configuration options are set to where you want to output it.

(1). Consoleappender Options

Threshold=warn: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be output immediately.

Target=system.err: By default: System.out, specify output console

(2). Fileappender Options

Threshold=warn: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be output immediately.

File=mylog.txt: Specifies the message output to the Mylog.txt file.

Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.

(3). Dailyrollingfileappender Options

Threshold=warn: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be output immediately.

File=mylog.txt: Specifies the message output to the Mylog.txt file.

Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.

Datepattern= '. ' YYYY-WW: Scrolls a file once a week, which results in a new file every week. You can also specify monthly, weekly, Days, hours, and minutes. The corresponding format is as follows:

1) '. ' YYYY-MM: Monthly

2) '. ' YYYY-WW: Weekly

3) '. ' YYYY-MM-DD: Every day

4) '. ' Yyyy-mm-dd-a: two times a day

5) '. ' YYYY-MM-DD-HH: Per hour

6) '. ' YYYY-MM-DD-HH-MM: Per minute

(4). Rollingfileappender Options

Threshold=warn: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be output immediately.

File=mylog.txt: Specifies the message output to the Mylog.txt file.

Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.

MAXFILESIZE=100KB: The suffix can be kb, MB, or GB. When the log file reaches this size, it will automatically scroll to move the original content to the Mylog.log.1 file

maxbackupindex=2: Specifies the maximum number of scroll files that can be produced.

4. Configure the layout of the log information with the following syntax:

Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
Log4j.appender.appenderName.layout.option1 = value1
...
Log4j.appender.appenderName.layout.option = Valuen
Among them, log4j offers the following types of layout:
Org.apache.log4j.HTMLLayout (Layout in HTML table Form),
Org.apache.log4j.PatternLayout (flexibility to specify layout mode),
Org.apache.log4j.SimpleLayout (contains the level of log information and the information string),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

About Additivity
Log4j.additivity.zhangsanLog = False

This additivity is also an interesting option.

It is the flag bit of whether the child logger inherits the output source (Appender) of the parent logger. Specifically, by default, logger inherits the Appender of the parent logger, which means that the logger is output in the logger of the parent appender. If Additivity is set to false, the child logger will only output in its own appender, not in the appender of the parent logger.
The effect is as follows:

Log4j.rootlogger=warn,a2,a3
Log4j.logger.test=debug

Log4j.appender.a2=org.apache.log4j.rollingfileappender
Log4j.appender.a2.file=. /logs/test.log
Log4j.appender.a2.encoding=utf-8
Log4j.appender.a2.append=true
Log4j.appender.a2.maxfilesize=2mb
Log4j.appender.a2.maxbackupindex=5
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
log4j.appender.a2.layout.conversionpattern=%-5p%d [%t]%c{3}.%m-%m%n

Log4j.additivity.test.xml=false
Log4j.logger.test.xml=debug,a3

Log4j.appender.a3=org.apache.log4j.rollingfileappender
Log4j.appender.a3.file=. /logs/test-xml.log
Log4j.appender.a3.encoding=utf-8
Log4j.appender.a3.append=true
Log4j.appender.a3.maxfilesize=2mb
Log4j.appender.a3.maxbackupindex=5
Log4j.appender.a3.layout=org.apache.log4j.patternlayout
log4j.appender.a3.layout.conversionpattern=%-5p%d [%t]%c{3}.%m-%m%n?
1

The configuration file has

Log4j.logger.test=debug
Log4j.additivity.test.xml=false
Log4j.logger.test.xml=debug,a3

In this example, the inheritance relationship is canceled by Log4j.additivity.test.xml=false, so that the XML log is only output in A3.

Other:

Regardless of the log level, A.java, B.java, C.java call their own logger, respectively, and write the logs to separate files.

This requirement is mainly in the configuration file, give Appender a name

Then, when called, uses the name to invoke the

public static Logger Loggera = Logger.getlogger ("Alog");

public static Logger Loggerb = Logger.getlogger ("Blog");

public static Logger Loggerc = Logger.getlogger ("Clog");

----------------------------------------------------------End.

Reprint Please specify: http://www.cnblogs.com/crazyacking/p/5456347.html

Http://www.cnblogs.com/crazyacking/p/5456347.html

JAVA-Elegant log (log4j) (Turn)

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.