Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for per-loglevel formatting #32

Merged
merged 8 commits into from
May 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions colorlog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from __future__ import absolute_import

from colorlog.colorlog import (
ColoredFormatter, escape_codes, default_log_colors)
ColoredFormatter, escape_codes, default_log_colors,
LevelFormatter)

from colorlog.logging import (
basicConfig, root, getLogger, log,
Expand All @@ -12,4 +13,4 @@
__all__ = ('ColoredFormatter', 'default_log_colors', 'escape_codes',
'basicConfig', 'root', 'getLogger', 'debug', 'info', 'warning',
'error', 'exception', 'critical', 'log', 'exception',
'StreamHandler')
'StreamHandler', 'LevelFormatter')
65 changes: 64 additions & 1 deletion colorlog/colorlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

from colorlog.escape_codes import escape_codes, parse_colors

__all__ = ('escape_codes', 'default_log_colors', 'ColoredFormatter')
__all__ = ('escape_codes', 'default_log_colors', 'ColoredFormatter',
'LevelFormatter')

# The default colors to use for the debug levels
default_log_colors = {
Expand Down Expand Up @@ -135,3 +136,65 @@ def format(self, record):
message += escape_codes['reset']

return message


class LevelFormatter(ColoredFormatter):
"""
An Extension of ColoredFormatter that uses per-loglevel format strings.
"""

def __init__(self, fmt=None, datefmt=None, style='%',
log_colors=None, reset=True,
secondary_log_colors=None):
"""
Set the per-loglevel format that will be used.

Supports fmt as a dict. All other args are passed on to the
``colorlog.ColoredFormatter`` constructor.

:Parameters:
- fmt (dict):
A mapping of log levels (represented as strings, e.g. 'WARNING') to
different formatters. (*New in version <TBD>) # TODO: version?
(All other parameters are the same as in colorlog.ColoredFormatter)

Example:

formatter = colorlog.LevelFormatter(fmt={
'DEBUG':'%(log_color)s%(msg)s (%(module)s:%(lineno)d)',
'INFO': '%(log_color)s%(msg)s',
'WARNING': '%(log_color)sWARN: %(msg)s (%(module)s:%(lineno)d)',
'ERROR': '%(log_color)sERROR: %(msg)s (%(module)s:%(lineno)d)',
'CRITICAL': '%(log_color)sCRIT: %(msg)s (%(module)s:%(lineno)d)',
})
"""
if sys.version_info > (2, 7):
super(LevelFormatter, self).__init__(
fmt=fmt, datefmt=datefmt, style=style, log_colors=log_colors,
reset=reset, secondary_log_colors=secondary_log_colors)
else:
ColoredFormatter.__init__(
self, fmt=fmt, datefmt=datefmt, style=style,
log_colors=log_colors, reset=reset,
secondary_log_colors=secondary_log_colors)
self.style = style
self.fmt = fmt

def format(self, record):
# If fmt is a dict, customize formatter per log level
if isinstance(self.fmt, dict):
self._fmt = self.fmt[record.levelname]
if sys.version_info > (3, 2):
# Update self._style because we've changed self._fmt
# (code based on stdlib's logging.Formatter.__init__())
if self.style not in logging._STYLES:
raise ValueError('Style must be one of: %s' % ','.join(
logging._STYLES.keys()))
self._style = logging._STYLES[self.style][0](self._fmt)

if sys.version_info > (2, 7):
message = super(LevelFormatter, self).format(record)
else:
message = ColoredFormatter.format(self, record)

return message