Debian Codegraph @

README

raw
1 NAME
2 Log::Contextual - Simple logging interface with a contextual log
3
4 VERSION
5 version 0.009001
6
7 SYNOPSIS
8 use Log::Contextual qw( :log :dlog set_logger with_logger );
9 use Log::Contextual::SimpleLogger;
10 use Log::Log4perl ':easy';
11 Log::Log4perl->easy_init($DEBUG);
12
13 my $logger = Log::Log4perl->get_logger;
14
15 set_logger $logger;
16
17 log_debug { 'program started' };
18
19 sub foo {
20
21 my $minilogger = Log::Contextual::SimpleLogger->new({
22 levels => [qw( trace debug )]
23 });
24
25 my @args = @_;
26
27 with_logger $minilogger => sub {
28 log_trace { 'foo entered' };
29 my ($foo, $bar) = Dlog_trace { "params for foo: $_" } @args;
30 # ...
31 slog_trace 'foo left';
32 };
33 }
34
35 foo();
36
37 Beginning with version 1.008 Log::Dispatchouli also works out of the box
38 with "Log::Contextual":
39
40 use Log::Contextual qw( :log :dlog set_logger );
41 use Log::Dispatchouli;
42 my $ld = Log::Dispatchouli->new({
43 ident => 'slrtbrfst',
44 to_stderr => 1,
45 debug => 1,
46 });
47
48 set_logger $ld;
49
50 log_debug { 'program started' };
51
52 DESCRIPTION
53 Major benefits:
54
55 * Efficient
56
57 The default logging functions take blocks, so if a log level is
58 disabled, the block will not run:
59
60 # the following won't run if debug is off
61 log_debug { "the new count in the database is " . $rs->count };
62
63 Similarly, the "D" prefixed methods only "Dumper" the input if the
64 level is enabled.
65
66 * Handy
67
68 The logging functions return their arguments, so you can stick them in
69 the middle of expressions:
70
71 for (log_debug { "downloading:\n" . join qq(\n), @_ } @urls) { ... }
72
73 * Generic
74
75 "Log::Contextual" is an interface for all major loggers. If you log
76 through "Log::Contextual" you will be able to swap underlying loggers
77 later.
78
79 * Powerful
80
81 "Log::Contextual" chooses which logger to use based on user defined
82 "CodeRef"s. Normally you don't need to know this, but you can take
83 advantage of it when you need to later.
84
85 * Scalable
86
87 If you just want to add logging to your basic application, start with
88 Log::Contextual::SimpleLogger and then as your needs grow you can
89 switch to Log::Dispatchouli or Log::Dispatch or Log::Log4perl or
90 whatever else.
91
92 This module is a simple interface to extensible logging. It exists to
93 abstract your logging interface so that logging is as painless as
94 possible, while still allowing you to switch from one logger to another.
95
96 It is bundled with a really basic logger, Log::Contextual::SimpleLogger,
97 but in general you should use a real logger instead. For something more
98 serious but not overly complicated, try Log::Dispatchouli (see
99 "SYNOPSIS" for example.)
100
101 A WORK IN PROGRESS
102 This module is certainly not complete, but we will not break the
103 interface lightly, so I would say it's safe to use in production code.
104 The main result from that at this point is that doing:
105
106 use Log::Contextual;
107
108 will die as we do not yet know what the defaults should be. If it turns
109 out that nearly everyone uses the ":log" tag and ":dlog" is really rare,
110 we'll probably make ":log" the default. But only time and usage will
111 tell.
112
113 IMPORT OPTIONS
114 See "SETTING DEFAULT IMPORT OPTIONS" for information on setting these
115 project wide.
116
117 -logger
118 When you import this module you may use "-logger" as a shortcut for
119 "set_logger", for example:
120
121 use Log::Contextual::SimpleLogger;
122 use Log::Contextual qw( :dlog ),
123 -logger => Log::Contextual::SimpleLogger->new({ levels => [qw( debug )] });
124
125 sometimes you might want to have the logger handy for other stuff, in
126 which case you might try something like the following:
127
128 my $var_log;
129 BEGIN { $var_log = VarLogger->new }
130 use Log::Contextual qw( :dlog ), -logger => $var_log;
131
132 -levels
133 The "-levels" import option allows you to define exactly which levels
134 your logger supports. So the default, "[qw(debug trace warn info error
135 fatal)]", works great for Log::Log4perl, but it doesn't support the
136 levels for Log::Dispatch. But supporting those levels is as easy as
137 doing
138
139 use Log::Contextual
140 -levels => [qw( debug info notice warning error critical alert emergency )];
141
142 -package_logger
143 The "-package_logger" import option is similar to the "-logger" import
144 option except "-package_logger" sets the logger for the current package.
145
146 Unlike "-default_logger", "-package_logger" cannot be overridden with
147 "set_logger" or "with_logger".
148
149 package My::Package;
150 use Log::Contextual::SimpleLogger;
151 use Log::Contextual qw( :log ),
152 -package_logger => Log::Contextual::WarnLogger->new({
153 env_prefix => 'MY_PACKAGE'
154 });
155
156 If you are interested in using this package for a module you are putting
157 on CPAN we recommend Log::Contextual::WarnLogger for your package
158 logger.
159
160 -default_logger
161 The "-default_logger" import option is similar to the "-logger" import
162 option except "-default_logger" sets the default logger for the current
163 package.
164
165 Basically it sets the logger to be used if "set_logger" is never called;
166 so
167
168 package My::Package;
169 use Log::Contextual::SimpleLogger;
170 use Log::Contextual qw( :log ),
171 -default_logger => Log::Contextual::WarnLogger->new({
172 env_prefix => 'MY_PACKAGE'
173 });
174
175 SETTING DEFAULT IMPORT OPTIONS
176 Eventually you will get tired of writing the following in every single
177 one of your packages:
178
179 use Log::Log4perl;
180 use Log::Log4perl ':easy';
181 BEGIN { Log::Log4perl->easy_init($DEBUG) }
182
183 use Log::Contextual -logger => Log::Log4perl->get_logger;
184
185 You can set any of the import options for your whole project if you
186 define your own "Log::Contextual" subclass as follows:
187
188 package MyApp::Log::Contextual;
189
190 use parent 'Log::Contextual';
191
192 use Log::Log4perl ':easy';
193 Log::Log4perl->easy_init($DEBUG)
194
195 sub arg_default_logger { $_[1] || Log::Log4perl->get_logger }
196 sub arg_levels { [qw(debug trace warn info error fatal custom_level)] }
197 sub default_import { ':log' }
198
199 # or maybe instead of default_logger
200 sub arg_package_logger { $_[1] }
201
202 # and almost definitely not this, which is only here for completeness
203 sub arg_logger { $_[1] }
204
205 Note the "$_[1] ||" in "arg_default_logger". All of these methods are
206 passed the values passed in from the arguments to the subclass, so you
207 can either throw them away, honor them, die on usage, etc. To be clear,
208 if you define your subclass, and someone uses it as follows:
209
210 use MyApp::Log::Contextual -default_logger => $foo,
211 -levels => [qw(bar baz biff)];
212
213 Your "arg_default_logger" method will get $foo and your "arg_levels"
214 will get "[qw(bar baz biff)]";
215
216 Additionally, the "default_import" method is what happens if a user
217 tries to use your subclass with no arguments. The default just dies, but
218 if you'd like to change the default to import a tag merely return the
219 tags you'd like to import. So the following will all work:
220
221 sub default_import { ':log' }
222
223 sub default_import { ':dlog' }
224
225 sub default_import { qw(:dlog :log ) }
226
227 See Log::Contextual::Easy::Default for an example of a subclass of
228 "Log::Contextual" that makes use of default import options.
229
230 FUNCTIONS
231 set_logger
232 my $logger = WarnLogger->new;
233 set_logger $logger;
234
235 Arguments: "LOGGER CODEREF"
236
237 "set_logger" will just set the current logger to whatever you pass it.
238 It expects a "CodeRef", but if you pass it something else it will wrap
239 it in a "CodeRef" for you. "set_logger" is really meant only to be
240 called from a top-level script. To avoid foot-shooting the function will
241 warn if you call it more than once.
242
243 with_logger
244 my $logger = WarnLogger->new;
245 with_logger $logger => sub {
246 if (1 == 0) {
247 log_fatal { 'Non Logical Universe Detected' };
248 } else {
249 log_info { 'All is good' };
250 }
251 };
252
253 Arguments: "LOGGER CODEREF", "CodeRef $to_execute"
254
255 "with_logger" sets the logger for the scope of the "CodeRef"
256 $to_execute. As with "set_logger", "with_logger" will wrap
257 $returning_logger with a "CodeRef" if needed.
258
259 has_logger
260 my $logger = WarnLogger->new;
261 set_logger $logger unless has_logger;
262
263 Arguments: none
264
265 "has_logger" will return true if a logger has been set.
266
267 log_$level
268 Import Tag: ":log"
269
270 Arguments: "CodeRef $returning_message, @args"
271
272 "log_$level" functions all work the same except that a different method
273 is called on the underlying $logger object. The basic pattern is:
274
275 sub log_$level (&@) {
276 if ($logger->is_$level) {
277 $logger->$level(shift->(@_));
278 }
279 @_
280 }
281
282 Note that the function returns its arguments. This can be used in a
283 number of ways, but often it's convenient just for partial inspection of
284 passthrough data
285
286 my @friends = log_trace {
287 'friends list being generated, data from first friend: ' .
288 Dumper($_[0]->TO_JSON)
289 } generate_friend_list();
290
291 If you want complete inspection of passthrough data, take a look at the
292 "Dlog_$level" functions.
293
294 Which functions are exported depends on what was passed to "-levels".
295 The default (no "-levels" option passed) would export:
296
297 log_trace
298 log_debug
299 log_info
300 log_warn
301 log_error
302 log_fatal
303 Note: "log_fatal" does not call "die" for you, see "EXCEPTIONS AND
304 ERROR HANDLING"
305
306 slog_$level
307 Mostly the same as "log_$level", but expects a string as first argument,
308 not a block. Arguments are passed through just the same, but since it's
309 just a string, interpolation of arguments into it must be done manually.
310
311 my @friends = slog_trace 'friends list being generated.', generate_friend_list();
312
313 logS_$level
314 Import Tag: ":log"
315
316 Arguments: "CodeRef $returning_message, Item $arg"
317
318 This is really just a special case of the "log_$level" functions. It
319 forces scalar context when that is what you need. Other than that it
320 works exactly same:
321
322 my $friend = logS_trace {
323 'I only have one friend: ' . Dumper($_[0]->TO_JSON)
324 } friend();
325
326 See also: "DlogS_$level".
327
328 slogS_$level
329 Mostly the same as "logS_$level", but expects a string as first
330 argument, not a block. Arguments are passed through just the same, but
331 since it's just a string, interpolation of arguments into it must be
332 done manually.
333
334 my $friend = slogS_trace 'I only have one friend.', friend();
335
336 Dlog_$level
337 Import Tag: ":dlog"
338
339 Arguments: "CodeRef $returning_message, @args"
340
341 All of the following six functions work the same as their "log_$level"
342 brethren, except they return what is passed into them and put the
343 stringified (with Data::Dumper::Concise) version of their args into $_.
344 This means you can do cool things like the following:
345
346 my @nicks = Dlog_debug { "names: $_" } map $_->value, $frew->names->all;
347
348 and the output might look something like:
349
350 names: "fREW"
351 "fRIOUX"
352 "fROOH"
353 "fRUE"
354 "fiSMBoC"
355
356 Which functions are exported depends on what was passed to "-levels".
357 The default (no "-levels" option passed) would export:
358
359 Dlog_trace
360 Dlog_debug
361 Dlog_info
362 Dlog_warn
363 Dlog_error
364 Dlog_fatal
365 Note: "Dlog_fatal" does not call "die" for you, see "EXCEPTIONS AND
366 ERROR HANDLING"
367
368 Dslog_$level
369 Mostly the same as "Dlog_$level", but expects a string as first
370 argument, not a block. Arguments are passed through just the same, but
371 since it's just a string, no interpolation point can be used, instead
372 the Dumper output is appended.
373
374 my @nicks = Dslog_debug "names: ", map $_->value, $frew->names->all;
375
376 DlogS_$level
377 Import Tag: ":dlog"
378
379 Arguments: "CodeRef $returning_message, Item $arg"
380
381 Like "logS_$level", these functions are a special case of "Dlog_$level".
382 They only take a single scalar after the $returning_message instead of
383 slurping up (and also setting "wantarray") all the @args
384
385 my $pals_rs = DlogS_debug { "pals resultset: $_" }
386 $schema->resultset('Pals')->search({ perlers => 1 });
387
388 DslogS_$level
389 Mostly the same as "DlogS_$level", but expects a string as first
390 argument, not a block. Arguments are passed through just the same, but
391 since it's just a string, no interpolation point can be used, instead
392 the Dumper output is appended.
393
394 my $pals_rs = DslogS_debug "pals resultset: ",
395 $schema->resultset('Pals')->search({ perlers => 1 });
396
397 LOGGER CODEREF
398 Anywhere a logger object can be passed, a coderef is accepted. This is
399 so that the user can use different logger objects based on runtime
400 information. The logger coderef is passed the package of the caller, and
401 the caller level the coderef needs to use if it wants more caller
402 information. The latter is in a hashref to allow for more options in the
403 future.
404
405 Here is a basic example of a logger that exploits "caller" to reproduce
406 the output of "warn" with a logger:
407
408 my @caller_info;
409 my $var_log = Log::Contextual::SimpleLogger->new({
410 levels => [qw(trace debug info warn error fatal)],
411 coderef => sub { chomp($_[0]); warn "$_[0] at $caller_info[1] line $caller_info[2].\n" }
412 });
413 my $warn_faker = sub {
414 my ($package, $args) = @_;
415 @caller_info = caller($args->{caller_level});
416 $var_log
417 };
418 set_logger($warn_faker);
419 log_debug { 'test' };
420
421 The following is an example that uses the information passed to the
422 logger coderef. It sets the global logger to $l3, the logger for the
423 "A1" package to $l1, except the "lol" method in "A1" which uses the $l2
424 logger and lastly the logger for the "A2" package to $l2.
425
426 Note that it increases the caller level as it dispatches based on where
427 the caller of the log function, not the log function itself.
428
429 my $complex_dispatcher = do {
430
431 my $l1 = ...;
432 my $l2 = ...;
433 my $l3 = ...;
434
435 my %registry = (
436 -logger => $l3,
437 A1 => {
438 -logger => $l1,
439 lol => $l2,
440 },
441 A2 => { -logger => $l2 },
442 );
443
444 sub {
445 my ( $package, $info ) = @_;
446
447 my $logger = $registry{'-logger'};
448 if (my $r = $registry{$package}) {
449 $logger = $r->{'-logger'} if $r->{'-logger'};
450 my (undef, undef, undef, $sub) = caller($info->{caller_level} + 1);
451 $sub =~ s/^\Q$package\E:://g;
452 $logger = $r->{$sub} if $r->{$sub};
453 }
454 return $logger;
455 }
456 };
457
458 set_logger $complex_dispatcher;
459
460 LOGGER INTERFACE
461 Because this module is ultimately pretty looking glue (glittery?) with
462 the awesome benefit of the Contextual part, users will often want to
463 make their favorite logger work with it. The following are the methods
464 that should be implemented in the logger:
465
466 is_trace
467 is_debug
468 is_info
469 is_warn
470 is_error
471 is_fatal
472 trace
473 debug
474 info
475 warn
476 error
477 fatal
478
479 The first six merely need to return true if that level is enabled. The
480 latter six take the results of whatever the user returned from their
481 coderef and log them. For a basic example see
482 Log::Contextual::SimpleLogger.
483
484 LOG ROUTING
485 In between the loggers and the log functions is a log router that is
486 responsible for finding a logger to handle the log event and passing the
487 log information to the logger. This relationship is described in the
488 documentation for "Log::Contextual::Role::Router".
489
490 "Log::Contextual" and packages that extend it will by default share a
491 router singleton that implements the with_logger() and set_logger()
492 functions and also respects the -logger, -package_logger, and
493 -default_logger import options with their associated default value
494 functions. The router singleton is available as the return value of the
495 router() function. Users of Log::Contextual may overload router() to
496 return instances of custom log routers that could for example work with
497 loggers that use a different interface.
498
499 EXCEPTIONS AND ERROR HANDLING
500 "Log::Contextual", by design, does not intentionally invoke "die" on
501 your behalf(*see footnote*) for "log_fatal".
502
503 Logging events are characterized as information, not flow control, and
504 conflating the two results in negative design anti-patterns.
505
506 As such, "log_fatal" would at be better used to communicate information
507 about a *future* failure, for example:
508
509 if ( condition ) {
510 log_fatal { "Bad Condition is true" };
511 die My::Exception->new();
512 }
513
514 This has a number of benefits:
515
516 * You're more likely to want to use useful Exception Objects and flow
517 control instead of cheating with log messages.
518
519 * You're less likely to run a risk of losing what the actual problem
520 was when some error occurs in your creation of the Exception Object
521
522 * You're less likely to run the risk of losing important log context
523 due to exceptions occurring mid way through "die" unwinding and
524 "exit" global destruction.
525
526 If you're still too lazy to use exceptions, then you can do what you
527 probably want as follows:
528
529 if ( ... ) {
530 log_fatal { "Bad condition is true" };
531 die "Bad condtion is true";
532 }
533
534 Or for ":dlog" style:
535
536 use Data::Dumper::Consise qw( Dumper );
537 if ( ... ) {
538 # Dlog_fatal but not
539 my $reason = "Bad condtion is true because: " . Dumper($thing);
540 log_fatal { $reason };
541 die $reason;
542 }
543
544 footnote
545 The underlying behaviour of "log_fatal" is dependent on the backing
546 library.
547
548 All the Loggers shipping with "Log::Contextual" behave this way, as do
549 many of the supported loggers, like "Log::Log4perl". However, not all
550 loggers work this way, and one must be careful.
551
552 "Log::Dispatch" doesn't support implementing "log_fatal" at all
553
554 "Log::Dispatchouli" implements "log_fatal" using "die" ( via Carp )
555
556 DESIGNER
557 mst - Matt S. Trout <[email protected]>
558
559 BUGS
560 Please report any bugs or feature requests on the bugtracker website
561 <https://github.com/haarg/Log-Contextual/issues>
562
563 When submitting a bug or request, please include a test-file or a patch
564 to an existing test-file that illustrates the bug or desired feature.
565
566 CONTRIBUTORS
567 * Christian Walde <[email protected]>
568
569 * Dan Book <[email protected]>
570
571 * Florian Schlichtin <[email protected]>
572
573 * Graham Knop <[email protected]>
574
575 * Jakob Voss <[email protected]>
576
577 * Karen Etheridge <[email protected]>
578
579 * Kent Fredric <[email protected]>
580
581 * Matt S Trout <[email protected]>
582
583 * Peter Rabbitson <[email protected]>
584
585 * Philippe Bruhat (BooK) <[email protected]>
586
587 * Tyler Riddle <[email protected]>
588
589 * Wes Malone <[email protected]>
590
591 AUTHOR
592 Arthur Axel "fREW" Schmidt <[email protected]>
593
594 COPYRIGHT AND LICENSE
595 This software is copyright (c) 2024 by Arthur Axel "fREW" Schmidt.
596
597 This is free software; you can redistribute it and/or modify it under
598 the same terms as the Perl 5 programming language system itself.
599