Logging with Log 4 j Introduction Logging chronological

  • Slides: 28
Download presentation
Logging with Log 4 j

Logging with Log 4 j

Introduction • Logging - chronological and systematic record of data processing events in a

Introduction • Logging - chronological and systematic record of data processing events in a program. Possible goals: • Create an audit trail • Investigate usage patterns • Discover problems and debug • Log 4 j is the most popular Java approach to logging

Auditing and Usage Patterns • Transactions in any system may be recorded as audit/paper

Auditing and Usage Patterns • Transactions in any system may be recorded as audit/paper trail, which allows to discover all the operations done with the business objects. This allows to protect the system against malevolent people. • Large volumes of audit data can be used to find out how the system is typically used (e. g. in Web server logs)

Logging vs. Debugging 1. Logging is faster then using a debugger 2. Logging can

Logging vs. Debugging 1. Logging is faster then using a debugger 2. Logging can be used to diagnose problems in the production stage as well as during development 3. Logging is easier than debugging in a distributed computing environment 4. To use logging as debugging tool we need to record lots of events

Activities Similar to Logging • All these may write to a storage device: •

Activities Similar to Logging • All these may write to a storage device: • • Tracing Debugging Error Handling Logging • The mode and purpose of writing is different

Various Logs • Various logs may be driven by: • Tracing the program flow,

Various Logs • Various logs may be driven by: • Tracing the program flow, intercepting method calls • Details of method execution at a granular level • Error conditions and exceptions that have occurred in the system • History of business events • Interactions with users and other systems

Approaches to Logging • System. out. println • Not very fast • Not easy

Approaches to Logging • System. out. println • Not very fast • Not easy to customize. Could use like this: Class Sample { public static final boolean debug = true; public void test(){ if (debug) System. out. println("Only during development"); } } • Custom logging API • Build vs buy decision • Open Source (like Log 4 j)

Java Specification JSR 47 • Logging to serve various target groups • Configure logging

Java Specification JSR 47 • Logging to serve various target groups • Configure logging from a property file and also at runtime • Log granularity (by function, by level, by custom filter) • Connect to existing logging services • Provide internationalization • Available for public review at http: //java. sun. com/about. Java/communityprocess/revie w/jsr 047/index. html

Log 4 j Background • In 1996, the SEMPER project developed a tracing API

Log 4 j Background • In 1996, the SEMPER project developed a tracing API • Later modified by IBM at their Zurich research lab (www. zurich. ibm. com) • Currently maintained by Source Forge (www. sourceforge. net). • Open source • Project home, download and documentation: http: //jakarta. apache. org/log 4 j/index. html

Log 4 j Design Principles • Log 4 j claims to be fast and

Log 4 j Design Principles • Log 4 j claims to be fast and flexible: speed first, flexibility second • Although Log 4 j has a many features, its first design goal was speed. Some Log 4 j components have been rewritten many times to improve performance.

Performance • After development - should log messages stay in the code? • When

Performance • After development - should log messages stay in the code? • When logging is turned off the cost of a log request is a method invocation plus an integer comparison. This takes a few nanoseconds. • The typical cost of an executed log request is about 100 microseconds. This is the cost of formatting the log message and sending it to the destination.

Hidden Costs of Logging • Method invocation involves the "hidden" cost of parameter construction.

Hidden Costs of Logging • Method invocation involves the "hidden" cost of parameter construction. To avoid the parameter construction cost you could write: if (logger. is. Debug. Enabled()) { logger. debug("Entry " + i + " is " + String. value. Of(entry[i])); } instead of logger. debug("Entry " + i + " is " + String. value. Of(entry[i])); Event better: avoid concatenation altogether; send objects to the logger (which have to. String() method)

Basic API 1. Printing messages are of the form: debug(Object message, Throwable t) debug(Object

Basic API 1. Printing messages are of the form: debug(Object message, Throwable t) debug(Object message) If the 1 st argument is a String object, it will be written in its present form. Other objects rendered by a registered Object renderer for its class or using the Object. to. String() method.

Basic Usage Example • Standard usage: class Foo { Logger logger; public Foo() {

Basic Usage Example • Standard usage: class Foo { Logger logger; public Foo() { logger = Logger. get. Instance(get. Class()); log. info(“Constructing foo”); } public String do. Stuff(long x){ log. debug(“doing stuff”); } }

Basic Concepts • Priority • Logger: handling the majority of log operations • Appender:

Basic Concepts • Priority • Logger: handling the majority of log operations • Appender: controlling the output of log operations • Layout: formatting the output for Appender • Configuration: • • log 4 j. properties log 4 j. xml

Priorities • Five recognized message priorities: • • Priority specific log methods following the

Priorities • Five recognized message priorities: • • Priority specific log methods following the form: • • • debug(Object message); debug(Object message, Throwable throwable); General log methods for wrappers and custom priorities: • • • DEBUG, INFO, WARN, ERROR, FATAL log(Priority level, Object message); log(Priority level, Object message, Throwable throwable); Localized log methods supporting Resource. Bundles: • • • L 7 dlog(Priority level, String message, Throwable throwable) L 7 dlog(Priority level, Object[] params, Throwable throwable) set. Resource. Bundle(Resource. Bundle);

Loggers • Loggers define a hierarchy and give the programmer run-time control on which

Loggers • Loggers define a hierarchy and give the programmer run-time control on which statements are printed or not. • Loggers are assigned priorities. A log statement is printed depending on its priority and its category. • Used to support output to multiple logs (Appenders) at the same time. Log 4 j. category. com. mycompany. finance=INFO, FIN_Appender This will direct all log messages in package com. mycompany. finance with priority > INFO to FIN_Appender.

Logger Names • You can name by locality. It turns out that instantiating a

Logger Names • You can name by locality. It turns out that instantiating a logger in each class, with the logger name equal to the fully-qualified name of the class, is a useful and straightforward approach. • However, this is not the only way for naming. A common alternative is to name loggers by functional areas. For example, the "database" logger, "RMI" logger, "security" logger, or the "XML" logger.

Logger Naming Convention • Benefits of using fully qualified class names for categories It

Logger Naming Convention • Benefits of using fully qualified class names for categories It is very simple to implement: • It is very simple to explain to new developers • It automatically mirrors your application's own modular design • It can be further refined at will • Printing the category automatically gives information on the locality of the log statement

Root category • If no category is defined via a configuration file or programmatically,

Root category • If no category is defined via a configuration file or programmatically, then all messages will be sent to the root category • All categories define a priority level and an Appender Example of definition in (log 4 j. properties): Log 4 j. root. Category=WARN, ROOT_Appender

Appenders • An Appender is a object that sends log messages to their final

Appenders • An Appender is a object that sends log messages to their final destination • File. Appender – Write to a log file • Socket. Appender – Dumps log output to a socket • Syslog. Appender – Write to the syslog

Appenders continued • NTEvent. Log. Appender – Write the logs to the NT Event

Appenders continued • NTEvent. Log. Appender – Write the logs to the NT Event Log system. • Rolling. File. Appender – After a certain size is reached it will rename the old file and start with a new one. • Socket. Appender – Dumps log output to a socket • SMTPAppender – Send Messages to email • JMSAppender – Sends messages using Java Messaging Service • Or create your own. Not that difficult.

Pattern. Layout – Customize your message • Used to customize the layout of a

Pattern. Layout – Customize your message • Used to customize the layout of a log entry. The format is closely related to conversion pattern of the printf function in C. The following options are available: • • c - Used to output the category of the logging event. C - Used to output the fully qualified class name of the caller issuing the logging request. d - Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH: mm: ss, SSS} or %d{dd MMM yyyy HH: mm: ss, SSS}. If no date format specifier is given then ISO 8601 format is assumed F - Used to output the file name where the logging request was issued. • •

Pattern. Layout – Customize your message • • l - Used to output location

Pattern. Layout – Customize your message • • l - Used to output location information of the caller which generated the logging event. (C+M+L) L - Used to output the line number from where the logging request was issued. n - Outputs the platform dependent line separator characters. M - Used to output the method name where the logging request was issued. p - Used to output the priority of the logging event. t - Used to output the name of the thread that generated the logging event. x - Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.

log 4 j. properties – Example 1 log 4 j. root. Logger=DEBUG, my. Appender

log 4 j. properties – Example 1 log 4 j. root. Logger=DEBUG, my. Appender log 4 j. appender. my. Appender=org. apache. log 4 j. Console. Appender log 4 j. appender. my. Appender. layout=org. apache. log 4 j. Patten. Layout log 4 j. appender. my. Appender. layout. Conversion. Pattern= %-4 r [%t] %-5 p %c %x - %m%n Output example: 0 [main] INFO com. web. robot. Web. Robot. Main - Web. Robot. Main application started 2203 [main] INFO com. web. robot. Web. Robot. Main - Spring application context initialized 2203 [main] INFO com. web. robot. Web. Robot - Web. Robot started 2203 [main] INFO com. web. robot. impl. Main. Bookmark. Processor - Starting to load bookmarks 7750 [main] INFO com. web. robot. impl. Main. Bookmark. Processor - Totally [74] bookmarks loaded 7750 [main] INFO com. web. robot. Web. Robot - [74] bookmarks loaded by [com. web. robot. impl. Main. Bookmark. Processor ] 7750 [main] INFO com. web. robot. impl. Main. Bookmark. Processor - Starting to process bookmarks 11234 [main] INFO com. web. robot. impl. Main. Bookmark. Processor - Bookmarks processed: [66] saved, [8] ignored 11234 [main] INFO com. web. robot. Web. Robot - Web. Robot finished 11234 [main] INFO com. web. robot. Web. Robot. Main - Web. Robot. Main finished

log 4 j. properties – Example 2 # Set options for appender named "ROOT_Appender"

log 4 j. properties – Example 2 # Set options for appender named "ROOT_Appender" # It should be a Rolling. File. Appender, with maximum file size of 10 MB# using at most one backup file. The layout is using a pattern layout. ISO 8061 date format with context printing enabled. log 4 j. appender. ROOT_Appender=org. log 4 j. Rolling. File. Appender log 4 j. appender. ROOT_Appender. File=out. log 4 j. appender. ROOT_Appender. Max. File. Size=10 MB log 4 j. appender. ROOT_Appender. Max. Backup. Index=1 log 4 j. appender. ROOT_Appender. layout=org. log 4 j. Pattern. Layout log 4 j. appender. ROOT_Appender. layout. Conversion. Pattern=%d{ISO 8601} %p %t %x - %m%n # Root category set to DEBUG using the ROOT_Appender appender defined above. log 4 j. root. Category=INFO, ROOT_Appender log 4 j. category. com. emaritz. registration. ejb=DEBUG

Commons-logging • • • The Jakarta commons-logging package is an ultra -thin and modular

Commons-logging • • • The Jakarta commons-logging package is an ultra -thin and modular bridge between different logging implementations Commons-logging is very important when writing libraries that might be used in other projects A library that uses the commons-logging API can be used with any logging implementation at runtime

References • Log 4 J Home http: //logging. apache. org/log 4 j/index. html •

References • Log 4 J Home http: //logging. apache. org/log 4 j/index. html • Log 4 J Tutorial http: //supportweb. cs. bham. ac. uk/documentation/tutori als/docsystem/build/tutorials/log 4 j. html • Short introduction to log 4 j by Ceki Gülcü http: //logging. apache. org/log 4 j/1. 2/manual. html • Commons Logging http: //commons. apache. org/logging/