|
PatternFormatter offers complete control over the appearance of Log4r log events without having to write custom Formatter classes. In order to take advantage of PatternFormatter, some familarity with Kernel#sprintf or the C printf function is recommended. For time formatting, please look at Time.strftime.
PatternFormatter accepts three hash arguments:
pattern: | Log event format string. |
date_pattern: | Date format string. |
date_method: | Time method to call (instead of using date_pattern). |
The pattern format string is something like "%l [%d] %80M", which resembles a pattern one would normally pass to Kernel#sprintf. However, the directives are specific to Log4r. Before we go on, let’s cover some terminology.
A pattern string is simply a bunch of directives combined with the desired format. For instance, to show the level in brackets followed by the date and then the log message trimmed to 15 characters, we use the following pattern:
"[%l] %d :: %.15m" #=> [DEBUG] 2001-01-12 13:15:50 :: This is a messa
To create a PatternFormatter with this format:
p = PatternFormatter.new(:pattern => "[%l] %d :: %.15m")
To format time, do one of the following:
If neither date_pattern nor date_method is specified, the default date format will be used. Currently, that would be ISO8601,
The date_pattern is exactly what one would pass to Time.strftime. To specify a date_pattern, pass :date_pattern=>"pattern" to PatternFormat.new.
Alternatively, date_method can be specified to produce the output of a specific Time method, such as usec or to_s or any other zero argument Time method that produces a time. More precisely, the method to call will be invoked on Time.now. To specify a date_method, pass :date_method=>’methodname’ (or a Symbol equivalent) to PatternFormatter.new.
As explained in log4r/configurator.rb, the hash arguments to PatternFormatter are XML parameters. Here’s an example:
<formatter type="PatternFormatter" pattern="[%l] %d :: %.15m"> <date_method>usec</date_method> </formatter>
The performance impact of using a particular directive letter is noted in the What the Directives Letters mean section.
The performance impact of time formatting merits special attention. If you aren’t aware yet, the Time class is kind of a kludge. Time.now.usec happens to be faster than Time.now. If you’re concerned about performance, please profile the various time methods and patterns.
Version: | $Id: patternformatter.rb,v 1.2 2002/01/28 16:05:05 cepheus Exp $ |
Author: | Leon Torres <leon@ugcs.caltech.edu> |
Required files |
Classes and Modules |