Welcome to easylogger’s documentation!

Summary

Easylogger is a Python package which wraps aspects of original logging module in simple and Pythonic way. You can use all power of the original package with the new facilities side-by-side.

The key features of current version of easylogging package are:

  • Easy to start logging without configuring anything;
  • Provided decorator-mode to log every function or method call and its doc-string;
  • Imitate and replace stdout and stderr streams in order to redirect print() messages to required logging handlers;
  • Alternative message formatting system (like print() does);
  • And more! See unit-tests for additional code examples;

See examples below for the features description.

Note

Python version 2.6 or higher is required to use easylogger package.

Examples

1. Easy start to use logging facilities:

from easylogger import log, info, debug, DEBUG
log("Hello, World!")
log.info("This is an information message")
log.debug("This is a debug message")
log.error("This is an error message")
log.critical("This is an critical message")
info("Hello!")
debug("Bye")
log.log(DEBUG, "Generic log method.")
... [DEBUG   ] Hello, World!
... [INFO    ] This is an information message
... [DEBUG   ] This is a debug message
... [ERROR   ] This is an error message
... [CRITICAL] This is an critical message
... [INFO    ] Hello!
... [DEBUG   ] Bye!
... [DEBUG   ] Generic log method.

2. Using logger as decorator:

@log
def create_human(name, sex, age=26):
    """Create new human with name '{name}' and age {age}."""
    print "Creating new human '{0}-{1}-{2}'.".format(name, sex, age)

class MyExClass(object):

    @info
    def print_hi(self, who):
        print "Who?", who

log("Checking decorator-mode.")
create_human("Ivan", "male")
MyExClass().print_hi("me")
... [DEBUG   ] Checking decorator-mode.
... [DEBUG   ] Executing function create_human(name='Ivan', sex='male', age=26).
... [DOC     ] Create new human with name 'Ivan' and age 26.
Creating new human 'Ivan-male-26'.
... [INFO    ] Executing method MyExClass.print_hi(who='me').
Who? me

3. Imitate and replace stdout and stderr streams:

import sys
from easylogger import log, STDOUT, STDERR

# replace current streams
sys.stdout = log.get_stream(STDOUT)
sys.stderr = log.get_stream(STDERR)

print "Hello,", "World!"
print >> sys.stderr, "Error message!"

# assign original stream values
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
... [STDOUT  ] Hello, World!
... [STDERR  ] Error message!

Warning

Keep in mind that if you provide sys.stdout (sys.stderr) as stream parameter to logging.StreamHandler you may get into recursive loop when using stream redirection. Always provide sys.__stdout__ (sys.__stderr__) when constructing a stream handler to avoid this problem.

4. Alternative message formatting system:

from easylogger import log, error, info, LoggingOptions

# new message style
log("Hello, World!", "test1", "test2")
component = "brain"
error("Error occurred in", component, "with code", 123, int)
log.set_options(new_style_delimiter="_")
log("brown", "fox", "jumps", "over", "lazy", "dog")

# old message style
opt = LoggingOptions()
opt.enable_new_style = False
log.set_options(opt)
info("a %s %s", "b", "c")
... [DEBUG   ] Hello, World! test1 test2
... [ERROR   ] Error occurred in brain with code 123 <type 'int'>
... [DEBUG   ] brown_fox_jumps_over_lazy_dog
... [INFO    ] a b c

Note

For more options see easylogger.LoggingOptions.

5. Using original logging features and new ones side-by-side:

from easylogger import get_logger, INFO
import logging.config

logging.config.fileConfig("logging.cfg")
mylog = get_logger("simpleExample", level=INFO)
mylog.info("Hello!")
mylog.debug("Hello!")
mylog.error("Hello!")
simpleExample - INFO - Hello!
simpleExample - ERROR - Hello!

Note

A lot of examples can be found in /tests/basic_tests.py file.

Easylogger objects

Easylogger is a wrapper for standard logging module, which provides some new logging facilities and allows accessing them in more Pythonic way.

copyright:Copyright 2011 by Oleg Churkin <bahusoff@gmail.com>.
license:BSD, see LICENSE.txt for details.
easylogger.info(msg, *args, **kwargs)[source]

Log a message with severity INFO on the root logger.

easylogger.debug(msg, *args, **kwargs)[source]

Log a message with severity DEBUG on the root logger.

easylogger.error(msg, *args, **kwargs)[source]

Log a message with severity ERROR on the root logger.

easylogger.warning(msg, *args, **kwargs)[source]

Log a message with severity WARNING on the root logger.

easylogger.warn(msg, *args, **kwargs)

Log a message with severity WARNING on the root logger.

easylogger.exception(msg, *args, **kwargs)[source]

Log a message with severity ERROR on the root logger.

easylogger.critical(msg, *args, **kwargs)[source]

Log a message with severity CRITICAL on the root logger.

easylogger.compose_handler(handler, level=None, format_tuple=None, filter_name=None)[source]

Help to compose final handler.

Parameters:
  • handler – any handler object from logging and logging.handlers;
  • level – logging level (INFO, DEBUG and so on);
  • format_tuple – message format tuple (fmt, datefmt), see logging.Formatter. Only if string is provided, datefmt will be passed as None;
  • filter_name – filter name, see logging.Filter;
easylogger.get_logger(name=None, level=None, handlers=None, options=None, extra=None)[source]

Return basic logger object.

Parameters:
  • name – logger’s name;
  • level – logging level, if not specified and some handlers are provided, minimum of all their levels will be taken. If final value is NOTSET, then Defaults.GLOBAL_LOGGING_LEVEL will be used;
  • handlers – list of handlers for created logger to attach, if value is not iterable, it will be put in a list automatically;
  • optionsLoggingOptions object;
  • extra – extra arguments for underlying logging functionality, see documentation for logging;
easylogger.get_default_logger(stream=None)[source]

Return default logger for this module.

Parameters:stream – stream object for default logging handler logging.StreamHandler, default value is sys.__stdout__.
class easylogger.LoggingOptions[source]

This structure contains different logging options.

Available options:
  • indent_size - specifies number of spaces to be inserted before

    ‘%(message)s’ parameter, see logging.Formatter for more details;

  • enable_new_style - if True log’s methods will join all provided
    positional arguments with space as delimiter, e.g.:
    >>> log.info("I", "am", "fine.")
    I am fine.
    
  • new_style_delimiter - delimiter between message parts when new

    message style is enabled, space by default;

  • enable_decorator_mode - if True log’s methods will produce necessary

    messages when used as decorators, otherwise no output will be produced;

  • enable_doc_processing - if True all doc strings will be logged by log

    or its method used as decorators;

  • doc_processing_prefix - if specified, only doc strings begins with

    this character(s) will be logged. Character(s) will be stripped from logged message;

  • doc_processing_level - logging level for logged doc strings, by default

    it’s DOC;

class easylogger.LoggerAdapter(logger=None, options=None, extra=None)[source]

An adapter for loggers which makes it easier to specify contextual information in logging output.

append_handlers(*handlers)[source]

Append provided handlers to the list of existed ones.

critical(msg, *args, **kwargs)[source]

Delegate a critical call to the underlying logger, after adding contextual information from this adapter instance.

debug(msg, *args, **kwargs)[source]

Delegate a debug call to the underlying logger, after adding contextual information from this adapter instance.

effective_level

Return effective logging level, any message produced with this level will be logged by all attached handlers.

error(msg, *args, **kwargs)[source]

Delegate an error call to the underlying logger, after adding contextual information from this adapter instance.

exception(msg, *args, **kwargs)[source]

Delegate an exception call to the underlying logger, after adding contextual information from this adapter instance.

get_effective_level()[source]

Return effective logging level, any message produced with this level will be logged by all attached handlers.

get_level()[source]

Return current logger’s level.

get_stream(level=None)[source]

Return stream imitation object, which can replace stdout and stderr streams.

Parameters:level – logging level, messages will be logged with, usually STDOUT or STDERR;
info(msg, *args, **kwargs)[source]

Delegate an info call to the underlying logger, after adding contextual information from this adapter instance.

level

Return current logger’s level.

log(level, msg, *args, **kwargs)[source]

Delegate a log call to the underlying logger, after adding contextual information from this adapter instance.

process_message(msg, args, kwargs)[source]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, args or keyword args. Return the message, args and kwargs modified (or not) to suit your needs.

replace_handlers(*handlers)[source]

Replace current list of handlers with the provided ones.

set_effective_level(level)[source]

Set effective level: set the same logging level for current logger and for all its handlers.

set_level(level)[source]

Set logging level for current logger only.

set_options(*args, **kwargs)[source]

Set logging options, see LoggingOptions class above.

Parameters:
  • args – here can be only one positional argument: instance of LoggingOptions object, if it’s provided, keyword arguments will be ignored and current logging options will be replaced with provided ones;
  • kwargs – any existing options can be provided (see available in LoggingOptions class);
warning(msg, *args, **kwargs)[source]

Delegate a warning call to the underlying logger, after adding contextual information from this adapter instance.

Indices and tables

Table Of Contents

This Page