File Coverage

blib/lib/Log/Trace.pm
Criterion Covered Total %
statement 254 308 82.4
branch 104 154 67.5
condition 33 65 50.7
subroutine 41 49 83.6
pod 2 3 66.6
total 434 579 74.9


line stmt bran cond sub pod time code
1             package Log::Trace;
2 11     11   10692 use Carp;
  11         22  
  11         1058  
3              
4             #Hires times if available
5             eval
6             {
7             require Time::HiRes;
8             };
9              
10 11     11   61 use vars qw($VERSION @EXPORT);
  11         22  
  11         768  
11             @EXPORT = qw(TRACE_HERE TRACEF); # TRACE, DUMP
12 11     11   54 use strict qw(subs vars);
  11         22  
  11         431  
13 11     11   58 use Fcntl ':flock';
  11         19  
  11         51358  
14              
15             $VERSION = sprintf"%d.%03d", q$Revision: 1.70 $ =~ /: (\d+)\.(\d+)/;
16              
17             #################################################
18             # Importing
19             #################################################
20              
21 82     82   100 *{"_debug"} = 0 ? sub { warn __PACKAGE__ . " @_\n" } : sub {};
22              
23             #Import into calling packages
24             sub import
25             {
26 36     36   32292 my $pkg = shift;
27 36         82 my $callpkg = caller(0);
28 36         87 my @args = @_;
29 36 100       147 if (ref $args[1] eq 'HASH')
30             {
31             # e.g. 'import (print => {Verbose => 1})
32 5         23 @args = ($args[0], undef, @args[1..$#args])
33             }
34 36         127 $pkg->_import($callpkg, @args);
35             }
36              
37             sub deep_import # deprecated. use 'import Log::Trace {Deep => 1, ...} ...'
38             {
39 0     0 0 0 my $pkg = shift;
40 0         0 my $callpkg = caller(0);
41 0 0       0 my $params = ref $_[0] ? shift : {};
42 0         0 $params->{Deep} = 1;
43 0 0       0 push @_, undef if @_ == 1; # deep_import 'print';
44 0         0 $pkg->_import($callpkg, @_, $params);
45             }
46              
47              
48             sub TRACEF
49             {
50 3     3 1 440 my $callpkg = caller();
51 3         4 my $trace = *{"$callpkg\::TRACE"};
  3         11  
52 3 100       12 my $params = ref $_[0] ? shift : {};
53 3         5 my $format = shift;
54 3         12 $trace->($params, sprintf($format, @_));
55             }
56              
57              
58             sub TRACE_HERE
59             {
60 5     5 1 2330 my $callpkg = caller();
61 5 100       16 my $params = ref $_[0] ? shift : {};
62             # see 'perldoc -f caller'
63             # calling caller() from the DB package stores subroutine args in @DB::args
64 5         5 my @caller;
65 5         5 do {
66             package DB;
67 5         19 @caller = caller(1);
68 5 100       32 @caller = caller(0) unless $caller[0];
69             };
70 5         10 my $sub = $caller[3]; # the subroutine that called TRACE_HERE
71 5         19 my ($file, $line) = (caller(0))[1,2]; # the location of the TRACE_HERE
72 5         11 my $trace = *{"$callpkg\::TRACE"};
  5         17  
73 5 100 100     27 shift @DB::args if @DB::args && "$DB::args[0]" eq "$params";
74 5         24 $trace->($params, "In $sub(".join(",", @DB::args).") - line $line of $file");
75             }
76              
77              
78             #################################################
79             # Exporting
80             #################################################
81              
82             sub _import
83             {
84 37     37   60 my $pkg = shift;
85 37         4458 my (@packages) = shift;
86 37         82 my ($target, $arg, $params) = @_;
87 37 50       107 $target = '' unless defined $target;
88              
89 37 100       146 if ($params->{Deep}) {
90             # extend the package list
91 4         20 push @packages, _deep_import_packages($params->{Everywhere});
92             }
93 37 100       120 if ($params->{AutoImport}) {
94             # override the default require() to catch new modules being loaded
95 2         9 _install_require($pkg, $params, $target, $arg)
96             }
97              
98             # lookup: valid target > TRACE sub. These are also closures around '$arg'
99 5     5   11 my %import_targets = (
100             'print' => sub {_log_to_fh($arg, _log_normal(@_))},
101 1     1   2 'print-verbose' => sub {_log_to_fh($arg, _log_verbose(@_))},
102 1     1   4 'print-debug' => sub {_log_to_fh($arg, _log_debug(@_))},
103 3     3   7 'warn' => sub {warn _log_normal(@_)},
104 1     1   3 'warn-verbose' => sub {warn _log_verbose(@_)},
105 1     1   6 'warn-debug' => sub {warn _log_debug(@_)},
106 3     3   9 'buffer' => sub {$$arg .= _log_normal(@_)},
107 1     1   4 'buffer-verbose' => sub {$$arg .= _log_verbose(@_)},
108 1     1   5 'buffer-debug' => sub {$$arg .= _log_debug(@_)},
109 3     3   6 'file' => sub {_log_to_file($arg, _log_normal(@_))},
110 1     1   5 'file-verbose' => sub {_log_to_file($arg, _log_verbose(@_))},
111 1     1   4 'file-debug' => sub {_log_to_file($arg, _log_debug(@_))},
112 0     0   0 'log' => sub {_log_to_file($arg, _log_debug(@_))},
113 0     0   0 'syslog' => sub {_log_to_syslog($arg, _log_normal(@_))},
114 0     0   0 'syslog-verbose' => sub {_log_to_syslog($arg, _log_verbose(@_))},
115 0     0   0 'syslog-debug' => sub {_log_to_syslog($arg, _log_debug(@_))},
116 37         4361 'custom' => $arg,
117             );
118              
119 37         93 my $suffix = '';
120 37 100       131 $params->{Verbose} = 0 unless defined $params->{Verbose};
121 37 100       3743 if ($params->{Verbose} == 1)
    100          
122             {
123 4         7 $suffix = '-verbose';
124             }
125             elsif ($params->{Verbose} == 2)
126             {
127 4         10 $suffix = '-debug';
128             }
129 37 50       158 $target = $import_targets{$target.$suffix} ? $target.$suffix : $target;
130 37         134 _debug("Initialising target: $target");
131              
132 37         78 foreach my $export_to (@packages) {
133             # Check whether to export functions to the package
134 232 100       435 my $match = defined $params->{Match} ? $params->{Match} : '.';
135 232 100       848 next unless $export_to =~ /$match/;
136 41         51 my %exclude;
137 41 50       163 if (my $excl = $params->{Exclude}) {
138 0 0       0 %exclude = map {$_ => 1} ref $excl eq 'ARRAY' ? @$excl : $excl;
  0         0  
139             }
140 41         72 $exclude{+__PACKAGE__} = 1; # exclude ourselves
141 41 50       95 next if $exclude{$export_to};
142              
143 41         131 _debug("Exporting target:$target to $export_to");
144             # set up the TRACE/DUMP functions
145 41         56 my ($trace, $dump);
146 41 50 33     220 if ($target && $import_targets{$target})
147             {
148 41         115 $trace = _trace_maker($export_to, $params, $import_targets{$target});
149 41         115 $dump = _dump_maker($export_to, $params, $trace);
150             }
151             else
152             {
153             # Just export stub functions
154 0     0   0 $trace = $dump = sub {};
  0         0  
155 0 0       0 carp "$pkg imported with unknown target $target" if $target;
156             }
157              
158             # Now export ...
159 41         105 __replace_subroutine($export_to, 'TRACE', $trace);
160 41         85 __replace_subroutine($export_to, 'DUMP', $dump);
161 41         120 __replace_subroutine($export_to, 'TRACEF', \&TRACEF);
162 41         103 __replace_subroutine($export_to, 'TRACE_HERE', \&TRACE_HERE);
163              
164 41 100       1039 if ($params->{AllSubs})
165             {
166             # wrap all functions in package with calls to TRACE
167 3         11 _debug("wrapping all functions in $export_to");
168 3         10 _wrap_functions($export_to, $trace);
169             }
170             }
171             }
172              
173             sub __replace_subroutine
174             {
175 170     170   256 my ($package, $sub, $coderef) = @_;
176 170 50       393 if (defined \&{"${package}::$sub"})
  170         714  
177             {
178             # quietly remove existing stub function
179             # This avoids unsightly "subroutine foo redefined" warnings
180             # 'no warnings "redefine"' doesn't work pre perl 5.6
181 170         8944 eval "undef \$${package}::{'$sub'}";
182             }
183 170         1075 *{"${package}::$sub"} = $coderef;
  170         739  
184             }
185              
186             sub _trace_maker
187             {
188 41     41   168 my ($package, $params, $trace_sub) = @_;
189 41         69 my $trace_level = $params->{Level};
190             return sub
191             {
192 62     62   9297 local $@; # in-case TRACE is called from &DESTROY
193 62         75 my $rv;
194             eval
195 62         94 {
196 62 100 66     353 my $level = shift->{Level} if ($_[0] && ref $_[0] eq 'HASH');
197 62 100       144 return unless _evaluate_level($package, $trace_level, $level);
198 48         137 $rv = 1 && $trace_sub->(@_);
199             };
200 62 50       339 if ($@)
201             {
202 0         0 warn __PACKAGE__ . " : $@";
203             }
204 62         316 return $rv;
205             }
206 41         202 }
207              
208             sub _dump_maker
209             {
210 41     41   63 my ($package, $params, $trace_sub) = @_;
211 41         64 my $trace_level = $params->{Level};
212             return sub
213             {
214             # always return the dumped data regardless of level unless called in
215             # void context
216 3     3   2300 my $context = wantarray();
217 3         5 local $@; # in-case DUMP is called from &DESTROY
218 3         7 my $rv;
219             eval
220 3         8 {
221 3 100       14 return $rv = _dump($params, @_) if defined $context;
222              
223 2         3 my $level = undef;
224 2 50 33     17 if ($_[0] && ref $_[0] eq 'HASH' && defined $_[0]{Level})
      33        
225             {
226 0         0 $level = shift->{Level};
227             }
228 2 50       7 return unless _evaluate_level($package, $trace_level, $level);
229 2         7 my $dumped = _dump($params, @_);
230 2         8 $rv = 1 && $trace_sub->($dumped);
231             };
232 3 50       8 if ($@)
233             {
234 0         0 warn __PACKAGE__ . " : $@";
235             }
236 3         9 return $rv;
237             }
238 41         195 };
239              
240              
241             # returns a list of packages to export trace functions to
242             sub _deep_import_packages
243             {
244 4     4   11 my $all_packages = shift;
245              
246             # Build the list of packages
247 4         544 my @packages;
248 4         9 foreach my $module (@{_list_all_packages()})
  4         10  
249             {
250 770 100       1232 next if $module eq __PACKAGE__;
251 766 100 100     1545 next unless $all_packages || defined (&{"$module\::TRACE"});
  575         3639  
252 195         240 push @packages, $module;
253             }
254 4         129 return @packages;
255             }
256              
257              
258             my %_autowrap;
259             sub _wrap_functions {
260 3     3   5 my ($package, $trace) = @_;
261              
262 3 100       11 return if $_autowrap{$package};
263 2 50       9 $_autowrap{$package} = {} unless defined $_autowrap{$package};
264              
265 2         4 my $symbols = \%{$package . '::'};
  2         7  
266             # wrap coderefs in the caller's symbol table
267 2         8 foreach my $typeglob (keys %$symbols) {
268              
269             # skip TRACE/DUMP and other potential deep recursions
270 16 100       65 next if $typeglob =~ /^(?:TRACE(?:F|_HERE)?|DUMP|AUTOLOAD)$/;
271              
272             # only wrap code references
273 8         8 my $sub = *{$symbols->{$typeglob}}{CODE};
  8         27  
274 8 100 66     37 next unless (defined $sub and defined &$sub);
275              
276             # skip if sub is already wrapped
277 6 50       18 next if $_autowrap{$package}{$typeglob}++;
278              
279             # define wrapped subroutine body
280 6         8 my $sub_body = <<'WRAPPED';
281             my ($name) = "${package}::$typeglob";
282             my ($callpkg, $file, $line) = caller(1);
283             my $arg = $_[0] && ref($_[0]) ? ref($_[0]) . ', ...' : "";
284             $trace->( "${name}( $arg )" );
285             goto &$sub
286             WRAPPED
287              
288             # wrap subroutine, preserving prototypes
289 6         8 my $wrapped_sub;
290 6 50       21 if(defined (my $proto = prototype($sub)))
291             {
292 0         0 $wrapped_sub = eval "sub ($proto) { $sub_body }";
293             }
294             else
295             {
296 6 0 0 0   967 $wrapped_sub = eval "sub { $sub_body }";
  0 50 33     0  
  0 50 33     0  
  0 0 0     0  
  0 50 33     0  
  0 50 33     0  
  1         953  
  1         2  
  1         6  
  1         5  
  1         5  
  1         28  
  1         7  
  1         6  
  1         5  
  1         3  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  1         30  
  1         3  
  1         8  
  1         5  
  1         6  
  1         23  
  1         4  
  1         6  
  1         4  
  1         6  
297             }
298              
299 6         18 __replace_subroutine($package, $typeglob, $wrapped_sub);
300             }
301             }
302              
303              
304             # return a list of all defined packages in the symbol table
305             # we could use %INC, but we'd miss packages that are defined in other modules
306             sub _list_all_packages {
307 774     774   967 my ($package) = @_;
308 774 100       2012 $package = '' unless defined $package;
309 774         715 my @packages;
310              
311             # this is a recursive look in the symbol table:
312             # %main::
313             # CGI::
314             # Cookie::
315             # Data::
316             # Dumper::
317             # ...
318              
319 774         678 my %symbols = %{$package . "::"};
  774         20411  
320 774         4510 foreach my $module (keys %symbols)
321             {
322 14126 100       33592 next unless $module =~ s/::$//;
323             # ignore 'main' (deep recursion) and all invalid package names
324 778 100 100     2864 next if !$package && ($module eq 'main' || $module !~ /^[a-zA-Z_]\w*$/);
      66        
325              
326 770 100       1717 my $prefix = $package ? $package . '::' : '';
327             # Add this module
328 770         1333 push @packages, $prefix . $module;
329             # and recurse to sub-packages
330 770         863 push @packages, @{_list_all_packages($prefix . $module)};
  770         1685  
331             }
332 774         10563 return \@packages;
333             }
334              
335              
336             # Override the built-in require()
337             # This is tricky because these are treated differently by perl:
338             # 1. require CGI
339             # 2. require "CGI"
340             # We have no way of distinguishing the two, so we make a best guess
341             #
342             # This only works since perl 5.6.1
343             #
344             # See 'perlsub' for more information about overriding built-ins
345             sub _install_require
346             {
347 2     2   9 my ($pkg, $params, $target, @args) = @_;
348              
349             # CORE::require has prototype(;$), but we get "bareword foo not allowed"
350             # errors if we use that. prototype(*) works though
351             my $require = sub (*)
352             {
353 3     3   1520 local $^W;
354 3         38 my $what = shift;
355 3 100       16 return 1 if $INC{$what};
356 1         7 _debug("require $what");
357              
358 1         2 my $package;
359 1 50       14 if ($what =~ /^v?[\d_.]+$/) {
    50          
    0          
360             # take advantage of UNIVERSAL->VERSION($require) for a portable
361             # version check
362 0         0 local $_Log::Trace::PerlVersion::VERSION = $];
363 0         0 eval {_Log::Trace::PerlVersion->VERSION($what)};
  0         0  
364 0 0       0 if (my $error = $@) {
365 0         0 $error =~ s/_Log::Trace::PerlVersion/Perl/;
366 0         0 die $error; #rethrow exception
367             }
368 0         0 return 1;
369             } elsif ($what =~ /(.*)\.pm$/) {
370             # looks like a module name, get the main package from the filename
371             # (perl 5.8 & ActivePerl 5.6.1)
372 1         5 ($package = $1) =~ s{/}{::}g;
373             } elsif ($what =~ /^[a-zA-Z_]\w*(?:::\w+)*$/i) {
374             # package name: vanilla perl 5.6.1, 5.6.2
375 0         0 $package = $what;
376 0         0 ($what = "$what.pm") =~ s{::}{/}g;
377             }
378              
379 1         495 my $rv = CORE::require $what;
380 1 50 33     95 if ($rv && $package)
381             {
382             # import Log::Trace into package
383 1         8 return unless $params->{Everywhere}
384 1 50 33     7 || defined (&{"$package\::TRACE"});
385 1         7 $pkg->_import($package, $target, @args, $params);
386             }
387 1         25 return $rv;
388 2         14 };
389              
390             # Override global require, silencing "... used only once" warnings
391 2         11 *CORE::GLOBAL::require = *CORE::GLOBAL::require = $require;
392             }
393              
394              
395             # Returns caller info for exported functions
396             sub __caller
397             {
398             # We need to look several frames back, so we keep going until we find
399             # something from outside this package
400 13     13   17 my @caller;
401 13         27 for (1 .. 8) {
402 65         297 my @c = caller($_);
403 65 100       147 last unless defined $c[0];
404 52         149 @caller = @c;
405 52 50 66     225 last unless $caller[0] eq __PACKAGE__
406 4         79 || $caller[3] =~ /^@{[__PACKAGE__]}\::/o;
407             }
408              
409             # because we don't seem to get a call frame for main::__ANON__
410 13 50       74 $caller[0] = 'main' if ($caller[0] eq __PACKAGE__);
411 13         17 $caller[3] =~ s/^@{[__PACKAGE__]}\::.*/main::__ANON__/;
  13         114  
412 13         151 return @caller;
413             }
414              
415             #################################################
416             # TRACE guts
417             #################################################
418              
419             sub _evaluate_level
420             {
421 64     64   95 my ($callpkg, $imported_level, $trace_level) = @_;
422              
423 64 100       207 return 1 if ! defined $imported_level;
424              
425 27 100       140 if (ref $imported_level eq 'CODE')
    100          
    50          
426             {
427 2         7 return $imported_level->($callpkg, $trace_level);
428             }
429             elsif (ref $imported_level eq 'ARRAY')
430             {
431 7         12 for (@$imported_level)
432             {
433 19 100 66     46 return 1 if (! defined($_) && ! defined($trace_level));
434 18 100 100     72 next unless defined($trace_level) && defined($_);;
435 12 100       43 return 1 if $_ == $trace_level;
436             }
437             }
438             elsif (!ref $imported_level)
439             {
440 18 100       56 return unless defined $trace_level;
441 17         61 return $imported_level >= $trace_level;
442             }
443             }
444              
445             sub _log_normal
446             {
447 14     14   67 return join(",", @_)."\n";
448             }
449              
450             sub _log_verbose
451             {
452 4     4   15 my ($pack,$file,$line,$sub) = __caller();
453 4         29 return "$sub ($line) :: " . join( ", ", @_ ) . "\n";
454             }
455              
456             sub _log_debug
457             {
458 4     4   13 my ($pack,$file,$line,$sub) = __caller();
459 4         21 my $timestamp = _timestamp();
460 4         38 return "$file: $sub ($line) [$timestamp] " . join( ", ", @_ ) . "\n";
461             }
462              
463             sub _log_to_fh
464             {
465 7     7   13 my ($fh, @output) = @_;
466 7 100       18 $fh = \*STDOUT unless $fh;
467 7         26 print $fh @output;
468             }
469              
470             sub _log_to_file
471             {
472 5     5   6 my $filename = shift;
473 5         8 my ($pack,$file,$line,$sub) = __caller();
474              
475 5         14 local *LOG_FILE;
476 5 50       337 if (open (LOG_FILE, ">> $filename"))
477             {
478 5 50       7 if (eval {flock LOG_FILE, LOCK_EX|LOCK_NB})
  5         36  
479             {
480 5         42 print LOG_FILE @_;
481 5         129 flock LOG_FILE, LOCK_UN;
482 5         66 close LOG_FILE;
483             }
484             else
485             {
486 0         0 die "couldn't get lock on $filename : $!";
487             }
488             }
489             else
490             {
491 0         0 die "Cannot open $filename : $!";
492             }
493             }
494              
495             sub _log_to_syslog
496             {
497 0   0 0   0 my ($priority) = shift || 'debug';
498              
499 0 0       0 return unless eval {require Sys::Syslog};
  0         0  
500 0         0 Sys::Syslog::openlog(__PACKAGE__, 'pid');
501 0         0 my $rv = Sys::Syslog::syslog($priority, join ",", @_);
502 0         0 Sys::Syslog::closelog();
503 0         0 return $rv;
504             }
505              
506             sub _dump
507             {
508 3     3   9 my ($params, @args) = @_;
509              
510 3 100       8 my $msg = ref $args[0] ? '' : shift @args;
511 3 100 66     20 $msg .= ": " if($msg && @args);
512              
513 3         4 my $type;
514             eval
515 3         5 {
516 3 50       9 if ($params->{Dumper})
517             {
518 0         0 $type = 'Data::Serializer';
519 0         0 require Data::Serializer;
520 0 0       0 my $params = ref $params->{Dumper} ?
521             $params->{Dumper} : { serializer => $params->{Dumper} };
522 0         0 my $serialiser = Data::Serializer->new(%$params);
523 0         0 for (@args)
524             {
525 0         0 $msg .= $serialiser->raw_serialize($_) . "\n";
526             }
527             }
528             else
529             {
530 3         6 $type = 'Data::Dumper';
531 3         20 require Data::Dumper;
532             # avoid 'used $var only once' warning
533 3         7 local $Data::Dumper::Indent;
534 3         4 local $Data::Dumper::Sortkeys;
535 3         4 local $Data::Dumper::Quotekeys;
536 3         5 $Data::Dumper::Indent = 1;
537 3         3 $Data::Dumper::Sortkeys = 1;
538 3         4 $Data::Dumper::Quotekeys = 0;
539              
540 3         14 $msg .= Data::Dumper::Dumper(@args);
541             }
542             };
543 3 50       310 die "$type not available: $@" if $@;
544 3         9 return $msg;
545             }
546              
547             sub _gettimeofday()
548             {
549 4 50   4   58 return Time::HiRes::gettimeofday() if $INC{'Time/HiRes.pm'};
550 0         0 return (time(), undef);
551             }
552              
553             #Provide localtime-style timestamp with microsecond resolution if Time::HiRes
554             #is available
555             sub _timestamp
556             {
557 4     4   17 my ($epoch, $usec) = _gettimeofday();
558 4         817 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($epoch);
559 4         15 $year+=1900; $mon+=1;
  4         7  
560 4         27 my $stamp = sprintf("%4d-%02d-%02d %02d:%02d:%02d",$year,$mon,$mday,$hour,$min,$sec);
561 4 50       29 $stamp .= sprintf(".%.6d",$usec) if(defined $usec);
562 4         14 return $stamp;
563             }
564              
565             1;
566              
567             =head1 NAME
568              
569             Log::Trace - provides a unified approach to tracing
570              
571             =head1 SYNOPSIS
572              
573             # The tracing targets
574             use Log::Trace; # No output
575             use Log::Trace 'print'; # print to STDOUT
576             use Log::Trace log => '/var/log/foo.log'; # Output to log file
577             use Log::Trace print => { Level => 3 };
578              
579             # Switch on/off logging with a constant
580             use Log::Trace;
581             import Log::Trace ('log' => LOGFILE) if TRACING;
582              
583              
584             # Set up tracing for all packages that advertise TRACE
585             use Foo;
586             use Bar;
587             use Log::Trace warn => { Deep => 1 };
588              
589             # Sets up tracing in all subpackages excluding Foo
590             use Log::Trace warn => {Deep => 1, 'Exclude' => 'Foo'};
591              
592              
593             # Exported functions
594             TRACE("Record this...");
595             TRACE({Level => 2}, "Only shown if tracing level is 2 or higher");
596             TRACEF("A la printf: %d-%.2f", 1, 2.9999);
597             TRACE_HERE(); # Record where we are (file, line, sub, args)
598             DUMP(\@loh, \%hoh); # Trace out via Data::Dumper
599             DUMP("Title", \@loh); # Trace out via Data::Dumper
600             my $dump = DUMP(@args); # Dump is returned without being traced
601              
602             =head1 DESCRIPTION
603              
604             A module to provide a unified approach to tracing. A script can C
605             Log::Trace qw( E mode E )> to set the behaviour of the TRACE function.
606              
607             By default, the trace functions are exported to the calling package only. You
608             can export the trace functions to other packages with the C option. See
609             L<"OPTIONS"> for more information.
610              
611             All exports are in uppercase (to minimise collisions with "real" functions).
612              
613             =head1 FUNCTIONS
614              
615             =over 4
616              
617             =item TRACE(@args)
618              
619             Output a message. Where the message actually goes depends on how you imported
620             Log::Trace (See L<"Importing/enabling Log::Trace">)
621              
622             The first argument is an optional hashref of options:
623              
624             TRACE('A simple message');
625              
626             vs:
627              
628             TRACE({ Level => 2.1 }, 'A message at a specified trace level');
629              
630             =item TRACEF($format, @args)
631              
632             C equivalent of TRACE. Also accepts an optional hashref:
633              
634             TRACEF('%d items', scalar @items);
635             TRACEF({ Level => 5 }, '$%1.2d', $value);
636              
637             =item DUMP([$message,] @args)
638              
639             Serialises each of @args, optionally prepended with $message. If called in a
640             non-void context, DUMP will return the serialised data rather than TRACE
641             it. This is useful if you want to DUMP a datastructure at a specific tracing
642             level.
643              
644             DUMP('colours', [qw(red green blue)]); # outputs via TRACE
645             my $dump = DUMP('colours', [qw(red green blue)]); # output returned
646              
647             =item TRACE_HERE()
648              
649             TRACEs the current position on the call stack (file, line number, subroutine
650             name, subroutine args).
651              
652             TRACE_HERE();
653             TRACE_HERE({Level => 99});
654              
655             =back
656              
657             =head1 Importing/enabling Log::Trace
658              
659             =over 4
660              
661             =item import($target, [$arg], [\%params])
662              
663             Controls where TRACE messages go. This method is called automatically when you
664             call C<'use Log::Trace;'>, but you may explicitly call this method at
665             runtime. Compare the following:
666              
667             use Log::Trace 'print';
668              
669             which is the same as
670              
671             BEGIN {
672             require Log::Trace;
673             Log::Trace->import('print');
674             }
675              
676             Valid combinations of C<$target> and C are:
677              
678             =over 4
679              
680             =item print =E $filehandle
681              
682             Prints trace messages to the supplied C<$filehandle>. Defaults to C
683             if no file handle is specified.
684              
685             =item warn
686              
687             Prints trace messages via Cs to C.
688              
689             =item buffer =E \$buffer
690              
691             Appends trace messages to a string reference.
692              
693             =item file =E $filename
694              
695             Append trace messages to a file. If the file doesn't exist, it will be created.
696              
697             =item log =E $filename
698              
699             This is equivalent to:
700              
701             use Log::Trace file => $filename, {Verbose => 2};
702              
703             =item syslog =E $priority
704              
705             Logs trace messages to syslog via C, if available.
706              
707             You should consult your syslog configuration before using this option.
708              
709             The default C<$priority> is 'C', and the C is set to
710             C. You can configure the C, but beyond that, you can
711             implement your own syslogging via the C trace target.
712              
713             =item custom => \&custom_trace_sub
714              
715             Trace messages are processed by a custom subroutine. E.g.
716              
717             use Log::Trace custom => \&mylogger;
718              
719             sub mylogger {
720             my @messages = @_;
721             foreach (@messages) {
722             # highly sensitive trace messages!
723             tr/a-zA-Z/n-za-mN-ZA-M/;
724             print;
725             }
726             }
727              
728             =back
729              
730             The import C<\%params> are optional. These two statements are functionally the
731             same:
732              
733             import Log::Trace print => {Level => undef};
734             import Log::Trace 'print';
735              
736             See L<"OPTIONS"> for more information.
737              
738             B If you use the C tracing option, you should be careful about
739             supplying a subroutine named C.
740              
741             =back
742              
743             =head1 OPTIONS
744              
745             =over 4
746              
747             =item AllSubs =E BOOL
748              
749             Attaches a C statement to all subroutines in the package. This can be
750             used to track the execution path of your code. It is particularly useful when
751             used in conjunction with C and C options.
752              
753             B Anonymous subroutines and C are not Cd.
754              
755             =item AutoImport =E BOOL
756              
757             By default, C will only set up C routines in modules that
758             have already been loaded. This option overrides C so that modules
759             loaded after C can automatically be set up for tracing.
760              
761             B: This is an experimental feature. See the ENVIRONMENT NOTES
762             for information about behaviour under different versions of perl.
763              
764             This option has no effect on perl E 5.6
765              
766             =item Deep =E BOOL
767              
768             Attaches C to all packages (that define a TRACE function). Any
769             TRACEF, DUMP and TRACE_HERE routines will also be overridden in these packages.
770              
771             =item Dumper =E Data::Serializer backend
772              
773             Specify a serialiser to be used for DUMPing data structures.
774              
775             This should either be a string naming a Data::Serializer backend (e.g. "YAML")
776             or a hashref of parameters which will be passed to Data::Serializer, e.g.
777              
778             {
779             serializer => 'XML::Dumper',
780             options => {
781             dtd => 'path/to/my.dtd'
782             }
783             }
784              
785             Note that the raw_serialise() method of Data::Serializer is used. See L
786             for more information.
787            
788             If you do not have C installed, leave this option undefined to use the
789             C natively.
790              
791             Default: undef (use standalone Data::Dumper)
792              
793             =item Everywhere =E BOOL
794              
795             When used in conjunction with the C option, it will override the
796             standard behaviour of only enabling tracing in packages that define C
797             stubs.
798              
799             Default: false
800              
801             =item Exclude =E STRING|ARRAY
802              
803             Exclude a module or list of modules from tracing.
804              
805             =item Level =E NUMBER|LIST|CODE
806              
807             Specifies which trace levels to display.
808              
809             If no C is defined, all TRACE statements will be output.
810              
811             If the value is numeric, only TRACEs that are at the specified level or below
812             will be output.
813              
814             If the value is a list of numbers, only TRACEs that match the specified levels
815             are output.
816              
817             The level may also be a code reference which is passed the package name and the
818             TRACE level. It mst return a true value if the TRACE is to be output.
819              
820             Default: undef
821              
822             =item Match =E REGEX
823              
824             Exports trace functions to packages that match the supplied regular
825             expression. Can be used in conjunction with C. You can also use
826             C as an exclusion method if you give it a negative look-ahead.
827              
828             For example:
829              
830             Match => qr/^(?!Acme::)/ # will exclude every module beginning with Acme::
831              
832             and
833              
834             Match => qr/^Acme::/ # does the reverse
835              
836             Default: '.' # everything
837              
838             =item Verbose =E 0|1|2
839              
840             You can use this option to prepend extra information to each trace message. The
841             levels represent increasing levels of verbosity:
842              
843             0: the default*, don't add anything
844             1: adds subroutine name and line number to the trace output
845             2: As [1], plus a filename and timestamp (in ISO 8601 : 2000 format)
846              
847             This setting has no effect on the C or C targets.
848              
849             * I
850              
851             =back
852              
853             =head1 ENVIRONMENT NOTES
854              
855             The AutoImport feature overrides C which requires perl 5.6, but you may see unexpected errors if you aren't using at
856             least perl 5.8. The AutoImport option has no effect on perl E 5.6.
857              
858             In mod_perl or other persistent interpreter environments, different applications could trample on each other's
859             C routines if they use Deep (or Everywhere) option. For example application A could route all the trace output
860             from Package::Foo into "appA.log" and then application B could import Log::Trace over the top, re-routing all the trace output from Package::Foo
861             to "appB.log" for evermore. One way around this is to ensure you always import Log::Trace on every run in a persistent environment from all your
862             applications that use the Deep option. We may provide some more tools to work around this in a later version of C.
863              
864             C has not been tested in a multi-threaded application.
865              
866             =head1 DEPENDENCIES
867              
868             Carp
869             Time::HiRes (used if available)
870             Data::Dumper (used if available - necessary for meaningful DUMP output)
871             Data::Serializer (optional - to customise DUMP output)
872             Sys::Syslog (loaded on demand)
873              
874             =head1 RELATED MODULES
875              
876             =over 4
877              
878             =item Log::TraceMessages
879              
880             C is similar in design and purpose to C.
881             However, it only offers a subset of this module's functionality. Most notably,
882             it doesn't offer a mechanism to control the tracing output of an entire
883             application - tracing must be enabled on a module-by-module
884             basis. C also offers control over the output with the trace
885             levels and supports more output targets.
886              
887             =item Log::Agent
888              
889             C offers a procedural interface to logging. It strikes a good
890             balance between configurability and ease of use. It differs to C in
891             a number of ways. C has a concept of channels and priorities, while
892             C only offers levels. C also supports tracing code
893             execution path and the C import option. C trades a certain
894             amount of configurability for increased ease-of use.
895              
896             =item Log::Log4Perl
897              
898             A feature rich perl port of the popular C library for Java. It is
899             object-oriented and comprised of more than 30 modules. It has an impressive
900             feature set, but some people may be frightened of its complexity. In contrast,
901             to use C you need only remember up to 4 simple functions and a
902             handful of configuration options.
903              
904             =back
905              
906             =head1 SEE ALSO
907              
908             L - A guide to using Log::Trace
909              
910             =head1 VERSION
911              
912             $Revision: 1.70 $ on $Date: 2005/11/01 11:32:59 $ by $Author: colinr $
913              
914             =head1 AUTHOR
915              
916             John Alden and Simon Flack with some additions by Piers Kent and Wayne Myers
917            
918              
919             =head1 COPYRIGHT
920              
921             (c) BBC 2005. This program is free software; you can redistribute it and/or modify it under the GNU GPL.
922              
923             See the file COPYING in this distribution, or http://www.gnu.org/licenses/gpl.txt
924              
925             =cut