Overview -------- Lager (as in the beer) is a logging framework for Erlang. Its purpose is to provide a more traditional way to perform logging in an erlang application that plays nicely with traditional UNIX logging tools like logrotate and syslog. [Travis-CI](http://travis-ci.org/basho/lager) :: ![Travis-CI](https://secure.travis-ci.org/basho/lager.png) Features -------- * Finer grained log levels (debug, info, notice, warning, error, critical, alert, emergency) * Logger calls are transformed using a parse transform to allow capturing Module/Function/Line/Pid information * When no handler is consuming a log level (eg. debug) no event is even sent to the log handler * Supports multiple backends, including console and file. * Rewrites common OTP error messages into more readable messages * Support for pretty printing records encountered at compile time * Tolerant in the face of large or many log messages, won't out of memory the node * Supports internal time and date based rotation, as well as external rotation tools * Syslog style log level comparison flags * Colored terminal output (requires R16+) Usage ----- To use lager in your application, you need to define it as a rebar dep or have some other way of including it in erlang's path. You can then add the following option to the erlang compiler flags ```erlang {parse_transform, lager_transform} ``` Alternately, you can add it to the module you wish to compile with logging enabled: ```erlang -compile([{parse_transform, lager_transform}]). ``` Before logging any messages, you'll need to start the lager application. The lager module's start function takes care of loading and starting any dependencies lager requires. ```erlang lager:start(). ``` You can also start lager on startup with a switch to `erl`: ```erlang erl -pa path/to/lager/ebin -s lager ``` Once you have built your code with lager and started the lager application, you can then generate log messages by doing the following: ```erlang lager:error("Some message") ``` Or: ```erlang lager:warning("Some message with a term: ~p", [Term]) ``` The general form is lager:Severity() where Severity is one of the log levels mentioned above. Configuration ------------- To configure lager's backends, you use an application variable (probably in your app.config): ```erlang {lager, [ {handlers, [ {lager_console_backend, info}, {lager_file_backend, [{file, "error.log"}, {level, error}]}, {lager_file_backend, [{file, "console.log"}, {level, info}]} ]} ]} ]}. ``` The available configuration options for each backend are listed in their module's documentation. Custom Formatting ----------------- All loggers have a default formatting that can be overriden. A formatter is any module that exports format(#lager_log_message{},Config#any()). It is specified as part of the configuration for the backend: ```erlang {lager, [ {handlers, [ {lager_console_backend, [info, {lager_default_formatter, [time," [",severity,"] ", message, "\n"]}}, {lager_file_backend, [{name, "error.log"}, {level, error}, {formatter, lager_default_formatter}, {formatter_config, [date, " ", time," [",severity,"] ",pid, " ", message, "\n"]}]}, {lager_file_backend, [{name, "console.log"}, {level, info}]} ]} ]} ]}. ``` Included is lager_default_formatter. This provides a generic, default formatting for log messages using a "semi-iolist" as configuration. Any iolist allowed elements in the configuration are printed verbatim. Atoms in the configuration are treated as metadata properties and extracted from the log message. The metadata properties date,time, message, and severity will always exist. The properties pid, file, line, module, function, and node will always exist if the parser transform is used. ``` ["Foo"] -> "Foo", regardless of message content. [message] -> The content of the logged message, alone. [{pid,"Unknown Pid"}] -> "" if pid is in the metadata, "Unknown Pid" if not. [{pid, ["My pid is ", pid], "Unknown Pid"}] -> if pid is in the metadata print "My pid is ", otherwise print "Unknown Pid" ``` Optionally, a tuple of {atom(),semi-iolist()} can be used. The atom will look up the property, but if not found it will use the semi-iolist() instead. These fallbacks can be nested or refer to other properties. ``` [{pid,"Unknown Pid"}] -> "" if pid is in the metadata, "Unknown Pid" if not. [{server,[$(,{pid,"Unknown Server"},$)]}}] -> user provided server metadata, otherwise "()", otherwise "(Unknown Server)" ``` Error logger integration ------------------------ Lager is also supplied with a error_logger handler module that translates traditional erlang error messages into a friendlier format and sends them into lager itself to be treated like a regular lager log call. To disable this, set the lager application variable `error_logger_redirect' to `false'. The error_logger handler will also log more complete error messages (protected with use of trunc_io) to a "crash log" which can be referred to for further information. The location of the crash log can be specified by the crash_log application variable. If undefined it is not written at all. Messages in the crash log are subject to a maximum message size which can be specified via the crash_log_msg_size application variable. Overload Protection ------------------- Prior to lager 2.0, the gen_event at the core of lager operated purely in synchronous mode. Asynchronous mode is faster, but has no protection against message queue overload. In lager 2.0, the gen_event takes a hybrid approach. it polls its own mailbox size and toggles the messaging between synchronous and asynchronous depending on mailbox size. ```erlang {async_threshold, 20}, {async_threshold_window, 5} ``` This will use async messaging until the mailbox exceeds 20 messages, at which point synchronous messaging will be used, and switch back to asynchronous, when size reduces to `20 - 5 = 15`. If you wish to disable this behaviour, simply set it to 'undefined'. It defaults to a low number to prevent the mailbox growing rapidly beyond the limit and causing problems. In general, lager should process messages as fast as they come in, so getting 20 behind should be relatively exceptional anyway. If you want to limit the number of messages per second allowed from error_logger, which is a good idea if you want to weather a flood of messages when lots of related processes crash, you can set a limit: ```erlang {error_logger_hwm, 50} ``` It is probably best to keep this number small. Runtime loglevel changes ------------------------ You can change the log level of any lager backend at runtime by doing the following: ```erlang lager:set_loglevel(lager_console_backend, debug). ``` Or, for the backend with multiple handles (files, mainly): ```erlang lager:set_loglevel(lager_file_backend, "console.log", debug). ``` Lager keeps track of the minium log level being used by any backend and supresses generation of messages lower than that level. This means that debug log messages, when no backend is consuming debug messages, are effectively free. A simple benchmark of doing 1 million debug log messages while the minimum threshold was above that takes less than half a second. Syslog style loglevel comparison flags -------------------------------------- In addition to the regular log level names, you can also do finer grained masking of what you want to log: ``` info - info and higher (>= is implicit) =debug - only the debug level !=info - everything but the info level <=notice - notice and below "}]) ``` As of lager 2.0, you can also use a 3 tuple while tracing, where the second element is a comparison operator. The currently supported comparison operators are: * '<' - less than * '=' - equal to * '>' - greater than ```erlang lager:trace_console([{request, '>' 117}, {request, '<' 120}]) ``` Using '=' is equivalent to the 2-tuple form. Setting the truncation limit at compile-time -------------------------------------------- Lager defaults to truncating messages at 4096 bytes, you can alter this by using the {lager_truncation_size, X} option. In rebar, you can add it to erl_opts: ```erlang {erl_opts, [{parse_transform, lager_transform}, {lager_truncation_size, 1024}]}. ``` You can also pass it to erlc, if you prefer: ``` erlc -pa lager/ebin +'{parse_transform, lager_transform}' +'{lager_truncation_size, 1024}' file.erl ```