Public
Configuration
Memento.config!
— Function.config!([logger], level; fmt::AbstractString, levels::Dict{AbstractString, Int}, colorized::Bool) -> Logger
Sets the Memento._log_levels
, creates a default root logger with a DefaultHandler
that prints to stdout.
Arguments
- 'logger::Union{Logger, AbstractString}`: The logger to configure (optional)
level::AbstractString
: the minimum logging level to log message to the root logger (required).
Keywords
fmt::AbstractString
: a format string to pass to theDefaultFormatter
which describes how to log messages (defaults toMemento.DEFAULT_FMT_STRING
). By default, format tokens should match theDefaultRecord
fieldnames.levels
: the default logging levels to use (defaults toMemento._log_levels
).colorized
: whether or not the message to stdout should be colorized.recursive
: whether or not to recursive set the level of all child loggers.substitute
: whether or not to substitute the global logger with Memento (only supported on julia 0.7).propagate
: whether the logger should also send messages to parent loggers (default: true)
Returns
Logger
: the logger passed in, or the root logger.
Memento.register
— Function.register(::Logger)
Register an existing logger with Memento if it has not already been registered.
Memento.reset!
— Function.reset!()
Removes all registered loggers and reinitializes the root logger without any handlers.
Loggers
Memento.Logger
— Type.Logger
A Logger
is responsible for converting msg strings into Records
which are then passed to each handler. By default loggers propagate their message to their parent loggers.
Fields
name::AbstractString
: is the name of the logger (required).handlers::Dict{Any, Handler}
: is a collection ofHandler
s (defaults to emptyDict
).level::AbstractString
: the current minimum logging level for the logger to log message to handlers (defaults to "not_set").levels::Dict{AbstractString, Int}
: a mapping of available logging levels to their relative priority (represented as integer values) (defaults to usingMemento._log_levels
)record::Type
: theRecord
type that should be produced by this logger (defaults toDefaultRecord
).propagate::Bool
: whether or not this logger should propagate its message to its parent (defaults totrue
).
Memento.getlogger
— Function.getlogger(name::Module) -> Logger
Converts the Module
to a String
and calls get_logger(name::String)
.
Arguments
name::Module
: the Module a logger should be associated
Returns
Logger
: the logger associated with the provided Module.
Returns the logger.
getlogger(name="root") -> Logger
If the logger or its parents do not exist then they are initialized with no handlers and not set.
Arguments
name
: the name of the logger (defaults to "root")
Returns
Logger
: the logger.
Base.log
— Method.log(logger::Logger, rec::Record)
Logs rec
to all its logger handlers. If this logger is not the root logger and logger.propagate
is true
then the parent logger is called.
NOTE: This method calls all handlers asynchronously and is recursive, so you should call it with a @sync
in order to synchronize all handler tasks.
Arguments
logger::Logger
: the logger to logargs
to.rec::Record
: aRecord
to log
Base.log
— Method.log(logger::Logger, level::AbstractString, msg::AbstractString)
Creates a Record
with the logger name, level, levelnum and message and calls the other log
method (which may recursively call itself on parent loggers with the created Record
).
Arguments
logger::Logger
: the logger to log to.level::AbstractString
: the log level as aString
msg::AbstractString
: the msg to log as aString
Throws
CompositeException
: may be thrown if an error occurs in one of the handlers (which are run with@async
)
Base.log
— Method.log(::Function, ::Logger, ::AbstractString)
Same as log(logger, level, msg)
, but in this case the message can be a function that returns the log message string.
Arguments
msg::Function
: a function that returns a messageString
logger::Logger
: the logger to log tolevel::AbstractString
: the log level as aString
Throws
CompositeException
: may be thrown if an error occurs in one of the handlers (which are run with@async
)
Memento.getlevel
— Method.getlevel(::Logger) -> AbstractString
Returns the current logger level.
Memento.getlevels
— Method.getlevels(::Logger) -> Dict
Get the available log levels for a logger and their associated priorities.
Memento.setlevel!
— Method.setlevel!(logger::Logger, level::AbstractString; recursive=false)
Changes what level this logger should log at.
Memento.setlevel!
— Method.setlevel!(f::Function, logger::Logger, level::AbstractString; recursive=false)
Temporarily change the level a logger will log at for the duration of the function f
.
Memento.gethandlers
— Function.gethandlers(logger::Logger)
Returns logger.handlers
Base.push!
— Method.push!(logger::Logger, handler::Handler)
Adds a new Handler
to the logger.
Memento.getfilters
— Method.getfilters(logger::Logger) -> Array{Filter}
Returns the filters for the logger.
Base.push!
— Method.push!(logger::Logger, filter::Memento.Filter)
Adds an new Filter
to the logger.
Memento.getpath
— Function.getpath(logger::Logger) -> Vector{Logger}
Returns the path of logger from the root logger.
Memento.getchildren
— Function.getchildren(name)
Takes a string representing the name of a logger and returns its children. Child loggers are extracted assuming a naming convention of "foo.bar.baz", where "foo.bar.baz" is the child of "foo.bar" which is the child of "foo".
Arguments
name
: the name of the logger.
Returns
Vector{Logger}
Memento.isroot
— Function.isroot(::Logger)
Returns true if logger.name
is "root" or ""
Memento.isset
— Function.isset(::Logger)
Returns true or false as to whether the logger is set. (ie: logger.level != "not_set")
Memento.ispropagating
— Function.ispropagating(::Logger)
Returns true or false as to whether the logger is propagating.
Memento.setpropagating!
— Function.setpropagating!([::Function], ::Logger, [::Bool])
Sets the logger to be propagating or not (Defaults to true).
Memento.setrecord!
— Function.setrecord!(logger::Logger, rec::Type{R}) where {R<:Record}
Sets the record type for the logger.
Arguments
logger::Logger
: the logger to set.rec::Record
: ARecord
type to use for logging messages (ie:DefaultRecord
).
Memento.trace
— Function.trace(logger::Logger, msg::AbstractString)
Logs the message at the trace level.
trace(msg::Function, logger::Logger)
Logs the message produced by the provided function at the trace level.
Memento.debug
— Function.debug(logger::Logger, msg::AbstractString)
Logs the message at the debug level.
debug(msg::Function, logger::Logger)
Logs the message produced by the provided function at the debug level.
Memento.info
— Function.info(logger::Logger, msg::AbstractString)
Logs the message at the info level.
info(msg::Function, logger::Logger)
Logs the message produced by the provided function at the info level.
Memento.notice
— Function.notice(logger::Logger, msg::AbstractString)
Logs the message at the notice level.
notice(msg::Function, logger::Logger)
Logs the message produced by the provided function at the notice level.
Memento.warn
— Function.warn(logger::Logger, msg::AbstractString)
Logs the message at the warn level.
warn(msg::Function, logger::Logger)
Logs the message produced by the provided function at the warn level.
Base.error
— Function.error(logger::Logger, msg::AbstractString)
Logs the message at the error level and throws an ErrorException
with that message
error(msg::Function, logger::Logger)
Logs the message produced by the provided function at the error level and throws an ErrorException
with that message.
error(logger::Logger, exc::Exception)
Calls error(logger, msg)
with the contents of the Exception
, then throw the Exception
. If the exception is a CompositeException
, each contained exception is logged, then the CompositeException
is thrown.
Memento.critical
— Function.critical(logger::Logger, msg::AbstractString)
Logs the message at the critical level and throws an ErrorException
with that message
critical(msg::Function, logger::Logger)
Logs the message produced by the provided function at the critical level and throws an ErrorException
with that message.
critical(logger::Logger, exc::Exception)
Calls critical(logger, msg)
with the contents of the Exception
, then throw the Exception
. If the exception is a CompositeException
, each contained exception is logged, then the CompositeException
is thrown.
Memento.alert
— Function.alert(logger::Logger, msg::AbstractString)
Logs the message at the alert level and throws an ErrorException
with that message
alert(msg::Function, logger::Logger)
Logs the message produced by the provided function at the alert level and throws an ErrorException
with that message.
alert(logger::Logger, exc::Exception)
Calls alert(logger, msg)
with the contents of the Exception
, then throw the Exception
. If the exception is a CompositeException
, each contained exception is logged, then the CompositeException
is thrown.
Memento.emergency
— Function.emergency(logger::Logger, msg::AbstractString)
Logs the message at the emergency level and throws an ErrorException
with that message
emergency(msg::Function, logger::Logger)
Logs the message produced by the provided function at the emergency level and throws an ErrorException
with that message.
emergency(logger::Logger, exc::Exception)
Calls emergency(logger, msg)
with the contents of the Exception
, then throw the Exception
. If the exception is a CompositeException
, each contained exception is logged, then the CompositeException
is thrown.
Handlers
Memento.Handler
— Type.Handler
Manage formatting Record
s and logging the resulting String
. All Handler
subtypes must implement at least 1 log(::Handler, ::Record)
method.
NOTE: Handlers can be useful if you need to special case logging behaviour based on the Formatter
, IO
and/or Record
types.
Memento.DefaultHandler
— Type.DefaultHanlder
The DefaultHandler manages any Formatter
, IO
and Record
.
Fields:
- fmt: a
Formatter
for convertingRecord
s toStrings
- io: an
IO
type for printingString
to. - opts: a dictionary of optional arguments such as :iscolorized and :colors Ex) ```Dict{Symbol, Any}( :iscolorized => true, :opts[:colors] => Dict{AbstractString, Symbol}( "debug" => :blue, "info" => :green, ... ) )```
Memento.Escalator
— Type.Escalator(fmt=DefaultFormatter(); level="warn", levels=nothing)
Escalates any logs it sees above a certain level
and throws an EscalationError
.
Arguments
fmt::Formatter
: for convertingRecord
s to error messagesStrings
Keyword Arguments
level
: threshold level for when to error, otherwise this is a no-oplevels
: an alternate levels dictionary if we're considering non-default levels
Base.log
— Method.log(handler::Handler, rec::Record)
Checks the Handler
filters and if they all pass then emit
the record.
Memento.getlevel
— Method.getlevel(::Handler) -> AbstractString
Returns the current handler level. The default is "not_set".
Memento.getfilters
— Method.getfilters(handler::Handler) -> Array{Memento.Filter}
Returns the filters for the handler. The default is the standard level-based filter.
Memento.emit
— Function.emit{F, O}(handler::DefaultHandler{F ,O}, rec::Record) where {F<:Formatter, O<:IO}
Handles printing any Record
with any Formatter
and IO
types.
emit(
handler::DefaultHandler{F, O},
rec::Record
) where {F<:Formatter, O<:Syslogs.Syslog}
Handles printing any records with any Formatter
and a Syslog
IO
type.
Memento.setlevel!
— Method.setlevel!(handler::DefaultHandler, level::AbstractString)
Sets the minimum level required to emit
the record from the handler.
Base.push!
— Method.push!(handler::DefaultHandler, filter::Memento.Filter)
Adds an new Filter
to the handler.
Memento.getlevels
— Method.getlevels(::Handler) -> Union{Dict, Nothing}
Get the available log levels for a handler and their associated priorities. The default is nothing
, for handlers which do not perform level-based filtering.
Memento.setup_opts
— Function.setup_opts(opts) -> Dict
Sets the default :colors if opts[:is_colorized] == true
.
Formatters
Memento.Formatter
— Type.Formatter
A Formatter
must implement a format(::Formatter, ::Record)
method which takes a Record
and returns a String
representation of the log Record
.
Memento.DefaultFormatter
— Type.DefaultFormatter
The DefaultFormatter
uses a simple format string to build the log message. Fields from the Record
to be used should be wrapped curly brackets.
Ex) "[{level} | {name}]: {msg}" will print message of the form [info | root]: my info message. [warn | root]: my warning message. ...
Memento.DictFormatter
— Type.DictFormatter([aliases, serializer])
Formats the record to Dict that is amenable to serialization formats such as JSON and then runs the serializer function on the produced dictionary.
Arguments
aliases::Dict{Symbol, Symbol}
: Mapping where the keys represent aliases and values
represent existing record attributes to include in the dictionary (defaults to all attributes).
serializer::Function
: A function that takes a Dictionary and returns a string. Defaults
to string(dict)
.
Memento.format
— Function.format(::DefaultFormatter, ::Record) -> String
Iteratively replaces entries in the format string with the appropriate fields in the Record
.
format(::DictFormatter, ::Record) -> Dict
Converts :date, :lookup and :stacktrace to strings and dicts respectively.
Records
Memento.Record
— Type.Record
A dictionary-like container with Symbol
keys used to store information about a log events including the msg, date, level, stacktrace, etc. Formatter
s use Records
to format log message strings.
You can access the properties of a Record
by using getproperty
(ie: record.msg).
Subtypes of Record
should implement getproperty(::MyRecord, ::Symbol)
and key-value pair iteration.
Memento.getlevel
— Method.getlevel(::Record) -> AbstractString
Returns the record level.
Memento.DefaultRecord
— Type.DefaultRecord <: AttributeRecord
Stores the most common logging event information. NOTE: if you'd like more logging attributes you can:
- add them to DefaultRecord and open a pull request if the new attributes are applicable to most applications.
- make a custom
Record
type.
Fields
date::Attribute{ZonedDateTime}
: timestamp of log eventlevel::Attribute{AbstractString}
: log levellevelnum::Attribute{Int}
: integer value for log levelmsg::Attribute{AbstractString}
: the log message itselfname::Attribute{AbstractString}
: the name of the source loggerpid::Attribute{Int}
: the pid of where the log event occuredlookup::Attribute{StackFrame}
: the top StackFramestacktrace::Attribute{StackTrace}
: a stacktrace
Memento.Attribute
— Type.Attribute
An Attribute
represents a lazily evaluated field in a log Record
.
Fields
f::Function
: A function to evaluate in order to get a value if one is not set.x::Union{Some{T}, Nothing}
: A value that may or may not exist yet.
Memento.AttributeRecord
— Type.AttributeRecord <: Record
A Record
which stores its properties as Attribute
s for lazy evaluation.
Calling getproperty
or iterating will evaluate and cache the properties accessed.
Base.get
— Method.get(attr::Attribute{T}) -> T
Run set attr.x
to the output of attr.f
if attr.x
is not already set. We then return the value stored in attr.x
Base.Dict
— Method.Dict(rec::Record)
Extracts the Record
and its properties into a Dict
On AttributeRecord
s this may be an expensive operation, so you probably don't want to do this for every log record unless you're planning on using every Attribute
.
Memento.get_trace
— Function.get_trace()
Returns the StackTrace
with StackFrame
s from the Memento
module filtered out.
Memento.get_lookup
— Function.get_lookup(trace::Attribute{StackTrace})
Returns the top StackFrame
for trace
if it isn't empty.
IO
Memento.FileRoller
— Type.FileRoller <: IO
Is responsible for managing a rolling log file.
Fields
prefix::AbstractString
: filename prefix for the log.folder::AbstractString
: directory where the log should be written.filepath::AbstractString
: the full filepath for the logfile::IO
: the current file IO handlebyteswritten::Int64
: keeps track of how many bytes have been written to the current file.max_sz::Int
: the maximum number of bytes written to a file before rolling over to another.
Memento.getfile
— Function.getfile(folder::AbstractString, prefix::AbstractString) -> String, IO
Grabs the next log file.
Memento.getsuffix
— Function.getsuffix(::Integer) -> String
Formats the nth file suffix.
Memento.TestUtils
Memento.TestUtils.@test_log
— Macro.@test_log(logger, level, msg, expr)
Test that the expression expr
emits a record in the logger
with the specified level
string and contains the msg
string or matches the msg
regular expression. If msg
is a boolean function, tests whether msg(output)
returns true. If msg
is a tuple or array, checks that the output contains/matches each item in msg
. Returns the result of evaluating expr
.
This will temporarily add a test handler to the logger
which will always be removed after executing the expression.
See also @test_nolog
to check for the absence of a record.
Example
julia> using Memento, Memento.TestUtils
julia> logger = getlogger("test_log");
julia> m = "Hello World!";
julia> @test_log logger "info" "Hello" info(logger, m)
julia> @test_log logger "info" r"^Hello" info(logger, m)
julia> @test_log logger "info" ("Hello", r"World!$") info(logger, m) # All elements occursin
Memento.TestUtils.@test_nolog
— Macro.@test_nolog(logger, level, msg, expr)
Test that the expression expr
does not emit a record in the logger
with the specified level
string containing the msg
string or matching the msg
regular expression.
See also @test_log
for further details.
Test.@test_warn
— Macro.@test_warn(logger, msg, expr)
Convenience macro that calls @test_log(logger, "warn", msg, expr)
.
Test.@test_throws
— Macro.@test_throws(logger, extype, expr)
Disables the logger
and calls @test_throws extype expr
.
Misc
Memento.Filter
— Type.Filter
A wrapper around a function that takes a log Record
and returns a bool whether to skip logging it.
Fields
f::Function
: a function that should return a bool given a Record
Memento.EscalationError
— Type.EscalationError(msg)
An error type for log records that have been escalated to errors.
Memento.LoggerSerializationError
— Type.LoggerSerializationError(logger::Logger)
Provides a helpful error message when a logger cannot be serialized.