The More Module

The more module implements special handlers and other things that are beyond the scope of Logbook itself or depend on external libraries. Additionally there are some handlers in logbook.ticketing, logbook.queues and logbook.notifiers.

Tagged Logging

class logbook.more.TaggingLogger(name=None, tags=None)[source]

A logger that attaches a tag to each record. This is an alternative record dispatcher that does not use levels but tags to keep log records apart. It is constructed with a descriptive name and at least one tag. The tags are up for you to define:

logger = TaggingLogger('My Logger', ['info', 'warning'])

For each tag defined that way, a method appears on the logger with that name:

logger.info('This is a info message')

To dispatch to different handlers based on tags you can use the TaggingHandler.

The tags themselves are stored as list named 'tags' in the extra dictionary.

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

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

level

the level of the record dispatcher as integer

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

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.

class logbook.more.TaggingHandler(handlers, filter=None, bubble=False)[source]

A handler that logs for tags and dispatches based on those.

Example:

import logbook
from logbook.more import TaggingHandler

handler = TaggingHandler(dict(
    info=OneHandler(),
    warning=AnotherHandler()
))
emit(record)[source]

Emit the specified logging record. This should take the record and deliver it to whereever the handler sends formatted log records.

Special Handlers

class logbook.more.TwitterHandler(consumer_key, consumer_secret, username, password, level=0, format_string=None, filter=None, bubble=False)[source]

A handler that logs to twitter. Requires that you sign up an application on twitter and request xauth support. Furthermore the oauth2 library has to be installed.

default_format_string = '[{record.channel}] {record.level_name}: {record.message}'

a class attribute for the default format string to use if the constructor was invoked with None.

emit(record)[source]

Emit the specified logging record. This should take the record and deliver it to whereever the handler sends formatted log records.

formatter_class

alias of TwitterFormatter

get_oauth_token()[source]

Returns the oauth access token.

make_client()[source]

Creates a new oauth client auth a new access token.

tweet(status)[source]

Tweets a given status. Status must not exceed 140 chars.

class logbook.more.SlackHandler(api_token, channel, level=0, format_string=None, filter=None, bubble=False)[source]

A handler that logs to slack. Requires that you sign up an application on slack and request an api token. Furthermore the slacker library has to be installed.

emit(record)[source]

Emit the specified logging record. This should take the record and deliver it to whereever the handler sends formatted log records.

class logbook.more.ExternalApplicationHandler(arguments, stdin_format=None, encoding='utf-8', level=0, filter=None, bubble=False)[source]

This handler invokes an external application to send parts of the log record to. The constructor takes a list of arguments that are passed to another application where each of the arguments is a format string, and optionally a format string for data that is passed to stdin.

For example it can be used to invoke the say command on OS X:

from logbook.more import ExternalApplicationHandler
say_handler = ExternalApplicationHandler(['say', '{record.message}'])

Note that the above example is blocking until say finished, so it’s recommended to combine this handler with the logbook.ThreadedWrapperHandler to move the execution into a background thread.

New in version 0.3.

emit(record)[source]

Emit the specified logging record. This should take the record and deliver it to whereever the handler sends formatted log records.

class logbook.more.ExceptionHandler(exc_type, level=0, format_string=None, filter=None, bubble=False)[source]

An exception handler which raises exceptions of the given exc_type. This is especially useful if you set a specific error level e.g. to treat warnings as exceptions:

from logbook.more import ExceptionHandler

class ApplicationWarning(Exception):
    pass

exc_handler = ExceptionHandler(ApplicationWarning, level='WARNING')

New in version 0.3.

handle(record)[source]

Emits the record and falls back. It tries to emit() the record and if that fails, it will call into handle_error() with the record and traceback. This function itself will always emit when called, even if the logger level is higher than the record’s level.

If this method returns False it signals to the calling function that no recording took place in which case it will automatically bubble. This should not be used to signal error situations. The default implementation always returns True.

class logbook.more.DedupHandler(format_string='message repeated {count} times: {message}', *args, **kwargs)[source]

A handler that deduplicates log messages.

It emits each unique log record once, along with the number of times it was emitted. Example::

with logbook.more.DedupHandler():
    logbook.error('foo')
    logbook.error('bar')
    logbook.error('foo')

The expected output::

message repeated 2 times: foo
message repeated 1 times: bar
handle(record)[source]

Emits the record and falls back. It tries to emit() the record and if that fails, it will call into handle_error() with the record and traceback. This function itself will always emit when called, even if the logger level is higher than the record’s level.

If this method returns False it signals to the calling function that no recording took place in which case it will automatically bubble. This should not be used to signal error situations. The default implementation always returns True.

pop_application()[source]

Pops the context object from the stack.

pop_context()[source]

Pops the context object from the stack.

pop_greenlet()[source]

Pops the context object from the stack.

pop_thread()[source]

Pops the context object from the stack.

Colorized Handlers

New in version 0.3.

class logbook.more.ColorizedStderrHandler(*args, **kwargs)[source]

A colorizing stream handler that writes to stderr. It will only colorize if a terminal was detected. Note that this handler does not colorize on Windows systems.

New in version 0.3.

Changed in version 1.0: Added Windows support if colorama is installed.

class logbook.more.ColorizingStreamHandlerMixin[source]

A mixin class that does colorizing.

New in version 0.3.

Changed in version 1.0.0: Added Windows support if colorama is installed.

forbid_color()[source]

Forbid colorizing the stream (should_colorize will return False)

force_color()[source]

Force colorizing the stream (should_colorize will return True)

get_color(record)[source]

Returns the color for this record.

should_colorize(record)[source]

Returns True if colorizing should be applied to this record. The default implementation returns True if the stream is a tty. If we are executing on Windows, colorama must be installed.

Other

class logbook.more.JinjaFormatter(template)[source]

A formatter object that makes it easy to format using a Jinja 2 template instead of a format string.