[Translation] Log4J Quick Start and References

xiaoxiao2021-03-06  60

Original source: http://www.vipan.com/ Translator: Drunk ~ White E-mail: envelop@163.com Chinese Title: log4j Quick Start and Reference Text: Part 1, Quick Start

First, you need to download the log4j software and decompress the log4j.jar in it. In the ClassPath in your application, you can simply copy this file to JDK% java_home% / lib / ext Under contents. After you have finished working, you can save the following code to TestLogging.java: ################################################################# ## Import org.apache.log4j. *;

//How use log4jpublic class testlogging {

// Initialize a logging category. Here, we get the root category // static category cat = category.getroot (); // OR, Get a Custom Category Static Category Cat = Category.GetInstance (Testlogging.class.getname ()) ;

// from here! Methods Are: cat.debug (your_Message_String), // cat.info (...), cat.warn (...), cat.error (...), CAT. Fatal (...)

Public static void main (string args []) {// try a few logging methods cat.debug ("start of main ()"); Cat.Info ("Just Testing A Log Message with Priority Set To Info"); Cat .warn ("Just Testing A Log Message with Priority Set to Warn"); Cat.Error ("Just Testing A Log Message with Priority Set To Error"); Cat.Fatal ("Just Testing A Log Message with Priority Set To Fatal ");

// alternate but inconvenient form cat.log (priority.debug, "calling init ()");

NEW TESTLOGGING (). init ();

Public void init () {java.util.properties prop = system.getproperties (); java.util.enumeration enum = prop.propertyNames ();

Cat.info ("*** system environment as seen by java ***"); Cat.debug ("*** format: property = Value ***");

While (enum.hasmoreElements ()) {string key = (string) ENUM.NEXTELEMENT (); cat.info (key = " system.getproperty (key));}}}

######################################################################################################################################################################################################################################################################################################## ########## log4J By default, five levels (low to high) log messages can be recorded. 1) Debug 2) Info 3) WARN 4) ERROR 5) Fatal

Save in the directory of TestLoggin.class, save the following lines in a log4j.properties file. By default, when you use getroot () or getInstance ("category_name" in your code, log4j will be in the application's classpath Find this file: ##################################################### Rootcategory = debug, dest1log4j.appender.dest1 = org.apache.log4j.consoleappenderlog4j.Appender.dest1.Layout = org.apache.log4j.patternLayout ##################### ####################### leLeappender Specify the console address, that is, the log message is output to the console, and PatternLayout specifies the message. The format of the output, by default,% m% n,% M specified is that the message content is specified, which is specified by the operating system platform, which is more similar to the output control statement in the C language. Now, you can compile and run TestLogging.java, you can get the following output results:

Start of main () Just testing a log message with priority set to INFOJust testing a log message with priority set to WARNJust testing a log message with priority set to ERRORJust testing a log message with priority set to FATALCalling init () *** System Environment As seen by java ****** format: proty = value *** java.runtime.name = Java (TM) 2 runtime environment, Standard EditionSun.Boot.library.path = C: /JDK1.3/JRE/ Binjava.vm.version = 1.3.0_02java.vm.vendor = Sun Microsystems Inc .... and so on

If you want to print a message such as Debug, Info, Error, etc., then add the following line on the last line of log4j.properties file: log4j.appender.dest1.Layout.conversionPattern =% - 5P:% m% N this line cover The default message output format% m% n,% P specifies the level of the print message (INFO, DEBUG ..., where -5 specifies the width of the five characters, - specified is left alignment),% M Specify the content of the message, the% N specified is a newline break on the operating system platform. When these work is completed, there is no need to recompile TestLogging.java, and TestLogG is used again, it will receive the following output: Debug: Start of main () INFO: Just testing a log message with priority set to INFOWARN: Just testing a log message with priority set to WARNERROR: Just testing a log message with priority set to ERRORFATAL: Just testing a log message with priority set to FATALDEBUG : Calling init () info: *** SYSTEM ENVIRONMENT As Seen by java *** debug: *** Format: Property = value *** info: java.runtime.name = Java (TM) 2 Runtime Environment, Standard EditionInfo : sun.boot.library.path = c: /jdk1.3/jre/bininfo: java.vm.version = 1.3.0_02info: java.vm.vendor = sun microsystems inc ... And so on if you don't want to output a log Debug and info message, then modify "log4j.Rotcategory = debug, dest1" is: log4j.rootcategory = war4j.rootcategory = WARN, DEST1 The line file tells that the row of log4j jumps to the hierarchy message output, which means that as debug, info layer The submission will not generate output, run TestLogging.class again, get the following results: ####################: Just Testing a log message with priority set to Warnerror: Just Testing a log message with priority set to errorfatal: Just Testing a log message with priority set to fatal #############

The second part log4j detailed log4j has three major components: Category, attachment and layout. In the program, you can initialize a category and call various log methods to record the message string into the log. A category can be configured to output to multiple targets, which are called attachments in the log4j framework, which can include console, text files, html files, XML files, even Windows flat event log systems. , Can even be sent as a message. All these objects are configured by log4j.properties files. For programs that use the log4j frame, simply calls only methods similar to info (), debug (), and so on. Attachment categories can be consolerapnder, FileAppender, SMTPAppender, SocketAppender, NteventLogappender, Syslogappender, JMSAppender, AsyncAppender, and Nullappender. The attachment class can be formatted using the layout (Layout) to format it before sending a message to the target. For example, HTMLLayout will format the message to an HTML format. In addition to the message string to the log file, you can also record the date, time, message hierarchical, class name, source code, method name, thread name, and other information, and the specific output needs to be by the attachment The layout manager is configured. The name of Category is a case where the case is distinguished in ".". In general, we usually use your_class_name.class.getname () to get a Java class name as a name of Category, such as TestProj.util.test. Each word in the category name is said to be an ancestor of the subsequent words and a parent of the immediately following word. This is important because Log4j has this concept of inheriting priorities and appenders from ancestors until overridden in a particular category. There is a no The name of the category called root, it is like XML document elements, which is all the ancestors of Category. You can use the following code to initially initially root category or specified category. ############### Category cat = category.getRoot (); category cat2 = category.getInstance ("Your.category.Name"); ######### ########## The constant of the hierarchy is Fatal, Error, Warn, Info and Debug, can specify the hierarchical hierarchical category in log4j.properties, such as specifying log4j.rootcategory = Warn, Simple Then means calling the root Category program only logs WARN and WARN's messages. If you don't specify a default category for a category, Category will inherit from his father Category. The common Category class is: public void log (priority p, object message);

// Convenient shortcuts to the generic logging methodpublic void debug (Object message); public void info (Object message); public void warn (Object message); public void error (Object message); public void fatal (Object message); log4j only The recording level is equal or higher than the preset hierarchy, as follows: category cat = category.getroot (); Cat.SetPriority (priorror); // Setting the preset hierarchy is Error level // Later .. .//catted processing ... "); // This message will not output, erroorcat.error (" User Input is Erroneous! "); // message output, level equal Cat.fatal ( "Cannot Process User Input. Program Terminated!"); // Message Output, Hierarchy is higher than the preset level

Part III log4j Configuration All configuration work should be done in the log4j.properties file, and the file is generally in the same directory of the application. Before using the log system, we must first configure log4j. Configure log4j means adding an attachment to category and sets a Layout for each Category. Category has inheritance relationship, but they are not fixed in the order in the log4j.properties file. Example 1: ###################################################################### ############### Set the preset hierarchy used by the root category used by the log4j is Debug, and only the A1 attachment .log4j.rootcategory = debug, A1 # attachment A1 is set For the console attachment. Log4j.appender.a1 = org.apache.log4j.consoleAppender # The layout used by the attachment is patternlayout, that is, the pattern layout log4j.appender.a1.Layout = org.apache.log4j.patternlayout # attachment A1 mode is% -4R [% T]% -5p% C% X-% M% N, where% M represents the message string,% N represents a newline, and the other's meaning of the character representative of characters is as follows. Log4j.Appender.a1.Layout.conversionPattern =% - 4R [% T]% -5p% C% X-% M% N ######################### ######################################################################################################################################################################################################################################################################################### ######################################################################################################################################################################################################################################################################################################## ######## Use two appenders, one to log to console, another to log to a filelog4j.rootCategory = debug, stdout, R # Print only messages of priority WARN or higher for your categorylog4j.category.your.category .name = WARN # Specifically inherit the priority level # log4j.category.your.category.name = INHERITED #### First appender writes to consolelog4j.appender.stdout = org.apache.log4j.ConsoleAppender

Log4j.appender.stdout.Layout = org.apache.log4j.patternlayout # pattern to output the caller's file name and line number.log4j.connder.stdout.Layout.ConversionPattern =% 5P [% t] (% F:% L) -% m% n #### Second appender writes to a filelog4j.appender.R = org.apache.log4j.RollingFileAppenderlog4j.appender.R.File = example.log # Control the maximum log file sizelog4j.appender.R.MaxFileSize = 100KB # Archive log files (one backup file here) log4j.appender.R.MaxBackupIndex = 1log4j.appender.R.layout = org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern =% p% t% c -% M% n ##################################################################################################################################################################################################################################################################################### ########### fourth part Log4j useful layout useful layout has TTCCLayout, HTMLLayout, PatternLayout, SimpleLayout and XMLLayout. PatternLayout which SimpleLayout and ignored JAVA throwable interfaces derived from the errors and Exceptions.HTMLLayout Have these exceptions with XMLLayout. The hierarchy of the log message is contained in the output of the SimpleLayout, followed by the log message string behind "-". For example: Debug - Hello World Message PatternLayout can determine the output of the message based on the output mode string, and the mode string is similar to the mode string in the C language. For example, PatternLayout If the mode string "% R []%-5p% C -% M% N" will output the following message: 176 [main] info org.foo.bar -located nearest Gas Station The following are the domain Let's explain: 1)% of the number of microseconds 2)% T output the name 3)% - 5P output message of the current thread. 4)% C Output Category Name 5) -% M and S are log messages themselves,% N is a newline. You can embed any characters you want to output in the mode string. The mode in the mode string is as follows:% m: message itself% P: The level of the message is the time interval (microsecond)% c: output the current log action when the current log is generated. The category name is output. For example, if the category name is "ABC", "% C {2}" will output "BC". {2} It means output "After point separated Category name, if {n } No, the entire Category name will be output.% T: The name% x: output of the current thread is associated with the current thread (see section below), especially for multi-client multi-threaded applications like java servlets. in. % N: Output platform related newline character. %%: Output a "%" character% D: The date of output log generation can of course customize the format of the date.

For example:% D {HH: mm: SS, SSSS} or% D {DD MMM YYYY HH: MM: SS, SSSS}, if not specified, the ISO8601 format will be output. % L: Output location information, equivalent to% C.% M (% F:% L) combination. % C: The class name where the output log message is generated. If the class name is "test.page.class1"% C {1} indicates the output class name "class1",% c {2} output "Page.class1", and % C outputs "test.page.class1". % M: Method Name% f: The file name% of the output log message is generated when the log message is generated: the line number in the output code can be added between the% and mode characters to control its minimum width, The maximum width, and the way the text is aligned. Such as: 1)% 20C: Specifies the name of the output category, the minimum width is 20, if the name of Category is less than 20, the default is aligned. 2)% -20c: Specifies the name of the output category, the minimum width is 20, if the name of Category is less than 20, "-" specifies the left alignment. 3)% .30c: Specifies the name of the output category, the maximum width is 30. If the name of Category is greater than 30, it will cut the characters over the left, but there will be no spaces if less than 30. 4)% 20.30c: If the name of Category is less than 20, the space is completed, and right or right, if its name is longer than 30 characters, the character from the left departure is cut off. 4)% 20.30c:

The fifth part of the attachment and related key value parameters of the attachment and related key value parameters threshold = WARN: Specifies the lowest level of the log message. Immediateflush = true: The default is True, meaning that all messages will be output immediately. Target = system.err: By default: system.out, specify the output console 2.FileAppender option threshold = warn: Specify the minimum level of the log message. Immediateflush = true: The default is True, meaning that all messages will be output immediately. FILE = myLog.txt: Specifies the message to output to myLog.txt file. APPEND = false: The default is true, that is, the message is added to the specified file, and false refers to the contents of the specified file. 3. RollingFileAppender Options Threshold = WARN: Specifies the lowest level of the log message. Immediateflush = true: The default is True, meaning that all messages will be output immediately. FILE = myLog.txt: Specifies the message to output to myLog.txt file. APPEND = false: The default is true, that is, the message is added to the specified file, and false refers to the contents of the specified file. MaxFileSize = 100kb: The suffix can be KB, MB or GB. When the log file arrives at this size, it will automatically scroll, so that the original content is moved to myLog.log.1 file. MaxBackupIndex = 2: Specifies the maximum number of scrolling files that can be generated. 4.DailyRollingFileAppender Option Threshold = WARN: Specifies the lowest level of the log message. Immediateflush = true: The default is True, meaning that all messages will be output immediately. FILE = myLog.txt: Specifies the message to output to myLog.txt file. APPEND = false: The default is true, that is, the message is added to the specified file, and false refers to the contents of the specified file. DatePattern = '.' YYYY-WW: Scrolls a file once a week, that is, a new file per week. Of course, you can also specify months, week, day, time, and division. That is, the corresponding format is as follows: 1) '.' YYYY-MM: Month 2) '.' YYYY-WW: Week 3) '.' YYYY-MM-DD: Every day 4) '.' YYYY-MM-DD -A: Two times a day 5) '.' YYYY-MM-DD-HH: Hour 6) '.' YYYY-MM-DD-HH-MM: 10.PatternLayout Option ConversionPattern =% M% N: Specify How to format the specified message. 6.htmlLayout Option LocationInfo = true: Default is false, output Java file name and line number title = my app file: Default is log4j log message.7.xmlLayout option locationInfo = true: The default is false, output Java files and Sixth part log4j configuration case resolution # log4j.debug = true # log4j.disable = Fatal # log4j.additivity.testlogging = false

log4j.rootCategory =, dest1log4j.category.TestLogging = DEBUG, dest1log4j.appender.dest1 = org.apache.log4j.ConsoleAppender # log4j.appender.dest1.layout = org.apache.log4j.SimpleLayoutlog4j.appender.dest1.layout = org .apache.log4j.patternlayout # log4j.Appender.Dest1.Layout.conversionPattern =% - 5P% l% x:% m% n! -------------------- - ####### End of profment ####### ----------------------!

######################################################################################################################################################################################################################################################################################################## ######################################################################################################################### With #, paste and uncomment itm Above. ########################################################################################################################################################################################################################################################################## ###################################################################

! ------------------------------------------------- ---------------------------- !! Place this file anywhere in classpath !! appenders are additive by default. !! priorities are inherited unsil Overridden in a category. !! In $ {property_key}, The value of the key can be defined as a system !! Property or in this file itself. System Properties Area Searched First and !! the this file. !! --- -------------------------------------------------- ------------------------!

! ------------------------------------------------- ---------------------------- !! Configure log4j's operation at the meta level !! ----------- -------------------------------------------------- ---------------- !! Observe log4j paarsing this file # log4j.debug = true! Set this to false for log4j to actually Obey the log4j.disable property (next) # log4j. Disableoverride = false! disable all logging in all categories for Messages with prior qual to! or limited! ---------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- -------- !! Configure categories (loggers) !! --------------------------------- --------------------------------------------!

Root Category (Usually Sufficient To Set this One ONLY!, Logs Messages with priority debug (default) or higher # log4j.rootcategory =, dest1! Or, # log4j.rootcategory = debug, dest1, dest2

! YOUR CATEGORIES (to customize logging per class / pkg / project / etc)! Here, overrides ancestor's priority and makes it WARN or higher for this cat. # Log4j.category.TestLogging = WARN, dest3! Or, # log4j.category. Testlogging = debug, dest3

! -------- Don't do this !!! Appenders Are Additive by Default !!! --------------- !! It WRITE SAME LOG Message TWICE To dest1. overce for root, the for !! this category. !! # Log4j.category.testlogging = debug, dest1, dest3 !! if you do not want additivity for this category, Say So !! # log4j.additivity.testlogging = false !! ---------------------------------------------- --------------------------------------------------- -------------------------------------------------- ---------- !! Configure appenders (log destinations / targets) and their options !! ------------------------- -------------------------------------------------- -!

Write to console (stdout or stderr) # log4j.Appender.dest1 = org.apache.log4j.consoleappender # log4j.Appender.Dest1.immediateflush = true

! WRITE LOG TO A FILE, ROLL THE FILE AFTER SOME SIZE # log4j.appender.dest2 = org.apache.log4j.RollingFileAppender! This appender will only log messages with priority equal to or higher than! The one specified here # log4j.appender .dest2.Threshold = ERROR! Specify the file name ($ {property_key} gets substituted with its value) # log4j.appender.dest2.File = $ {java.home} /log4j.log! Do not append, overwrite # log4j .appender.dest2.append = false! Control the maximum log file size # log4j.Appender.Dest2.maxFilesize = 100kb! Keep Backup file (s) (Backups Will Be in filename.1, .2 etc.) # log4j.appender .dest2.maxbackupindex = 2

! WRITE LOG TO A FILE, ROLL THE FILE EVERY WEEK # log4j.appender.dest3 = org.apache.log4j.DailyRollingFileAppender! Specify the file name # log4j.appender.dest3.File = log4TestLogging2.html! Control the maximum log file size # log4j.Appender.Dest3.maxfilesize = 300kb! rollover log file at the start of each week # log4j.Appender.Dest3.datePattern = '.' YYYY-WW! -------------- -------------------------------------------------- ------------- !! Configure appender layouts (log formats) and their options !! ----------------------- -------------------------------------------------- ----!

Use Simple Log Format (E.G. Info - Your Log Message) # log4j.Appender.Dest1.Layout = Org.Apache.log4j.simpleLayout

! USE AC PRINTF STYLE PATTERN TO FORMAT LOG MESSAGE # log4j.appender.dest1.layout = org.apache.log4j.PatternLayout! For a pattern layout, specify the pattern (Default is% m% n which is fastest) # log4j.appender .DEST1.LAYOUT.CONVERSIONPATTERN =% - 5p:% m% n! or, # log4j.Appender.Dest1.Layout.conversionPattern =% - 5P% 6.10R [% T]% x (% f:% L) -% M% N

# log4j.Appender.Dest2.Layout = org.apache.log4j.patternLayout # log4j.Appender.Dest2.Layout.conversionPattern = [% D {ISO8601}]% 5P% 6.6R [% T]% x (% f:% L) -% M% N! OR, (The Pattern Below Will Slow Down Your App) # log4j.Appender.Dest2.Layout.conversionPattern = [% D {YYYY-MM-DD HH: MM},% 6.6R]% -5P [% T]% x (% F:% L) -% M% N

! FORMAT LOG MESSAGES IN THE FORM OF AN HTML TABLE # log4j.appender.dest3.layout = org.apache.log4j.HTMLLayout! Include Java file name and line number (Default is false) # log4j.appender.dest3.layout.LocationInfo = True! Set

转载请注明原文地址:https://www.9cbs.com/read-117175.html

New Post(0)