|
Logging for AllThe Case for LoggingA very valid point is often raised to during development of any server application: it is hard to know what a given subsystem is doing. In fact, it is often hard to know what the system as a whole is doing. There are some facilities available (e.g. it is usually possible to know the SQL statements executed), but globally it is very difficult to know what's going on, and when possible it is nearly always module-specific. Very often there is no way to activate tracing for everything.
Almost all projects have a need for a global logging facility. Instead of
peppering
Log4j, a Jakarta project, is a fantastically useful tool that belongs in every Java developer's toolbox. The goal of this article is to introduce you to Log4j, its features, and how to deploy it in your own code. What are the Features of Log4j?
How to Log with Log4j
In order to shield your code base from a change in logging packages (something that can
always happen, especially considering the close advent of a Sun-blessed logging
facility), I recommend you encapsulate log4j in your own
And now for a code sample:
import com.mycompany.logging.Logger;
class MyLoggingClass
{
private static final Logger LOG = Logger.newInstance( MyLoggingClass.class );
void myLoggingMethod()
{
log.debug("this is a debugging message");
log.info("this is an informational message");
log.warn("this is a warning!");
log.error("this is an error!!");
log.fatal("this is a fatal error!!!");
}
}
All logging methods are also available with a debug(String, Throwable) info(String, Throwable) warn(String, Throwable) error(String, Throwable) fatal(String, Throwable) Each has an associated priority, in increasing order: debug < info < warn < error < fatalThe log can filtered according to priority and category. E.g. in the log4j configuration file (text or XML) I can say "only log stuff coming from com.waldura.system at priority >= WARN". The log format can be fully customized, right now I make it look like this: date time PRIO package.class method:line - messageLast but not least you can decide where the logged data is sent, e.g. by email, to a file, etc. The default log configuration logs everything from every class to the console. Conclusion
Log4j is cool, and you'll love it. Get rid of those lame
References
Copyright © 2000-2007 by Renaud Waldura. Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee, provided that copies are not made or distributed for profit or commercial advantage, and that copies bear this notice and full citation on the first page. Copyright for components of this work owned by others than Renaud Waldura must be honored. Abstracting with credit is permitted. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or fee. Request permission to publish from renaud@waldura.com. Last modified: 2002/08/01 01:17:48 $ |