AccessLog/Formatter.pm untested

filter: Statementstmt 0.0% 0 / 139 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 229 CC 11 SCAR 35.9
CC
11
Cov
0%
format_line
72.0
item
6.0
escape_string
6.0
CRAP 36.4
1 package Catalyst::Plugin::AccessLog::Formatter;
2  
3 # ABSTRACT: Log formatter for Catalyst::Plugin::AccessLog
4 our $VERSION = '1.10'; # VERSION
5 our $AUTHORITY = 'cpan:ARODLAND'; # AUTHORITY
6  
7 use namespace::autoclean;
8 use Moose;
9 use DateTime;
10  
11 my %items;
12  
13 sub item {
14 my ($names, $code) = @_;
15 $names = [ $names ] unless ref $names;
16  
17 $items{$_} = $code for @$names;
18 }
19  
20 my %whitespace_escapes = (
21 "\r" => "\\r",
22 "\n" => "\\n",
23 "\t" => "\\t",
24 "\x0b" => "\\v",
25 );
26  
27 # Approximate the rules for safely escaping headers/etc given in the apache docs
28 sub escape_string {
29 my $str = shift;
30 return "" unless defined $str and length $str;
31  
32 $str =~ s/(["\\])/\\$1/g;
33 $str =~ s/([\r\n\t\x0b])/$whitespace_escapes{$1}/eg;
34 $str =~ s/([^[:print:]])/sprintf '\x%02x', ord $1/eg;
35  
36 return $str;
37 }
38  
39 sub get_item {
40 my ($self, $c, $key, $arg) = @_;
41  
42 return "[unknown format key $key]" unless exists $items{$key};
43 return $items{$key}->($self, $c, $arg);
44 }
45  
46 sub format_line {
47 my ($self, $c) = @_;
48 my $format = $self->format;
49 my $output = "";
50  
51 while (1) {
52 my $argument = qr/\{ ( [^}]+ ) \}/x;
53 my $longopt = qr/\[ ( [^]]+ ) \]/x;
54  
55 if ($format =~ /\G \Z/cgx) { # Found end of string.
56 last;
57 } elsif ($format =~ /\G ( [^%]+ )/cgx) { # Found non-percenty text.
58 $output .= $1;
59 } elsif ($format =~ /\G \%\% /cgx) { # Literal percent
60 $output .= "%";
61 } elsif ($format =~ /\G \% $argument $longopt/cgx) { # Long opt with argument
62 $output .= $self->get_item($c, $2, $1);
63 } elsif ($format =~ /\G \% $longopt/cgx) { # Long opt
64 $output .= $self->get_item($c, $1);
65 } elsif ($format =~ /\G \% $argument (.)/cgx) { # Short opt with argument
66 $output .= $self->get_item($c, $2, $1);
67 } elsif ($format =~ /\G \% (.)/cgx) { # Short opt
68 $output .= $self->get_item($c, $1);
69 } else {
70 warn "Can't happen!";
71 }
72 }
73  
74 return $output;
75 }
76  
77 =head1 DESCRIPTION
78  
79 The log format argument is a string which will be used to generate each line
80 of the access log. The string consists of literal characters which will be
81 copied to the log output verbatim, and escapes, which will be replaced with
82 information about the request or the response. This format string is
83 intended to be compatible with the Apache C<LogFormat> directive, however it
84 contains some extensions and leaves a few features unimplemented.
85  
86 Escapes can be either B<short escapes> or B<long escapes>. Both types begin
87 with the "C<%>" character. Short escapes consist of a C<%> followed by a
88 single character, for example C<%h> for the remote hostname. Long
89 escapes consist of a C<%> followed by a name inside B<square brackets>, for
90 example C<%[remote_hostname]> for the same option. Apache-compatible
91 options have both short escapes and long escapes, while incompatible options
92 have only long escapes.
93  
94 Some escapes (currently C<%[time]>, C<%[apache_time]>, C<%[header]>, and
95 C<%[apache_header]>) may also take an argument, which can be optional or
96 required. The argument is placed inside B<curly braces> between the percent
97 sign and the name of the escape, for example C<%{User-agent}i> or
98 C<%{User-agent}[header]> to get the value of the C<User-agent> header.
99  
100 A literal percent-sign can be produced in the output using the escape
101 sequence C<%%>.
102  
103 =head2 Configuration
104  
105 The following are optional arguments passed to
106 C<< Catalyst::Plugin::AccessLog::Formatter->new >>. Ordinarily these values
107 will be provided by L<Catalyst::Plugin::AccessLog> from its C<formatter>
108 config hash.
109  
110 =over 4
111  
112 =item format
113  
114 B<Default:> C<'%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"'> (Apache
115 C<common> log format).
116  
117 The format string for each line of output. You can use Apache C<LogFormat>
118 strings, with a reasonably good level of compatibility, or you can use a
119 slightly more readable format. The log format is documented in detail in
120 L<Catalyst::Plugin::AccessLog::Formatter>.
121  
122 =cut
123  
124 has 'format' => (
125 is => 'rw',
126 default => '%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"',
127 );
128  
129 =item time_format
130  
131 B<Default:> C<'%Y-%m-%dT%H:%M:%S'> (ISO 8601)
132  
133 The default time format for the C<%t> / C<%[time]> escape. This is a
134 C<strftime> format string, which will be provided to L<DateTime>'s
135 C<strftime> method.
136  
137 =cut
138  
139 has 'time_format' => (
140 is => 'rw',
141 default => '%Y-%m-%dT%H:%M:%S',
142 );
143  
144 =item time_zone
145  
146 B<Default:> local
147  
148 The timezone to use when printing times in access logs. This will be passed
149 to L<DateTime::TimeZone>'s constructor. Olson timezone names, POSIX TZ
150 values, and the keywords C<"local"> and C<"UTC"> are reasonable choices.
151  
152 =cut
153  
154 has 'time_zone' => (
155 is => 'rw',
156 default => 'local',
157 );
158  
159 =item hostname_lookups
160  
161 B<Default:> B<false>
162  
163 If this option is set to a true value, then the C<%h> /
164 C<%[remote_hostname]> escape will resolve the client IP address using
165 reverse DNS. This is generally not recommended for reasons of performance
166 and security. Equivalent to the Apache option C<HostnameLookups>.
167  
168 =cut
169  
170 has 'hostname_lookups' => (
171 is => 'rw',
172 default => 0,
173 );
174  
175 =back
176  
177 =head2 Escapes
178  
179 =over 4
180  
181 =item %[remote_address], %a
182  
183 The IP address of the remote client.
184  
185 =cut
186  
187 item ['a', 'remote_address'] => sub {
188 return $_[1]->request->address;
189 };
190  
191 =item %[clf_size], %b
192  
193 The size of the response content in bytes. If the response content is empty,
194 produces a dash C<-> instead of 0. This is compatible with CLF.
195  
196 =cut
197  
198 item ['b', 'clf_size'] => sub {
199 return $_[1]->response->content_length || "-";
200 };
201  
202 =item %[size], %B
203  
204 The size of the response content in bytes. Always numeric, even for 0.
205  
206 =cut
207  
208 item ['B', 'size'] => sub {
209 return $_[1]->response->content_length;
210 };
211  
212 =item %[remote_host], %h
213  
214 The hostname of the remote client, if the C<hostname_lookups> config option
215 is true. Otherwise, the IP address of the remote client, as
216 C<%[remote_address]>.
217  
218 =cut
219  
220 item ['h', 'remote_host'] => sub {
221 my ($self, $c) = @_;
222 if ($self->hostname_lookups) {
223 return $c->request->hostname;
224 } else {
225 return $c->request->address;
226 }
227 };
228  
229 =item %[header], %i
230  
231 The value of the request header named in the (mandatory) argument, or "-" if
232 no such header was provided. Usage: C<%{User-agent}i> to get the
233 C<User-agent> request header.
234  
235 =cut
236  
237 item ['i', 'header'] => sub {
238 my ($self, $c, $arg) = @_;
239 my $header = $c->req->header($arg);
240 return "-" unless defined($header);
241 return escape_string($header);
242 };
243  
244 =item %l
245  
246 For Apache compatibility, this option produces a single dash C<->. In Apache
247 this option returns the remote username from an C<ident> check, if the
248 module is present, which it never is, which means it always produces a
249 single dash on Apache as well. We don't bother implementing ident.
250  
251 =cut
252  
253 item 'l' => sub { # for apache compat
254 return "-";
255 };
256  
257 =item %[method], %m
258  
259 The request method (e.g. GET, POST).
260  
261 =cut
262  
263 item ['m', 'method'] => sub {
264 return $_[1]->request->method;
265 };
266  
267 =item %[port], %p
268  
269 The port number that the request was received on. In apache this is the
270 server's "canonical port", however this is information that's not available
271 to Catalyst.
272  
273 =cut
274  
275 item ['p', 'port'] => sub {
276 return $_[1]->req->base->port;
277 };
278  
279 =item %[query], %q
280  
281 The query string (beginning with a ? if there is a query string, otherwise
282 an empty string).
283  
284 =cut
285  
286 item ['q', 'query' ] => sub {
287 my $qstring = $_[1]->req->uri->query;
288 if (defined $qstring && length $qstring) {
289 return "?$qstring";
290 } else {
291 return "";
292 }
293 };
294  
295 =item %[request_line], %r
296  
297 The first line of the HTTP request, e.g. C<"GET / HTTP/1.0">.
298  
299 =cut
300  
301 item ['r', 'request_line'] => sub { # Mostly for apache's sake
302 my ($self, $c) = @_;
303 my $path = $c->req->path;
304 my $query = $c->req->uri->query;
305 if (defined $query && length $query) {
306 $query = "?$query";
307 } else {
308 $query = "";
309 }
310 return $c->req->method . " /${path}${query} " . $c->req->protocol;
311 };
312  
313 =item %[status], %s
314  
315 The HTTP status of the response, e.g. 200 or 404.
316  
317 =cut
318  
319 item ['s', 'status'] => sub {
320 return $_[1]->response->status;
321 };
322  
323 =item %[apache_time], %t
324  
325 The time that the request was received.
326  
327 While this escape and the C<%[time]> escape both take an optional
328 C<strftime> argument, they differ in their default formats. This escape
329 defaults to a "human readable" format which is lousy to parse, but is
330 nonetheless compatible with apache.
331  
332 =cut
333  
334 item ['t', 'apache_time'] => sub {
335 my ($self, $c, $arg) = @_;
336 return "-" unless $c->use_stats;
337 my $format = $arg || '[%d/%b/%Y:%H:%M:%S %z]'; # Apache default
338 my @start_time = $c->stats->created;
339 return DateTime->from_epoch(epoch => $start_time[0] + $start_time[1] / 1_000_000,
340 time_zone => $self->time_zone)->strftime($format);
341 };
342  
343 =item %[time], %[datetime]
344  
345 The time that the request was received.
346  
347 While this escape and the C<%[apache_time]> escape both take an optional
348 C<strftime> argument, they differ in their default formats. This escape
349 defaults to the C<time_format> config option passed to the constructor.
350 If that option is not provided, the default is ISO 8601.
351  
352 =cut
353  
354 item ['time', 'datetime'] => sub {
355 my ($self, $c, $arg) = @_;
356 return "-" unless $c->use_stats;
357 my $format = $arg || $self->time_format;
358 my @start_time = $c->stats->created;
359 return DateTime->from_epoch(epoch => $start_time[0] + $start_time[1] / 1_000_000,
360 time_zone => $self->time_zone)->strftime($format);
361 };
362  
363 =item %[remote_user], %u
364  
365 The REMOTE_USER variable as set by HTTP basic auth, or certain frontend
366 authentication methods. Returns a dash C<-> if no such thing exists.
367  
368 =cut
369  
370 item ['u', 'remote_user'] => sub {
371 return $_[1]->request->remote_user || '-';
372 };
373  
374 =item %[host_port], %v, %V
375  
376 The host and the port of the request URI. Apache specifies that these should
377 be the server's "canonical" host and port, but this information is
378 unavailable to Catalyst.
379  
380 =cut
381  
382 item ['V', 'v', 'host_port'] => sub {
383 return $_[1]->request->base->host_port;
384 };
385  
386 =item %[hostname]
387  
388 The hostname of the request URI.
389  
390 =cut
391  
392 item 'hostname' => sub {
393 return $_[1]->request->base->host;
394 };
395  
396 =item %[path], %U
397  
398 The request path (relative to the application root, but with a leading
399 slash).
400  
401 =cut
402  
403 # Possibly improvement: use uri_for to absolutize this with base, and then
404 # take the path component off of that...
405 item ['U', 'path'] => sub {
406 return '/' . $_[1]->request->path;
407 };
408  
409 =item %[handle_time], %T
410  
411 The time spent handling this request, as provided by the C<< $c->stats >>
412 object. Returns a dash C<-> if stats are unavailable.
413  
414 =cut
415  
416 item ['T', 'handle_time'] => sub {
417 my ($self, $c) = @_;
418 if ($c->use_stats) {
419 return sprintf "%f", $c->stats->elapsed;
420 } else {
421 return "-";
422 }
423 };
424  
425 =item %[action]
426  
427 The private path of the Catalyst action that handled the request.
428  
429 =cut
430  
431 item 'action' => sub {
432 return $_[1]->action->reverse;
433 };
434  
435 =item %[sessionid]
436  
437 The session ID, if there is one, otherwise "-".
438  
439 =cut
440  
441 item 'sessionid' => sub {
442 my ($self, $c) = @_;
443 return "-" unless $c->can('sessionid') && defined $c->sessionid;
444 return $c->sessionid;
445 };
446  
447 =item %[userid]
448  
449 The user ID, if Authentication is enabled and a user exists, otherwise "-"
450  
451 =cut
452  
453 item 'userid' => sub {
454 my ($self, $c) = @_;
455 return "-" unless $c->can('user');
456 return "-" unless $c->user_exists && defined $c->user->id;
457 return $c->user->id;
458 };
459  
460 =item %[request_count]
461  
462 The request count for the current process, as displayed in debug info.
463  
464 =cut
465  
466 item 'request_count' => sub {
467 $Catalyst::COUNT;
468 };
469  
470 =item %[pid]
471  
472 The process ID of the instance handling the request.
473  
474 =cut
475  
476 item 'pid' => sub {
477 $$
478 };
479  
480 =back
481  
482 =cut
483  
484 1;