AnyEvent::Log(3)
π NAME π
This is the AnyEvent::Log(3) manual page, and the NAME section is literally: AnyEvent::Log - simple logging "framework". That's the whole vibe, bestie β simple logging with a cute little framework energy. π
β¨ SYNOPSIS β¨
Okay so here's the quick-start party. Simple uses:
use AnyEvent;
AE::log fatal => "No config found, cannot continue!"; # never returns
AE::log alert => "The battery died!";
AE::log crit => "The battery is too hot!";
AE::log error => "Division by zero attempted.";
AE::log warn => "Couldn't delete the file.";
AE::log note => "Attempted to create config, but config already exists.";
AE::log info => "File soandso successfully deleted.";
AE::log debug => "the function returned 3";
AE::log trace => "going to call function abc";
Log level overview:
LVL NAME SYSLOG PERL NOTE
1 fatal emerg exit system unusable, aborts program!
2 alert failure in primary system
3 critical crit failure in backup system
4 error err die non-urgent program errors, a bug
5 warn warning possible problem, not necessarily error
6 note notice unusual conditions
7 info normal messages, no action required
8 debug debugging messages for development
9 trace copious tracing output
"Complex" uses β for speed-sensitive code, like trace/debug messages where you don't wanna pay the cost unless it's actually on:
use AnyEvent::Log;
my $tracer = AnyEvent::Log::logger trace => \my $trace;
$tracer->("i am here") if $trace;
$tracer->(sub { "lots of data: " . Dumper $self }) if $trace;
Configuration (also look at the EXAMPLES section, bestie):
# set default logging level to suppress anything below "notice"
# i.e. enable logging at "notice" or above - the default is to
# to not log anything at all.
$AnyEvent::Log::FILTER->level ("notice");
# set logging for the current package to errors and higher only
AnyEvent::Log::ctx->level ("error");
# enable logging for the current package, regardless of global logging level
AnyEvent::Log::ctx->attach ($AnyEvent::Log::LOG);
# enable debug logging for module some::mod and enable logging by default
(AnyEvent::Log::ctx "some::mod")->level ("debug");
(AnyEvent::Log::ctx "some::mod")->attach ($AnyEvent::Log::LOG);
# send all critical and higher priority messages to syslog,
# regardless of (most) other settings
$AnyEvent::Log::COLLECT->attach (new AnyEvent::Log::Ctx
level => "critical",
log_to_syslog => "user",
);
π DESCRIPTION π
So this module implements a relatively simple "logging framework". It does not attempt to be "the" logging solution or even "a" logging solution for AnyEvent β AnyEvent simply creates logging messages internally, and this module more or less exposes the mechanism, with some extra spiff to allow using it from other modules as well. β¨
Remember that the default verbosity level is 4 ("error"), so only errors and more important messages will be logged, unless you set PERL_ANYEVENT_VERBOSE to a higher number before starting your program ("AE_VERBOSE=5" is recommended during development), or change the logging level at runtime with something like:
use AnyEvent::Log;
$AnyEvent::Log::FILTER->level ("info");
The design goal behind this module was to keep it simple (and small), but make it powerful enough to be potentially useful for any module, and extensive enough for the most common tasks, such as logging to multiple targets, or being able to log into a database. Like, it's giving "small but mighty" energy. π¦
The module is also usable before AnyEvent itself is initialised, in which case some of the functionality might be reduced.
The amount of documentation might indicate otherwise, but the runtime part of the module is still just below 300 lines of code. No cap. π
π¦ LOGGING LEVELS π¦
Logging levels in this module range from 1 (highest priority) to 9 (lowest priority). Note that the lowest numerical value is the highest priority, so when this document says "higher priority" it means "lower numerical value". Yes, it's one of those mappings β stay with me. π
Instead of specifying levels by name you can also specify them by aliases:
LVL NAME SYSLOG PERL NOTE
1 fatal emerg exit system unusable, aborts program!
2 alert failure in primary system
3 critical crit failure in backup system
4 error err die non-urgent program errors, a bug
5 warn warning possible problem, not necessarily error
6 note notice unusual conditions
7 info normal messages, no action required
8 debug debugging messages for development
9 trace copious tracing output
As you can see, some logging levels have multiple aliases β the first one is the "official" name, the second one the "syslog" name (if it differs) and the third one the "perl" name, suggesting (only!) that you log "die" messages at "error" priority. The NOTE column tries to provide some rationale on how to chose a logging level.
As a rough guideline, levels 1..3 are primarily meant for users of the program (admins, staff), and are the only ones logged to STDERR by default. Levels 4..6 are meant for users and developers alike, while levels 7..9 are usually meant for developers. π«Ά
You can normally only log a message once at highest priority level (1, "fatal"), because logging a fatal message will also quit the program β so use it sparingly :)
For example, a program that finds an unknown switch on the commandline might well use a fatal logging level to tell users about it β the "system" in this case would be the program, or module.
Some methods also offer some extra levels, such as 0, "off", "none" or "all" β these are only valid for the methods that documented them. Periodt. π
π LOGGING FUNCTIONS π
okay so these are the actual functions you'll be calling to log stuff. every single one of them uses the caller's package as the "logging context" β that's the whole vibe. also, bestie, log gets aliased to AnyEvent::log and AE::log as soon as the AnyEvent module is loaded, so you can be lazy about it β¨
AnyEvent::Log::log $level, $msg[, @args]β asks for$msgto be logged at$level, and returns true if the message actually got logged somewhere. yes, it tells you. iconic behavior tbh.- if the loglevel is
fatal, the program will abort. like, for real. π - if you only pass
$msg, it gets logged as-is. if you pass extra@args, then$msgis treated as ansprintfformat string. $msgshouldn't end with"\n", but honestly you may include it if that's convenient for you β no judgment. multiline messages are handled properly too, so go off π- last but not least:
$msgcan be a code reference, and then it's supposed to return the message. it only gets called when the message is actually going to be logged, which is a huge win if building the message is expensive. not me generating a whole dump for nothing π - this function saves and restores
$!and$@for you, so you literally don't have to. π«Ά - whether your message gets logged depends on the maximum log level and the caller's package. the return value is there so messages don't get "lost" β for example, when
AnyEvent::Debugdetects a runtime error it tries to log it atdielevel, but if that message is lost it just falls back towarn. - > ngl, you can (and should) call this as
AnyEvent::logorAE::logwithoutuse-ing this module, whenever possible (i.e. when you don't need any extra functionality), because those will load the logging module on demand only. they're also way shorter to type. slay. - also, if you're optionally generating a ton of debug messages (like when you're tracing some code), go look into using a logger callback plus a boolean enabler (see "logger", below). π
- if the loglevel is
Example β logging something at error level:
AE::log error => "something";
Example β using printf-formatting:
AE::log info => "%5d %-10.10s %s", $index, $category, $msg;
Example β only generate a costly dump when the message is actually being logged:
AE::log debug => sub { require Data::Dump; Data::Dump::dump \%cache };
$logger = AnyEvent::Log::logger $level[, \$enabled]β makes you a code reference that, when called, acts exactly likeAnyEvent::Log::logwas called right there with that level.$loggergets a$msgand optional@args, just likeAnyEvent::Log::logdoes:
my $debug_log = AnyEvent::Log::logger "debug";
$debug_log->("debug here");
$debug_log->("%06d emails processed", 12345);
$debug_log->(sub { $obj->as_string });
the whole idea here is deciding whether to log before actually logging β so when logger is called once but the returned callback gets called constantly, that's a tremendous speed win. π₯
despite that speed advantage, changes to your logging configuration will still be reflected by the logger callback, even if the config changes after it was created. no stale vibes.
to speed things up even more, you can bind a scalar variable to the logger β it'll be true if the logger should be called or not, and if it's false you can safely skip calling the logger entirely. this variable gets updated for as long as $logger is alive.
full example:
# near the init section
use AnyEvent::Log;
my $debug_log = AnyEvent:Log::logger debug => \my $debug;
# and later in your program
$debug_log->("yo, stuff here") if $debug;
$debug and $debug_log->("123");
AnyEvent::Log::exact_time $onβ by default,AnyEvent::LogusesAE::now, i.e. the cached eventloop time, for log timestamps. call this with a true value and it'll instead resort toAE::time, i.e. it fetches the current time on every single log message. this only makes a difference for event loops that actually cache the time (likeEVorAnyEvent::Loop).- you can change this setting at any time by calling this function. no locks, no drama. π¦
- since
AnyEvent::Loghas to work even before AnyEvent has been initialised, this switch also decides whether to useCORE::timeorTime::HiRes::timewhen logging a message before AnyEvent becomes available.
AnyEvent::Log::format_time $timestampβ formats a timestamp (the kind returned byAnyEvent->noworAnyEvent->timeor a whole bunch of other functions) exactly the wayAnyEvent::Logdoes. β¨- in your main program (as opposed to in your module) you can override the default timestamp display format by loading this module and then redefining this function.
- most commonly, this function gets used inside formatting callbacks.
AnyEvent::Log::default_format $time, $ctx, $level, $msgβ formats a log message using the given timestamp, logging context, log level and log message.- this is the formatting function used to format messages when no custom function is provided.
- same deal: in your main program (as opposed to in your module) you can override the default message format by loading this module and then redefining this function.
AnyEvent::Log::fatal_exit()β this is the function called after logging afatallog message. it must not return. ever. bestie. π«£- the default implementation simply calls
exit 1. - in your main program (as opposed to in your module) you can override the fatal exit function by loading this module and then redefining this function. just make sure you don't return. like, at all. π
- the default implementation simply calls
π LOGGING CONTEXTS π
so this module associates every log message with a so-called logging context, based on the caller's package. every single perl package gets its own logging context. every one. it's a whole ecosystem π§
a logging context has three major responsibilities: filtering, logging, and propagating the message.
for the first purpose β filtering β each context has a set of logging levels called the log level mask. messages that aren't in the set get ignored by this context (masked). blocked. not invited to the party π
for logging, the context stores two things: a formatting callback (takes the timestamp, context, level and string message, and formats it the way it should be logged) and a logging callback (responsible for actually logging the formatted message, and for telling AnyEvent::Log whether it has consumed the message or whether it should be propagated).
for propagation, a context can have any number of attached slave contexts. any message that's neither masked by the logging mask nor masked by the logging callback returning true will get passed to all slave contexts.
each call to a logging function will log the message at most once per context, so it doesn't matter (much) if there are cycles, or if the message can arrive at the same context via multiple paths. we love a non-exploding graph π
πΈ DEFAULTS πΈ
by default, all logging contexts have a full set of log levels (all), a disabled logging callback, and the default formatting callback.
package contexts have the package name as their logging title by default.
they have exactly one slave β the context of the parent package. the parent package is simply defined as the package name without the last component, i.e. AnyEvent::Debug::Wrapped becomes AnyEvent::Debug, and AnyEvent becomes... $AnyEvent::Log::COLLECT, which is the exception to the rule β just like the "parent" of any single-component package name in Perl is main, the default slave of any top-level package context is $AnyEvent::Log::COLLECT.
since perl packages only form an approximate hierarchy, this slave context can of course be removed. it's giving found family.
all other (anonymous) contexts have no slaves and an empty title by default.
when the module is loaded it creates the $AnyEvent::Log::LOG logging context that simply logs everything via warn, without propagating anything anywhere by default. the purpose of this context is to be a convenient place to override the global logging target or to attach additional log targets. it's not meant for filtering. read that again. π’
then it creates the $AnyEvent::Log::FILTER context, whose purpose is to suppress all messages with priority higher than $ENV{PERL_ANYEVENT_VERBOSE}. then it attaches the $AnyEvent::Log::LOG context to it. the purpose of the filter context is simply to provide filtering according to some global log level. classic gatekeeper behavior, honestly.
finally it creates the top-level package context $AnyEvent::Log::COLLECT and attaches the $AnyEvent::Log::FILTER context to it, but otherwise leaves it at default config. its purpose is simply to collect all log messages system-wide. the group chat admin, basically. π
the hierarchy is then:
any package, eventually -> $COLLECT -> $FILTER -> $LOG
the effect of all of this is that log messages, by default, wander up to the $AnyEvent::Log::COLLECT context where all messages normally end up, from there to $AnyEvent::Log::FILTER where log messages with lower priority than $ENV{PERL_ANYEVENT_VERBOSE} get filtered out, and then to the $AnyEvent::Log::LOG context to be passed to warn.
this makes it easy to set a global logging level (by modifying $FILTER), but still allow other contexts to send, for example, their debug and trace messages to the $LOG target despite the global logging level β or to attach additional log targets that log messages regardless of the global logging level. β¨ flexible queen β¨
it also makes it easy to modify the default warn-logger ($LOG) into something that logs to a file, or to attach additional logging targets (like logging to a file) by attaching it to $FILTER.
π CREATING/FINDING/DESTROYING CONTEXTS π
$ctx = AnyEvent::Log::ctx [$pkg]β this creates or returns a logging context (which is an object, btw).- if you give it a package name, then the context for that package gets returned.
- if you call it with no arguments at all, then you get the context for the caller's package (i.e. the same context a
AE::logcall would use). - if you pass
undef, then it creates a brand new anonymous context that isn't tied to any package and gets destroyed when no longer referenced. ghost context π»
AnyEvent::Log::resetβ resets all package contexts and recreates the default hierarchy if necessary, i.e. it resets the logging subsystem to defaults, as much as possible. this process keeps references to contexts held by other parts of the program intact, so nothing breaks. π«Ά- can be used to implement config-file (re-)loading: before loading a configuration, reset all contexts.
$ctx = new AnyEvent::Log::Ctx methodname => param...β a convenience constructor that makes it simpler to construct anonymous logging contexts. short, sweet, slay.
okay so each key-value pair results in an invocation of the method of the same name as the key with the value as parameter β unless the value is an arrayref, and then it calls the method with the contents of the array. The methods are called in the same order as specified. no cap, order matters π
Example: create a new logging context and set both the default logging level, some slave contexts and a logging callback.
$ctx = new AnyEvent::Log::Ctx
title => "dubious messages",
level => "error",
log_cb => sub { print STDOUT shift; 0 },
slaves => [$ctx1, $ctx, $ctx2],
;
CONFIGURING A LOG CONTEXT π
The following methods can be used to configure the logging context.
$ctx->title ([$new_title])
Returns the title of the logging context β this is the package name, for package contexts, and a user defined string for all others.
If $new_title is given, then it replaces the package name or title.
LOGGING LEVELS β¨
The following methods deal with the logging level set associated with the log context.
The most common method to use is probably $ctx->level ($level), which configures the specified and any higher priority levels.
All functions which accept a list of levels also accept the special string "all" which expands to all logging levels.
$ctx->levels ($level[, $level...)
Enables logging for the given levels and disables it for all others.
$ctx->level ($level)
Enables logging for the given level and all lower level (higher priority) ones. In addition to normal logging levels, specifying a level of 0 or "off" disables all logging for this level.
Example: log warnings, errors and higher priority messages.
$ctx->level ("warn");
$ctx->level (5); # same thing, just numeric
$ctx->enable ($level[, $level...])
Enables logging for the given levels, leaving all others unchanged.
$ctx->disable ($level[, $level...])
Disables logging for the given levels, leaving all others unchanged.
$ctx->cap ($level)
Caps the maximum priority to the given level, for all messages logged to, or passing through, this context. That is, while this doesn't affect whether a message is logged or passed on, the maximum priority of messages will be limited to the specified level β messages with a higher priority will be set to the specified priority.
Another way to view this is that ->level filters out messages with a too low priority, while ->cap modifies messages with a too high priority.
This is useful when different log targets have different interpretations of priority. For example, for a specific command line program, a wrong command line switch might well result in a "fatal" log message, while the same message, logged to syslog, is likely not fatal to the system or syslog facility as a whole, but more likely a mere "error".
This can be modeled by having a stderr logger that logs messages "as-is" and a syslog logger that logs messages with a level cap of, say, "error", or, for truly system-critical components, actually "critical".
SLAVE CONTEXTS π¦
The following methods attach and detach another logging context to a logging context.
Log messages are propagated to all slave contexts, unless the logging callback consumes the message.
$ctx->attach ($ctx2[, $ctx3...])
Attaches the given contexts as slaves to this context. It is not an error to add a context twice (the second add will be ignored).
A context can be specified either as package name or as a context object.
$ctx->detach ($ctx2[, $ctx3...])
Removes the given slaves from this context β it's not an error to attempt to remove a context that hasn't been added.
A context can be specified either as package name or as a context object.
$ctx->slaves ($ctx2[, $ctx3...])
Replaces all slaves attached to this context by the ones given.
LOG TARGETS π₯
The following methods configure how the logging context actually does the logging (which consists of formatting the message and printing it or whatever it wants to do with it).
$ctx->log_cb ($cb->($str))
Replaces the logging callback on the context ("undef" disables the logging callback).
The logging callback is responsible for handling formatted log messages (see "fmt_cb" below) β normally simple text strings that end with a newline (and are possibly multiline themselves).
It also has to return true iff it has consumed the log message, and false if it hasn't. Consuming a message means that it will not be sent to any slave context. When in doubt, return 0 from your logging callback.
Example: a very simple logging callback, simply dump the message to STDOUT and do not consume it.
$ctx->log_cb (sub { print STDERR shift; 0 });
You can filter messages by having a log callback that simply returns 1 and does not do anything with the message, but this counts as "message being logged" and might not be very efficient.
Example: propagate all messages except for log levels "debug" and "trace". The messages will still be generated, though, which can slow down your program.
$ctx->levels ("debug", "trace");
$ctx->log_cb (sub { 1 }); # do not log, but eat debug and trace messages
$ctx->fmt_cb ($fmt_cb->($timestamp, $orig_ctx, $level, $message))
Replaces the formatting callback on the context ("undef" restores the default formatter).
The callback is passed the (possibly fractional) timestamp, the original logging context (object, not title), the (numeric) logging level and the raw message string and needs to return a formatted log message. In most cases this will be a string, but it could just as well be an array reference that just stores the values.
If, for some reason, you want to use "caller" to find out more about the logger then you should walk up the call stack until you are no longer inside the "AnyEvent::Log" package.
To implement your own logging callback, you might find the "AnyEvent::Log::format_time" and "AnyEvent::Log::default_format" functions useful.
Example: format the message just as AnyEvent::Log would, by letting AnyEvent::Log do the work. This is a good basis to design a formatting callback that only changes minor aspects of the formatting.
$ctx->fmt_cb (sub {
my ($time, $ctx, $lvl, $msg) = @_;
AnyEvent::Log::default_format $time, $ctx, $lvl, $msg
});
Example: format just the raw message, with numeric log level in angle brackets.
$ctx->fmt_cb (sub {
my ($time, $ctx, $lvl, $msg) = @_;
"<$lvl>$msg\n"
});
Example: return an array reference with just the log values, and use "PApp::SQL::sql_exec" to store the message in a database.
$ctx->fmt_cb (sub { \@_ });
$ctx->log_cb (sub {
my ($msg) = @_;
sql_exec "insert into log (when, subsys, prio, msg) values (?, ?, ?, ?)",
$msg->[0] + 0,
"$msg->[1]",
$msg->[2] + 0,
"$msg->[3]";
0
});
$ctx->log_to_warn
Sets the "log_cb" to simply use "CORE::warn" to report any messages (usually this logs to STDERR).
$ctx->log_to_file ($path)
Sets the "log_cb" to log to a file (by appending), unbuffered. The function might return before the log file has been opened or created.
$ctx->log_to_path ($path)
Same as "->log_to_file", but opens the file for each message. This is much slower, but allows you to change/move/rename/delete the file at basically any time.
Needless(?) to say, if you do not want to be bitten by some evil person calling "chdir", the path should be absolute. Doesn't help with "chroot", but hey...
$ctx->log_to_syslog ([$facility])
Logs all messages via Sys::Syslog, mapping "trace" to "debug" and all the others in the obvious way. If specified, then the $facility is used as the facility ("user", "auth", "local0" and so on). The default facility is "user".
Note that this function also sets a "fmt_cb" β the logging part requires an array reference with [$level, $str] as input.
MESSAGE LOGGING π
These methods allow you to log messages directly to a context, without going via your package context.
$ctx->log ($level, $msg[, @params])
Same as "AnyEvent::Log::log", but uses the given context as log context.
Example: log a message in the context of another package.
(AnyEvent::Log::ctx "Other::Package")->log (warn => "heely bo");
$logger = $ctx->logger ($level[, \$enabled])
Same as "AnyEvent::Log::logger", but uses the given context as log context.
π CONFIGURATION VIA $ENV{PERL_ANYEVENT_LOG} π
Okay so bestie, you can also configure logging by setting the environment variable PERL_ANYEVENT_LOG (or AE_LOG) β yes, itβs giving βset it and forget itβ energy β¨
The value is one or more logging context specifications separated by : or whitespace. Each logging specification starts with a context name, followed by =, followed by zero or more comma-separated configuration directives. Here are some examples, and yes theyβre iconic:
# set default logging level
filter=warn
# log to file instead of to stderr
log=file=/tmp/mylog
# log to file in addition to stderr
log=+%file:%file=file=/tmp/mylog
# enable debug log messages, log warnings and above to syslog
filter=debug:log=+%warnings:%warnings=warn,syslog=LOG_LOCAL0
# log trace messages (only) from AnyEvent::Debug to file
AnyEvent::Debug=+%trace:%trace=only,trace,file=/tmp/tracelog
A context name in the log specification can be any of the following, bestie:
collect,filter,logβ these correspond to the three predefined$AnyEvent::Log::COLLECT,AnyEvent::Log::FILTER, and$AnyEvent::Log::LOGcontexts.%nameβ context names starting with a%are anonymous contexts created when the name is first mentioned. The difference from package contexts is that by default they have no attached slaves. This makes it possible to create new log contexts that can be referred to multiple times by name within the same log specification. Cute and reusable π- a perl package name β any other string references the logging context associated with the given Perl
package. In the unlikely case where you want to specify a package context that matches one of the other context name forms, you can add a::to the package name to force interpretation as a package.
The configuration specifications can be any number of the following:
stderrβ configures the context to use Perlβswarnfunction (which typically logs toSTDERR). Works likelog_to_warn.file=path β configures the context to log to a file with the given path. Works likelog_to_file.path=path β configures the context to log to a file with the given path. Works likelog_to_path.syslogorsyslog=expr β configures the context to log to syslog. If expr is given, then it is evaluated in theSys::Syslogpackage, so you could use:
log=syslog=LOG_LOCAL0
nologβ configures the context to not log anything by itself, which is the default. Same as$ctx->log_cb (undef).cap=level β caps logging messages entering this context at the given level, i.e. reduces the priority of messages with higher priority than this level. The default is0(oroff), meaning the priority will not be touched.0oroffβ sets the logging level of the context to0, i.e. all messages will be filtered out.allβ enables all logging levels, i.e. filtering will effectively be switched off (the default).onlyβ disables all logging levels, and changes the interpretation of following level specifications to enable the specified level only. Example: only enable debug messages for a context.
context=only,debug
exceptβ enables all logging levels, and changes the interpretation of following level specifications to disable that level. Rarely used. Example: enable all logging levels except fatal and trace (this is rather nonsensical).
filter=exept,fatal,trace
levelβ enables all logging levels, and changes the interpretation of following level specifications to be βthat level or any higher priority message.β This is the default. Example: log anything at or above warn level.
filter=warn
# or, more verbose
filter=only,level,warn
1..9or a logging level name (error,debugetc.) β a numeric loglevel or the name of a loglevel will be interpreted according to the most recentonly,exceptorleveldirective. By default, specifying a logging level enables that and any higher priority messages.+context β attaches the named context as slave to the context.+β a lone+detaches all contexts, i.e. clears the slave list from the context. Anonymous (%name) contexts have no attached slaves by default, but package contexts have the parent context as slave by default. Example: log messages fromMy::Moduleto a file, do not send them to the default log collector.
My::Module=+,file=/tmp/mymodulelog
Any character can be escaped by prefixing it with a \ (backslash), as usual, so to log to a file containing a comma, colon, backslash and some spaces in the filename, you would do this:
PERL_ANYEVENT_LOG='log=file=/some\ \:file\ with\,\ \\-escapes'
Since whitespace (which includes newlines) is allowed, it is fine to specify multiple lines in PERL_ANYEVENT_LOG, e.g.:
PERL_ANYEVENT_LOG="
filter=warn
AnyEvent::Debug=+%trace
%trace=only,trace,+log
" myprog
Also, in the unlikely case when you want to concatenate specifications, use whitespace as separator, as :: will be interpreted as part of a module name, an empty spec with two separators:
PERL_ANYEVENT_LOG="$PERL_ANYEVENT_LOG MyMod=debug"
π EXAMPLES π
This section shows some common configurations, both as code, and as PERL_ANYEVENT_LOG string. Slay, letβs go π
Setting the global logging level.
Either put PERL_ANYEVENT_VERBOSE="<number> into your environment before running your program, use PERL_ANYEVENT_LOG, or modify the log level of the root context at runtime:
PERL_ANYEVENT_VERBOSE=5 ./myprog
PERL_ANYEVENT_LOG=log=warn
$AnyEvent::Log::FILTER->level ("warn");
Append all messages to a file instead of sending them to STDERR.
This is affected by the global logging level.
$AnyEvent::Log::LOG->log_to_file ($path);
PERL_ANYEVENT_LOG=log=file=/some/path
Write all messages with priority error and higher to a file.
This writes them only when the global logging level allows it, because it is attached to the default context which is invoked after global filtering.
$AnyEvent::Log::FILTER->attach (
new AnyEvent::Log::Ctx log_to_file => $path);
PERL_ANYEVENT_LOG=filter=+%filelogger:%filelogger=file=/some/path
This writes them regardless of the global logging level, because it is attached to the toplevel context, which receives all messages before the global filtering.
$AnyEvent::Log::COLLECT->attach (
new AnyEvent::Log::Ctx log_to_file => $path);
PERL_ANYEVENT_LOG=%filelogger=file=/some/path:collect=+%filelogger
In both cases, messages are still written to STDERR.
Additionally log all messages with warn and higher priority to syslog, but cap at error.
This logs all messages to the default log target, but also logs messages with priority warn or higher (and not filtered otherwise) to syslog facility user. Messages with priority higher than error will be logged with level error.
$AnyEvent::Log::LOG->attach (
new AnyEvent::Log::Ctx
level => "warn",
cap => "error",
syslog => "user",
);
PERL_ANYEVENT_LOG=log=+%syslog:%syslog=warn,cap=error,syslog
Write trace messages (only) from AnyEvent::Debug to the default logging target(s).
Attach the $AnyEvent::Log::LOG context to the AnyEvent::Debug context β this simply circumvents the global filtering for trace messages.
my $debug = AnyEvent::Debug->AnyEvent::Log::ctx;
$debug->attach ($AnyEvent::Log::LOG);
PERL_ANYEVENT_LOG=AnyEvent::Debug=+log
This of course works for any package, not just AnyEvent::Debug, but assumes the log level for AnyEvent::Debug hasnβt been changed from the default.
π¦ ASYNCHRONOUS DISK I/O π¦
This module uses AnyEvent::IO to actually write log messages (in log_to_file and log_to_path), so it doesnβt block your program when the disk is busy and a non-blocking AnyEvent::IO backend is available. No cap, your program stays moving π
β¨
π AUTHOR π
Marc Lehmann <schmorp@schmorp.de>
http://anyevent.schmorp.de
Thatβs the whole page, bestie β source/version perl v5.42.0, dated 2019-09-18. Go log like the main character you are π
β¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-AnyEvent 7.17-160000.2.2 Β· GPL-1.0-or-later OR Artistic-1.0
- opensuse-leap 16.0: perl-AnyEvent 7.17-160000.2.2 Β· GPL-1.0-or-later OR Artistic-1.0
- opensuse-leap 16.0: perl-AnyEvent 7.17-160000.2.2 Β· GPL-1.0-or-later OR Artistic-1.0
- opensuse-leap 16.0: perl-AnyEvent 7.17-160000.2.2 Β· GPL-1.0-or-later OR Artistic-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms