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.

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()).

info(*args, **kwargs)

Logs a LogRecord with the level set to INFO.

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.

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.

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 = None

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 = None

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

loggers = None

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 = None

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 = None

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 = None

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.

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.

exception_shortname

An abbreviated exception name (no import path)

extra = None

optional extra information as dictionary. This is the place where custom log processors can attach custom context sensitive data.

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 = None

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 = None

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 = None

the keyword arguments for the format string.

late = False

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

level = None

the level of the log record as integer.

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 = None

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

process = None

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(_cls=<class 'logbook._fallback._StackBound'>)

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

static get_flag(flag, default=None)

Looks up the current value of a specific flag.

greenletbound(_cls=<class 'logbook._fallback._StackBound'>)

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_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_greenlet()

Pushes the context object to the greenlet stack.

push_thread()

Pushes the context object to the thread stack.

threadbound(_cls=<class 'logbook._fallback._StackBound'>)

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(_cls=<class 'logbook._fallback._StackBound'>)

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

callback = None

the callback that was passed to the constructor

greenletbound(_cls=<class 'logbook._fallback._StackBound'>)

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_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_greenlet()

Pushes the context object to the greenlet stack.

push_thread()

Pushes the context object to the thread stack.

threadbound(_cls=<class 'logbook._fallback._StackBound'>)

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