Skip to content

Commit 8c32c90

Browse files
committed
Support colored log output with colorlog.
1 parent 5cd2053 commit 8c32c90

1 file changed

Lines changed: 24 additions & 5 deletions

File tree

simpledaemonlog/logsetup.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
import sys
99
import logging
1010

11-
DEFAULT_FORMAT_STRING = '%(asctime)s|%(levelname)8s|%(name)10s|%(lineno)3s| %(message)s'
12-
11+
DEFAULT_FORMAT_STRING = '%(asctime)s|%(levelname)8s|%(module)20s|%(lineno)4s| %(message)s'
12+
COLORED_FORMAT_STRING = '%(log_color)s%(asctime)s%(reset)s|%(module)20s|%(lineno)4s| %(log_color)s%(message)s'
1313

1414
class StdLogger(object):
1515
def __init__(self, out, log):
@@ -35,11 +35,28 @@ def filter(self, record):
3535
return True
3636

3737

38-
def setup_console(level=logging.NOTSET, fs=DEFAULT_FORMAT_STRING):
38+
def setup_console(level=logging.NOTSET, fs=DEFAULT_FORMAT_STRING, color=False):
3939
console = logging.StreamHandler()
4040
console.addFilter(PrintfFilter())
4141

42-
formatter = logging.Formatter(fs)
42+
if color:
43+
""" https://pypi.python.org/pypi/colorlog """
44+
from colorlog import ColoredFormatter
45+
formatter = ColoredFormatter(
46+
COLORED_FORMAT_STRING, datefmt=None, reset=True,
47+
log_colors={
48+
#'DEBUG': 'cyan',
49+
'INFO': 'white',
50+
'WARNING': 'yellow',
51+
'ERROR': 'red',
52+
'CRITICAL': 'red,bg_white',
53+
},
54+
secondary_log_colors={},
55+
style='%'
56+
)
57+
else:
58+
formatter = logging.Formatter(fs)
59+
4360
console.setFormatter(formatter)
4461
console.setLevel(level)
4562

@@ -87,10 +104,12 @@ def setup_file(application_name, logdir="log", level=logging.NOTSET, fs=DEFAULT_
87104

88105
log = logging.getLogger(__name__)
89106

90-
log.info("A piece of info")
91107
log.debug("Some debug")
108+
log.info("A piece of info")
92109
log.warning("A small warning")
93110
log.error("A big error")
111+
log.critical("A critical message")
112+
94113
try:
95114
raise TypeError("An ugly TypeError")
96115
except TypeError:

0 commit comments

Comments
 (0)