NAME

Log::Tiny - Log data with as little code as possible

VERSION

Version 1.3

SYNOPSIS

This module aims to be a light-weight implementation *similar* to Log::Log4perl for logging data to a file.

Its use is very straight forward:

use Log::Tiny;

my $log = Log::Tiny->new( 'myapp.log' ) or 
  die 'Could not log! (' . Log::Tiny->errstr . ')';

foreach ( 1 .. 20 ) { 
    $log->DEBUG( "Performing extensive computations on $_" ) if $DEBUG;
    unless ( extensively_compute( $_ ) ) {
        $log->WARN( 
            "Investigating error (this may take a while)..." 
        );
        $log->ERROR( find_error() );
        save_state();
        exit 1;
    } else {
        $log->INFO( "Everything's A-OK!" );
    }
}

FUNCTIONS

new

Create a new Log::Tiny object. The first argument is the log destination and, optionally, a format follows.

The destination may be:

  • a filename, which is opened for append (the common case);

  • an already-open filehandle (glob, glob ref or IO::Handle object), which is used as-is and not closed when the object is destroyed -- handy for logging to \*STDERR or a handle you manage;

  • the string "-", which logs to STDOUT.

An optional third argument is a hash reference of format specifications that are merged over (and so may extend or override) the defaults for this object only. The format table is snapshotted per-instance, so customising one Log::Tiny object never affects another.

format

You may, at any time, change the format. The log format is similar in style to the sprintf you know and love; and, as a peek inside the source of this module will tell you, sprintf is used internally. However, be advised that these log formats are not sprintf.

Interpolated data are specified by an percent sign ( % ), followed by a character. A literal percent sign can be specified via two in succession ( %% ). You may use any of the formatting attributes as noted in perlfunc, under "sprintf" (perldoc -f sprintf).

Internally, the format routine uses a data structure (hash) that can be seen near the beginning of this package. Any unrecognized interpolation variables will be returned literally. This means that, assuming $format{d} does not exist, "%d" in your format will result in "%d" being outputted to the log file. No interpolation will occur.

You may, of course, decide to modify the format data structure. I have done my best to ensure a wide range of variables for your usage, however. They are (currently) as follows:

c => category       => The method called (see below for more info)
C => lcategory      => lowercase category
D => date (strftime)=> %D{...} formats now() with the brace strftime
                       pattern (default "%Y-%m-%d %H:%M:%S")
f => program_file   => Value of $0
F => caller_file    => Calling file
g => gmtime         => Output of scalar L<gmtime> (localized date string)
L => caller_line    => Calling line
m => message        => Message sent to the log method
n => newline        => Value of $/
o => osname         => Value of $^O
p => pid            => Value of $$
P => caller_pkg     => Calling package
r => runtime        => Seconds the current process has been running for
S => caller_sub     => Calling subroutine
t => localtime      => Output of scalar L<localtime> (localized date 
                       string)
T => unix_time      => Time since epoch (L<time>)
u => effective_uid  => Value of $>
U => real_uid       => Value of $<
v => long_perl_ver  => Value of $] (5.008008)
V => short_perl_ver => A "short" string for the version ("5.8.8")

See perlvar for information on the used global variables, and perlfunc (under "caller") or perldoc -f caller for information on the "calling" variables. Oh, and make sure you add %n if you want newlines.

WHATEVER_YOU_WANT (log a message)

This method is whatever you want it to be. Any method called on a Log::Tiny object that is not reserved will be considered an attempt to log in the category named the same as the method that was called. Currently, only in-use methods are reserved; However, to account for expansion, please only use uppercase categories. See formats above for information on customizing the log messages.

would_log

Returns true if a message logged under the given category would actually be emitted (i.e. it passes both "log_only" and "min_level"). Use it to guard expensive work:

$log->DEBUG( sub { expensive_dump() } );   # or:
$log->DEBUG( pricey() ) if $log->would_log('DEBUG');

Passing a code reference as the message (above) is usually simpler: the sub is only called when the message would be logged.

errstr

Called as a class method, Log::Tiny-errstr > reveals the error that Log::Tiny encountered in creation or invocation.

Caller depth ($Log::Tiny::caller_depth)

The %F, %L, %P and %S formats report the file, line, package and subroutine of the code that called the log method. If you wrap your logging in a helper of your own, that helper becomes the apparent caller. As with Log::Log4perl, localise $Log::Tiny::caller_depth to skip the extra frame(s):

sub my_log {
    local $Log::Tiny::caller_depth = 1;
    $log->INFO( @_ );
}

log_only

Log only the given categories

levels

Define an ordered list of severities, least to most severe:

$log->levels( [qw(DEBUG INFO WARN ERROR FATAL)] );

Level names are compared case-insensitively. On their own, levels do nothing; combine with "min_level" to filter. This is independent of "log_only" (which whitelists exact categories).

min_level

Get or set the minimum severity that will be logged. Categories at or above the threshold are logged; those below it are dropped; categories not present in the "levels" list are always logged.

$log->min_level('WARN');   # set
my $current = $log->min_level;   # get (undef if unset)

Requires "levels" to have been called first. Returns undef (and sets "errstr") for an unknown level name.

LOGWARN / LOGDIE / LOGCARP / LOGCLUCK / LOGCROAK / LOGCONFESS

Log-and-warn/die convenience methods, modelled on Log::Log4perl. Each logs the message under a category (WARN for the warn/carp/cluck variants, FATAL for the die/croak/confess variants) and then raises it:

$log->LOGWARN("disk getting full");   # logs (WARN) then warn()s
$log->LOGDIE("out of disk");           # logs (FATAL) then die()s
$log->LOGCROAK("bad args");            # logs then Carp::croak()s

The CARP/CLUCK/CROAK/CONFESS variants delegate to Carp. These names are reserved and cannot be used as ordinary log categories.

EASY MODE

Import the :easy tag for a functional interface that logs through a single process-wide logger, so short scripts need not carry an object:

use Log::Tiny ':easy';
INFO("started");
ERROR("boom");
LOGDIE("fatal");

The functions exported are TRACE, DEBUG, INFO, WARN, ERROR, FATAL and the LOG* family above. The default logger writes to STDERR with the format [%D] [%c] %m%n; call "easy_init" to change the destination, format or level.

easy_init

Configure (or reconfigure) the :easy logger. Accepts either a positional ($destination, $format) pair or a hash reference:

Log::Tiny->easy_init('/var/log/app.log');
Log::Tiny->easy_init(\*STDOUT, '%D %m%n');
Log::Tiny->easy_init({ file => 'app.log', format => '%m%n',
                       level => 'INFO' });

The level key (hash form) installs the standard TRACE < DEBUG < INFO < WARN < ERROR < FATAL order and sets it as the "min_level" threshold. Returns the logger.

AUTHOR

Jordan M. Adler, <jmadler at cpan.org>

BUGS

Please report any bugs or feature requests to bug-log-tiny at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Log-Tiny. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc Log::Tiny

You can also look for information at:

ACKNOWLEDGEMENTS

Much thanks to Michael Schilli CPAN:mschilli for his great work on Log::Log4perl, of which this module's formatting concept is largely based upon.

COPYRIGHT & LICENSE

Copyright 2007-2022 Jordan M. Adler, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.