home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / DateFormat.pm < prev    next >
Encoding:
Perl POD Document  |  2003-03-08  |  10.4 KB  |  365 lines

  1. ###########################################
  2. package Log::Log4perl::DateFormat;
  3. ###########################################
  4. use warnings;
  5. use strict;
  6.  
  7. our $GMTIME = 0;
  8.  
  9. my @MONTH_NAMES = qw(
  10. January February March April May June July
  11. August September October November December);
  12.  
  13. my @WEEK_DAYS = qw(
  14. Sunday Monday Tuesday Wednesday Thursday Friday);
  15.  
  16. ###########################################
  17. sub new {
  18. ###########################################
  19.     my($class, $format) = @_;
  20.  
  21.     my $self = { 
  22.                   stack => [],
  23.                   fmt   => undef,
  24.                };
  25.  
  26.     bless $self, $class;
  27.  
  28.         # Predefined formats
  29.     if($format eq "ABSOLUTE") {
  30.         $format = "HH:mm:ss,SSS";
  31.     } elsif($format eq "DATE") {
  32.         $format = "dd MMM yyyy HH:mm:ss,SSS";
  33.     } elsif($format eq "ISO8601") {
  34.         $format = "yyyy-MM-dd HH:mm:ss,SSS";
  35.     }
  36.  
  37.     if($format) { 
  38.         $self->prepare($format);
  39.     }
  40.  
  41.     return $self;
  42. }
  43.  
  44. ###########################################
  45. sub prepare {
  46. ###########################################
  47.     my($self, $format) = @_;
  48.  
  49.     $format =~ s/(([GyMdhHmsSEDFwWakKz])\2*)/rep($self, $1)/ge;
  50.  
  51.     $self->{fmt} = $format; 
  52. }
  53.  
  54. ###########################################
  55. sub rep {
  56. ###########################################
  57.     my ($self, $string) = @_;
  58.  
  59.     my $first = substr $string, 0, 1;
  60.     my $len   = length $string;
  61.  
  62.     #my ($s,$mi,$h,$d,$mo,$y,$wd,$yd,$dst) = localtime($time);
  63.  
  64.     # Here's how this works:
  65.     # Detect what kind of parameter we're dealing with and determine
  66.     # what type of sprintf-placeholder to return (%d, %02d, %s or whatever).
  67.     # Then, we're setting up an array, specific to the current format,
  68.     # that can be used later on to compute the components of the placeholders
  69.     # one by one when we get the components of the current time later on
  70.     # via localtime.
  71.     
  72.     # So, we're parsing the "yyyy/MM" format once, replace it by, say
  73.     # "%04d:%02d" and store an array that says "for the first placeholder,
  74.     # get the localtime-parameter on index #5 (which is years since the
  75.     # epoch), add 1900 to it and pass it on to sprintf(). For the 2nd 
  76.     # placeholder, get the localtime component at index #2 (which is hours)
  77.     # and pass it on unmodified to sprintf.
  78.     
  79.     # So, the array to compute the time format at logtime contains
  80.     # as many elements as the original SimpleDateFormat contained. Each
  81.     # entry is a arrary ref, holding an array with 2 elements: The index
  82.     # into the localtime to obtain the value and a reference to a subroutine
  83.     # to do computations eventually. The subroutine expects the orginal
  84.     # localtime() time component (like year since the epoch) and returns
  85.     # the desired value for sprintf (like y+1900).
  86.  
  87.     # This way, we're parsing the original format only once (during system
  88.     # startup) and during runtime all we do is call localtime *once* and
  89.     # run a number of blazingly fast computations, according to the number
  90.     # of placeholders in the format.
  91.  
  92. ###########
  93. #G - epoch#
  94. ###########
  95.     if($first eq "G") {
  96.         # Always constant
  97.         return "AD";
  98.  
  99. ##########
  100. #y - year#
  101. ##########
  102.     } elsif($first eq "y") {
  103.         if($len >= 4) {
  104.             # 4-digit year
  105.             push @{$self->{stack}}, [5, sub { return $_[0] + 1900 }];
  106.             return "%04d";
  107.         } else {
  108.             # 2-digit year
  109.             push @{$self->{stack}}, [5, sub { $_[0] % 100 }];
  110.             return "%02d";
  111.         }
  112.  
  113. ###########
  114. #M - month#
  115. ###########
  116.     } elsif($first eq "M") {
  117.         if($len >= 3) {
  118.             # Use month name
  119.             push @{$self->{stack}}, [4, sub { return $MONTH_NAMES[$_[0]] }];
  120.             return "%s";
  121.         } elsif($len == 2) {
  122.             # Use zero-padded month number
  123.             push @{$self->{stack}}, [4, sub { $_[0]+1 }];
  124.             return "%02d";
  125.         } else {
  126.             # Use zero-padded month number
  127.             push @{$self->{stack}}, [4, sub { $_[0]+1 }];
  128.             return "%d";
  129.         }
  130.  
  131. ##################
  132. #d - day of month#
  133. ##################
  134.     } elsif($first eq "d") {
  135.         push @{$self->{stack}}, [3, sub { return $_[0] }];
  136.         return "%0" . $len . "d";
  137.  
  138. ##################
  139. #h - am/pm hour#
  140. ##################
  141.     } elsif($first eq "h") {
  142.         push @{$self->{stack}}, [2, sub { ($_[0] % 12) || 12 }];
  143.         return "%0" . $len . "d";
  144.  
  145. ##################
  146. #H - 24 hour#
  147. ##################
  148.     } elsif($first eq "H") {
  149.         push @{$self->{stack}}, [2, sub { return $_[0] }];
  150.         return "%0" . $len . "d";
  151.  
  152. ##################
  153. #m - minute#
  154. ##################
  155.     } elsif($first eq "m") {
  156.         push @{$self->{stack}}, [1, sub { return $_[0] }];
  157.         return "%0" . $len . "d";
  158.  
  159. ##################
  160. #s - second#
  161. ##################
  162.     } elsif($first eq "s") {
  163.         push @{$self->{stack}}, [0, sub { return $_[0] }];
  164.         return "%0" . $len . "d";
  165.  
  166. ##################
  167. #E - day of week #
  168. ##################
  169.     } elsif($first eq "E") {
  170.         push @{$self->{stack}}, [6, sub { $WEEK_DAYS[$_[0]] }];
  171.         return "%${len}s";
  172.  
  173. ######################
  174. #D - day of the year #
  175. ######################
  176.     } elsif($first eq "D") {
  177.         push @{$self->{stack}}, [7, sub { $_[0] }];
  178.         return "%${len}s";
  179.  
  180. ######################
  181. #a - am/pm marker    #
  182. ######################
  183.     } elsif($first eq "a") {
  184.         push @{$self->{stack}}, [2, sub { $_[0] < 12 ? "AM" : "PM" }];
  185.         return "%${len}s";
  186.  
  187. ######################
  188. #S - milliseconds    #
  189. ######################
  190.     } elsif($first eq "S") {
  191.         push @{$self->{stack}}, 
  192.              [9, sub { substr sprintf("%06d", $_[0]), 0, $len }];
  193.         return "%s";
  194.  
  195. #############################
  196. #Something that's not defined
  197. #(F=day of week in month
  198. # w=week in year W=week in month
  199. # k=hour in day K=hour in am/pm
  200. # z=timezone
  201. #############################
  202.     } else {
  203.         return "-- '$first' not (yet) implemented --";
  204.     }
  205.  
  206.     return $string;
  207. }
  208.  
  209. ###########################################
  210. sub format {
  211. ###########################################
  212.     my($self, $secs, $msecs) = @_;
  213.  
  214.     $msecs = 0 unless defined $msecs;
  215.  
  216.     my @time; 
  217.  
  218.     if($GMTIME) {
  219.         @time = gmtime($secs);
  220.     } else {
  221.         @time = localtime($secs);
  222.     }
  223.  
  224.         # add milliseconds
  225.     push @time, $msecs;
  226.  
  227.     my @values = ();
  228.  
  229.     for(@{$self->{stack}}) {
  230.         my($val, $code) = @$_;
  231.         if($code) {
  232.             push @values, $code->($time[$val]);
  233.         } else {
  234.             push @values, $time[$val];
  235.         }
  236.     }
  237.  
  238.     return sprintf($self->{fmt}, @values);
  239. }
  240.  
  241. 1;
  242.  
  243. __END__
  244.  
  245. =head1 NAME
  246.  
  247. Log::Log4perl::DateFormat - Log4perl advanced date formatter helper class
  248.  
  249. =head1 SYNOPSIS
  250.  
  251.     use Log::Log4perl::DateFormat;
  252.  
  253.     my $format = Log::Log4perl::DateFormat->new("HH:mm:ss,SSS");
  254.  
  255.     # Simple time, resolution in seconds
  256.     my $time = time();
  257.     print $format->format($time), "\n";
  258.         # => "17:02:39,000"
  259.  
  260.     # Advanced time, resultion in milliseconds
  261.     use Time::HiRes;
  262.     my ($secs, $msecs) = Time::HiRes::gettimeofday();
  263.     print $format->format($secs, $msecs), "\n";
  264.         # => "17:02:39,959"
  265.  
  266. =head1 DESCRIPTION
  267.  
  268. C<Log::Log4perl::DateFormat> is a low-level helper class for the 
  269. advanced date formatting functions in C<Log::Log4perl::Layout::PatternLayout>.
  270.  
  271. Unless you're writing your own Layout class like
  272. L<Log::Log4perl::Layout::PatternLayout>, there's probably not much use
  273. for you to read this.
  274.  
  275. C<Log::Log4perl::DateFormat> is a formatter which allows dates to be
  276. formatted according to the log4j spec on
  277.  
  278.     http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
  279.  
  280. which allows the following placeholders to be recognized and processed:
  281.  
  282.     Symbol Meaning              Presentation    Example
  283.     ------ -------              ------------    -------
  284.     G      era designator       (Text)          AD
  285.     y      year                 (Number)        1996
  286.     M      month in year        (Text & Number) July & 07
  287.     d      day in month         (Number)        10
  288.     h      hour in am/pm (1~12) (Number)        12
  289.     H      hour in day (0~23)   (Number)        0
  290.     m      minute in hour       (Number)        30
  291.     s      second in minute     (Number)        55
  292.     S      millisecond          (Number)        978
  293.     E      day in week          (Text)          Tuesday
  294.     D      day in year          (Number)        189
  295.     F      day of week in month (Number)        2 (2nd Wed in July)
  296.     w      week in year         (Number)        27
  297.     W      week in month        (Number)        2
  298.     a      am/pm marker         (Text)          PM
  299.     k      hour in day (1~24)   (Number)        24
  300.     K      hour in am/pm (0~11) (Number)        0
  301.     z      time zone            (Text)          Pacific Standard Time
  302.     '      escape for text      (Delimiter)
  303.     ''     single quote         (Literal)       '
  304.  
  305. For example, if you want to format the current Unix time in 
  306. C<"MM/dd HH:mm"> format, all you have to do is this:
  307.  
  308.     use Log::Log4perl::DateFormat;
  309.  
  310.     my $format = Log::Log4perl::DateFormat->new("MM/dd HH:mm");
  311.  
  312.     my $time = time();
  313.     print $format->format($time), "\n";
  314.  
  315. While the C<new()> method is expensive, because it parses the format
  316. strings and sets up all kinds of structures behind the scenes, 
  317. followup calls to C<format()> are fast, because C<DateFormat> will
  318. just call C<localtime()> and C<sprintf()> once to return the formatted
  319. date/time string.
  320.  
  321. So, typically, you would initialize the formatter once and then reuse
  322. it over and over again to display all kinds of time values.
  323.  
  324. Also, for your convenience, 
  325. the following predefined formats are available, just as outlined in the
  326. log4j spec:
  327.  
  328.     Format   Equivalent                 Example
  329.     ABSOLUTE "HH:mm:ss,SSS"             "15:49:37,459"
  330.     DATE     "dd MMM yyyy HH:mm:ss,SSS" "06 Nov 1994 15:49:37,459"
  331.     ISO8601  "yyyy-MM-dd HH:mm:ss,SSS"  "1999-11-27 15:49:37,459"
  332.  
  333. So, instead of passing 
  334.  
  335.     Log::Log4perl::DateFormat->new("HH:mm:ss,SSS");
  336.  
  337. you could just as well say
  338.  
  339.     Log::Log4perl::DateFormat->new("ABSOLUTE");
  340.  
  341. and get the same result later on.
  342.  
  343. =head2 Known Shortcomings
  344.  
  345. The following placeholders are currently I<not> recognized, unless
  346. someone (and that could be you :) implements them:
  347.  
  348.     F day of week in month
  349.     w week in year 
  350.     W week in month
  351.     k hour in day 
  352.     K hour in am/pm
  353.     z timezone
  354.  
  355. Also, C<Log::Log4perl::DateFormat> just knows about English week and
  356. month names, internationalization support has to be added.
  357.  
  358. =head1 SEE ALSO
  359.  
  360. =head1 AUTHOR
  361.  
  362.     Mike Schilli, <log4perl@perlmeister.com>
  363.  
  364. =cut
  365.