Core Interface

This implements the core interface.

class logbook.Logger(name=None, level=0)

Instances of the Logger class represent a single logging channel. A “logging channel” indicates an area of an application. Exactly how an “area” is defined is up to the application developer.

Names used by logbook should be descriptive and are intended for user display, not for filtering. Filtering should happen based on the context information instead.

A logger internally is a subclass of a RecordDispatcher that implements the actual logic. If you want to implement a custom logger class, have a look at the interface of that class as well.

call_handlers(record)

Pass a record to all relevant handlers in the following order:

  • per-dispatcher handlers are handled first

  • afterwards all the current context handlers in the order they were pushed

Before the first handler is invoked, the record is processed (process_record()).

catch_exceptions(*args, **kwargs)

A context manager that catches exceptions and calls exception() for exceptions caught that way. Example:

with logger.catch_exceptions():
    execute_code_that_might_fail()
critical(*args, **kwargs)

Logs a LogRecord with the level set to CRITICAL.

debug(*args, **kwargs)

Logs a LogRecord with the level set to DEBUG.

disable()

Convenience method to disable this logger.

Raises

AttributeError – The disabled property is read-only, typically because it was overridden in a subclass.

New in version 1.0.

enable()

Convenience method to enable this logger.

Raises

AttributeError – The disabled property is read-only, typically because it was overridden in a subclass.

New in version 1.0.

error(*args, **kwargs)

Logs a LogRecord with the level set to ERROR.

exception(*args, **kwargs)

Works exactly like error() just that the message is optional and exception information is recorded.

group

optionally the name of the group this logger belongs to

handle(record)

Call the handlers for the specified record. This is invoked automatically when a record should be handled. The default implementation checks if the dispatcher is disabled and if the record level is greater than the level of the record dispatcher. In that case it will call the handlers (call_handlers()).

handlers

list of handlers specific for this record dispatcher

info(*args, **kwargs)

Logs a LogRecord with the level set to INFO.

level

the level of the record dispatcher as integer

property level_name

The level as unicode string

log(level, *args, **kwargs)

Logs a LogRecord with the level set to the level parameter. Because custom levels are not supported by logbook, this method is mainly used to avoid the use of reflection (e.g.: getattr()) for programmatic logging.

make_record_and_handle(level, msg, args, kwargs, exc_info, extra, frame_correction)

Creates a record from some given arguments and heads it over to the handling system.

name

the name of the record dispatcher

notice(*args, **kwargs)

Logs a LogRecord with the level set to NOTICE.

process_record(record)

Processes the record with all context specific processors. This can be overriden to also inject additional information as necessary that can be provided by this record dispatcher.

suppress_dispatcher = False

If this is set to True the dispatcher information will be suppressed for log records emitted from this logger.

trace(*args, **kwargs)

Logs a LogRecord with the level set to TRACE.

warn(*args, **kwargs)

Logs a LogRecord with the level set to WARNING. This function has an alias named warning().

warning(*args, **kwargs)

Alias for warn().

class logbook.LoggerGroup(loggers=None, level=0, processor=None)

A LoggerGroup represents a group of loggers. It cannot emit log messages on its own but it can be used to set the disabled flag and log level of all loggers in the group.

Furthermore the process_record() method of the group is called by any logger in the group which by default calls into the processor callback function.

add_logger(logger)

Adds a logger to this group.

disable(force=False)

Convenience method to disable this group.

Parameters

force – Force disable loggers that were explicitly set.

Raises

AttributeError – If force=True and the disabled property of a logger is read-only, typically because it was overridden in a subclass.

New in version 1.0.

disabled

the disabled flag for all loggers in the group, unless the loggers overrode the setting.

enable(force=False)

Convenience method to enable this group.

Parameters

force – Force enable loggers that were explicitly set.

Raises

AttributeError – If force=True and the disabled property of a logger is read-only, typically because it was overridden in a subclass.

New in version 1.0.

level

the level of the group. This is reflected to the loggers in the group unless they overrode the setting.

loggers

a list of all loggers on the logger group. Use the add_logger() and remove_logger() methods to add or remove loggers from this list.

process_record(record)

Like Logger.process_record() but for all loggers in the group. By default this calls into the processor function is it’s not None.

processor

an optional callback function that is executed to process the log records of all loggers in the group.

remove_logger(logger)

Removes a logger from the group.

class logbook.LogRecord(channel, level, msg, args=None, kwargs=None, exc_info=None, extra=None, frame=None, dispatcher=None, frame_correction=0)

A LogRecord instance represents an event being logged.

LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args

args

the positional arguments for the format string.

calling_frame

The frame in which the record has been created. This only exists for as long the log record is not closed.

channel

the name of the logger that created it or any other textual channel description. This is a descriptive name and can be used for filtering.

close()

Closes the log record. This will set the frame and calling frame to None and frame-related information will no longer be available unless it was pulled in first (pull_information()). This makes a log record safe for pickling and will clean up memory that might be still referenced by the frames.

property dispatcher

The dispatcher that created the log record. Might not exist because a log record does not have to be created from a logger or other dispatcher to be handled by logbook. If this is set, it will point to an object that implements the RecordDispatcher interface.

exception_message

The message of the exception.

exception_name

The name of the exception.

property exception_shortname

An abbreviated exception name (no import path)

filename

The filename of the module in which the record has been created. Requires a frame or that pull_information() was called before.

formatted_exception

The formatted exception which caused this record to be created in case there was any.

frame

If available, optionally the interpreter frame that pulled the heavy init. This usually points to somewhere in the dispatcher. Might not be available for all calls and is removed when the log record is closed.

frame_correction

A positive integer telling the number of frames to go back from the frame which triggered the log entry. This is mainly useful for decorators that want to show that the log was emitted from form the function they decorate

classmethod from_dict(d)

Creates a log record from an exported dictionary. This also supports JSON exported dictionaries.

func_name

The name of the function that triggered the log call if available. Requires a frame or that pull_information() was called before.

greenlet

The ident of the greenlet. This is evaluated late and means that if the log record is passed to another greenlet, pull_information() was called in the old greenlet.

heavy_init()

Does the heavy initialization that could be expensive. This must not be called from a higher stack level than when the log record was created and the later the initialization happens, the more off the date information will be for example.

This is internally used by the record dispatching system and usually something not to worry about.

heavy_initialized = False

a flag that is True if the log record is heavy initialized which is not the case by default.

information_pulled = False

a flag that is True when all the information was pulled from the information that becomes unavailable on close.

keep_open = False

can be overriden by a handler to not close the record. This could lead to memory leaks so it should be used carefully.

kwargs

the keyword arguments for the format string.

late = False

a flag that is True when heavy initialization is no longer possible

level

the level of the log record as integer.

property level_name

The level as unicode string

lineno

The line number of the file in which the record has been created. Requires a frame or that pull_information() was called before.

message

The formatted message.

module

The name of the module that triggered the log call if available. Requires a frame or that pull_information() was called before.

msg

The message of the log record as new-style format string.

process

the PID of the current process

process_name

The name of the process in which the record has been created.

pull_information()

A helper function that pulls all frame-related information into the object so that this information is available after the log record was closed.

thread

The ident of the thread. This is evaluated late and means that if the log record is passed to another thread, pull_information() was called in the old thread.

thread_name

The name of the thread. This is evaluated late and means that if the log record is passed to another thread, pull_information() was called in the old thread.

time = None

the time of the log record creation as datetime.datetime object. This information is unavailable until the record was heavy initialized.

to_dict(json_safe=False)

Exports the log record into a dictionary without the information that cannot be safely serialized like interpreter frames and tracebacks.

update_from_dict(d)

Like the from_dict() classmethod, but will update the instance in place. Helpful for constructors.

class logbook.Flags(**flags)

Allows flags to be pushed on a flag stack. Currently two flags are available:

errors

Can be set to override the current error behaviour. This value is used when logging calls fail. The default behaviour is spitting out the stacktrace to stderr but this can be overridden:

'silent'

fail silently

'raise'

raise a catchable exception

'print'

print the stacktrace to stderr (default)

introspection

Can be used to disable frame introspection. This can give a speedup on production systems if you are using a JIT compiled Python interpreter such as pypy. The default is True.

Note that the default setup of some of the handler (mail for instance) includes frame dependent information which will not be available when introspection is disabled.

Example usage:

with Flags(errors='silent'):
    ...
applicationbound()

Can be used in combination with the with statement to execute code while the object is bound to the application.

contextbound()

Can be used in combination with the with statement to execute code while the object is bound to the asyncio context.

static get_flag(flag, default=None)

Looks up the current value of a specific flag.

greenletbound()

Can be used in combination with the with statement to execute code while the object is bound to the greenlet.

pop_application()

Pops the context object from the stack.

pop_context()

Pops the context object from the stack.

pop_greenlet()

Pops the context object from the stack.

pop_thread()

Pops the context object from the stack.

push_application()

Pushes the context object to the application stack.

push_context()

Pushes the context object to the context stack.

push_greenlet()

Pushes the context object to the greenlet stack.

push_thread()

Pushes the context object to the thread stack.

stack_manager = <logbook._speedups.ContextStackManager object>

subclasses have to instanciate a ContextStackManager object on this attribute which is then shared for all the subclasses of it.

threadbound()

Can be used in combination with the with statement to execute code while the object is bound to the thread.

class logbook.Processor(callback=None)

Can be pushed to a stack to inject additional information into a log record as necessary:

def inject_ip(record):
    record.extra['ip'] = '127.0.0.1'

with Processor(inject_ip):
    ...
applicationbound()

Can be used in combination with the with statement to execute code while the object is bound to the application.

callback

the callback that was passed to the constructor

contextbound()

Can be used in combination with the with statement to execute code while the object is bound to the asyncio context.

greenletbound()

Can be used in combination with the with statement to execute code while the object is bound to the greenlet.

pop_application()

Pops the context object from the stack.

pop_context()

Pops the context object from the stack.

pop_greenlet()

Pops the context object from the stack.

pop_thread()

Pops the context object from the stack.

process(record)

Called with the log record that should be overridden. The default implementation calls callback if it is not None.

push_application()

Pushes the context object to the application stack.

push_context()

Pushes the context object to the context stack.

push_greenlet()

Pushes the context object to the greenlet stack.

push_thread()

Pushes the context object to the thread stack.

stack_manager = <logbook._speedups.ContextStackManager object>

subclasses have to instanciate a ContextStackManager object on this attribute which is then shared for all the subclasses of it.

threadbound()

Can be used in combination with the with statement to execute code while the object is bound to the thread.

logbook.get_level_name(level)

Return the textual representation of logging level ‘level’.

logbook.lookup_level(level)

Return the integer representation of a logging level.

logbook.CRITICAL
logbook.ERROR
logbook.WARNING
logbook.INFO
logbook.DEBUG
logbook.NOTSET

The log level constants