Don't use system.out.println! Use log4j ---- 中文-

xiaoxiao2021-03-06  41

Home: www.vipan.comvipan singlae-mail: Vipan@vipan.com

Don't use system.out.println!

Use log4j

Quick Start To use Log4j

Download the Log4j software (about 2.3MB as of log4j 1.1.3) and extract log4j.jar (about 156KB) out of it. Include log4j.jar in your application's classpath so that logging methods can find the needed classes. (I copied the log4j.jar file in java installation directory's lib / ext subdirectory because Java will automatically pick it up from there and add it to classpath!) Save the following sample code in a file named TestLogging.java somewhere in the classpath.import org.apache. Log4j. *;

// how to use log4j

Public 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 Prior Set to Error");

Cat.fatal ("Just Testing A Log Message with Priority Set To Fatal";

// Alternate But Inconient 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 Can log Messages with Five Priority Levels.

Use debug to write debugging messages which should not be printed when the application is in production. Use info for messages similar to the "verbose" mode of many applications. Use warn for warning messages which are logged to some log but the application is able to carry on without a problem. Use error for application error messages which are also logged to some log but, still, the application can hobble along. Such as when some administrator-supplied configuration parameter is incorrect and you fall back to using some hard-coded default value. Use fatal for critical messages, after logging of which the application quits abnormally. Save the following lines in a file named log4j.properties in the same directory as TestLogging.class (after compiling TestLogging.java above). Log4j looks for this File By Default In The Application's Classpath When You Call Gtroot () or getInstance ("category_name") in Your code.log4j.rootcategory = debug, dest1

Log4j.Appender.Dest1 = org.apache.log4j.consoleappender

log4j.appender.dest1.layout = org.apache.log4j.PatternLayout The PatternLayout defaults to% m% n which means print your-supplied message and a newline. This is exactly the same as printed out by Java's System.out.println ( ...) method, except that Log4j methods are shorter to write, among other great advantages Now, when you compile and run TestLogging.java, you will get output similar to:! Start of main () Just testing a log message with priority SET TO INFO

Just Testing a log message with priority set to warn

Just Testing a log message with priority set to error

Just Testing a Log Message with Priority Set To Fatal

Calling init ()

*** SYSTEM Environment As Seen by java ***

*** FORMAT: Property = Value ***

Java.Runtime.name = Java (TM) 2 Runtime Environment, Standard Edition

Sun.boot.library.path = c: /jdk1.3/jre/bin

Java.vm.version = 1.3.0_02

Java.vm.vendor = Sun Microsystems Inc.

... and so on If you want to print the priority (you assigned to the message) next to the message, append the following line to the end of the log4j.properties file and save it: log4j.appender.dest1.layout. ConversionPattern =% - 5P:% M% N You Will Override The Default% M% N.% P Will Print The Message Priority,% M Is The Message Itself,% N IS Newline. Since You Only Made Changes To a Properties File, NOT to Any Java Code, There is no need to re-compile testlogging.java. Just Run it folain. You Should get the folowing Output: debug: start of main ()

Info: Just Testing a Log Message with Priority Set To Info

WARN: Just Testing a log message with priority set to warn

Error: Just Testing a log message with priority set to error

Fatal: Just Testing a log message with priority set to fatal

Debug: Calling Init ()

Info: *** SYSTEM Environment As Seen by java *** debug: *** Format: property = value ***

Info: java.runtime.name = Java (TM) 2 Runtime Environment, Standard Edition

Info: sun.boot.library.path = c: /jdk1.3/jre/bin

Info: java.vm.version = 1.3.0_02

Info: java.vm.vendor = sun microsystems Inc.

... and so on If you are tired of all those DEBUG and INFO messages and want to disable them but still want to log other messages (for example, when the application is ready to go into production), change the log4j.rootCategory = DEBUG, dest1 line to: log4j.rootCategory = WARN, dest1 This line tells Log4j to skip messages with priority lower than WARN (such as DEBUG and INFO) Now, it will just print:. WARN: Just testing a log message with priority set To Warn

Error: Just Testing a log message with priority set to error

Fatal: Just Testing a log message with priority set to fatal

Log4j details

LOG4J HAS Three Main Components: Categories, appenders and letters.

You instantiate a category and then call its various logging methods to send your message strings to log (s). A category is configured to log to one or more destinations or targets. These logging destinations are called "appenders" in Log4j, probably because these classes by default "append" your message string to the end of the log. Log4j can send your log messages to the console, a text file, an html file, an xml file, a socket or even to the Windows NT Event log, all with one logging call. It can even send your log message as an email (desirable for fatal errors, for example). Some appender classes are ConsoleAppender, FileAppender, SMTPAppender, SocketAppender, NTEventLogAppender, SyslogAppender, JMSAppender, AsyncAppender and NullAppender. An appender uses a layout to format your message before actually writing it to the log. For example, the HTMLLayout will format all your messages into a nice HTML table. In addition to logging the message that you send, Log4j can also log the dat e, time, message priority (DEBUG, WARN, FATAL etc.), Java class name, source code line number, method name, Java thread name and much more. What to log is specified in the layout which an appender s configured with.