Skip to content

Commit

Permalink
Reformat code with black
Browse files Browse the repository at this point in the history
  • Loading branch information
borntyping committed Mar 22, 2021
1 parent 1501274 commit 1297254
Show file tree
Hide file tree
Showing 16 changed files with 281 additions and 222 deletions.
45 changes: 37 additions & 8 deletions colorlog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,43 @@
from __future__ import absolute_import

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

from colorlog.logging import (
basicConfig, root, getLogger, log,
debug, info, warning, error, exception, critical, StreamHandler)
basicConfig,
root,
getLogger,
log,
debug,
info,
warning,
error,
exception,
critical,
StreamHandler,
)

__all__ = ('ColoredFormatter', 'default_log_colors', 'escape_codes',
'basicConfig', 'root', 'getLogger', 'debug', 'info', 'warning',
'error', 'exception', 'critical', 'log', 'exception',
'StreamHandler', 'LevelFormatter', 'TTYColoredFormatter')
__all__ = (
"ColoredFormatter",
"default_log_colors",
"escape_codes",
"basicConfig",
"root",
"getLogger",
"debug",
"info",
"warning",
"error",
"exception",
"critical",
"log",
"exception",
"StreamHandler",
"LevelFormatter",
"TTYColoredFormatter",
)
95 changes: 63 additions & 32 deletions colorlog/colorlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,28 @@

from colorlog.escape_codes import escape_codes, parse_colors

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

# The default colors to use for the debug levels
default_log_colors = {
'DEBUG': 'white',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
"DEBUG": "white",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "bold_red",
}

# The default format to use for each style
default_formats = {
'%': '%(log_color)s%(levelname)s:%(name)s:%(message)s',
'{': '{log_color}{levelname}:{name}:{message}',
'$': '${log_color}${levelname}:${name}:${message}'
"%": "%(log_color)s%(levelname)s:%(name)s:%(message)s",
"{": "{log_color}{levelname}:{name}:{message}",
"$": "${log_color}${levelname}:${name}:${message}",
}


Expand Down Expand Up @@ -55,9 +60,15 @@ class ColoredFormatter(logging.Formatter):
Intended to help in creating more readable logging output.
"""

def __init__(self, fmt=None, datefmt=None, style='%',
log_colors=None, reset=True,
secondary_log_colors=None):
def __init__(
self,
fmt=None,
datefmt=None,
style="%",
log_colors=None,
reset=True,
secondary_log_colors=None,
):
"""
Set the format and colors the ColoredFormatter will use.
Expand Down Expand Up @@ -85,9 +96,13 @@ def __init__(self, fmt=None, datefmt=None, style='%',
if sys.version_info > (3, 2):
fmt = default_formats[style]
else:
fmt = default_formats['%']
fmt = default_formats["%"]

if sys.version_info > (3, 8) and isinstance(self, LevelFormatter) and isinstance(fmt, dict):
if (
sys.version_info > (3, 8)
and isinstance(self, LevelFormatter)
and isinstance(fmt, dict)
):
super(ColoredFormatter, self).__init__(fmt, datefmt, style, validate=False)
elif sys.version_info > (3, 2):
super(ColoredFormatter, self).__init__(fmt, datefmt, style)
Expand All @@ -96,8 +111,7 @@ def __init__(self, fmt=None, datefmt=None, style='%',
else:
logging.Formatter.__init__(self, fmt, datefmt)

self.log_colors = (
log_colors if log_colors is not None else default_log_colors)
self.log_colors = log_colors if log_colors is not None else default_log_colors
self.secondary_log_colors = secondary_log_colors
self.reset = reset

Expand All @@ -114,7 +128,7 @@ def format(self, record):
if self.secondary_log_colors:
for name, log_colors in self.secondary_log_colors.items():
color = self.color(log_colors, record.levelname)
setattr(record, name + '_log_color', color)
setattr(record, name + "_log_color", color)

# Format the message
if sys.version_info > (2, 7):
Expand All @@ -124,18 +138,24 @@ def format(self, record):

# Add a reset code to the end of the message
# (if it wasn't explicitly added in format str)
if self.reset and not message.endswith(escape_codes['reset']):
message += escape_codes['reset']
if self.reset and not message.endswith(escape_codes["reset"]):
message += escape_codes["reset"]

return message


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

def __init__(self, fmt=None, datefmt=None, style='%',
log_colors=None, reset=True,
secondary_log_colors=None):
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.
Expand All @@ -160,13 +180,23 @@ def __init__(self, fmt=None, datefmt=None, style='%',
"""
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)
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,
fmt=fmt,
datefmt=datefmt,
style=style,
log_colors=log_colors,
reset=reset,
secondary_log_colors=secondary_log_colors,
)
self.style = style
self.fmt = fmt

Expand All @@ -178,8 +208,9 @@ def format(self, record):
# 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()))
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):
Expand All @@ -199,10 +230,10 @@ class TTYColoredFormatter(ColoredFormatter):

def __init__(self, *args, **kwargs):
"""Overwrite the `reset` argument to False if stream is not a TTY."""
self.stream = kwargs.pop('stream')
self.stream = kwargs.pop("stream")

# Both `reset` and `isatty` must be true to insert reset codes.
kwargs['reset'] = kwargs.get('reset', True) and self.stream.isatty()
kwargs["reset"] = kwargs.get("reset", True) and self.stream.isatty()

ColoredFormatter.__init__(self, *args, **kwargs)

Expand Down
36 changes: 13 additions & 23 deletions colorlog/escape_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,42 +15,32 @@
if sys.platform == "win32":
colorama.init(strip=False)

__all__ = ('escape_codes', 'parse_colors')
__all__ = ("escape_codes", "parse_colors")


# Returns escape codes from format codes
def esc(*x):
return '\033[' + ';'.join(x) + 'm'
return "\033[" + ";".join(x) + "m"


# The initial list of escape codes
escape_codes = {
'reset': esc('0'),
'bold': esc('01'),
'thin': esc('02')
}
escape_codes = {"reset": esc("0"), "bold": esc("01"), "thin": esc("02")}

# The color names
COLORS = [
'black',
'red',
'green',
'yellow',
'blue',
'purple',
'cyan',
'white'
]
COLORS = ["black", "red", "green", "yellow", "blue", "purple", "cyan", "white"]

PREFIXES = [
# Foreground without prefix
('3', ''), ('01;3', 'bold_'), ('02;3', 'thin_'),

("3", ""),
("01;3", "bold_"),
("02;3", "thin_"),
# Foreground with fg_ prefix
('3', 'fg_'), ('01;3', 'fg_bold_'), ('02;3', 'fg_thin_'),

("3", "fg_"),
("01;3", "fg_bold_"),
("02;3", "fg_thin_"),
# Background with bg_ prefix - bold/light works differently
('4', 'bg_'), ('10', 'bg_bold_'),
("4", "bg_"),
("10", "bg_bold_"),
]

for prefix, prefix_name in PREFIXES:
Expand All @@ -60,4 +50,4 @@ def esc(*x):

def parse_colors(sequence):
"""Return escape codes from a color sequence."""
return ''.join(escape_codes[n] for n in sequence.split(',') if n)
return "".join(escape_codes[n] for n in sequence.split(",") if n)
18 changes: 14 additions & 4 deletions colorlog/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@
BASIC_FORMAT = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s"


def basicConfig(style='%', log_colors=None, reset=True,
secondary_log_colors=None, format=BASIC_FORMAT, datefmt=None, **kwargs):
def basicConfig(
style="%",
log_colors=None,
reset=True,
secondary_log_colors=None,
format=BASIC_FORMAT,
datefmt=None,
**kwargs
):
"""Call ``logging.basicConfig`` and override the formatter it creates."""
logging.basicConfig(**kwargs)
logging._acquireLock()
Expand All @@ -24,19 +31,22 @@ def basicConfig(style='%', log_colors=None, reset=True,
style=style,
log_colors=log_colors,
reset=reset,
secondary_log_colors=secondary_log_colors
))
secondary_log_colors=secondary_log_colors,
)
)
finally:
logging._releaseLock()


def ensure_configured(func):
"""Modify a function to call ``basicConfig`` first if no handlers exist."""

@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(logging.root.handlers) == 0:
basicConfig()
return func(*args, **kwargs)

return wrapper


Expand Down
18 changes: 9 additions & 9 deletions colorlog/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ def assert_log_message(log_function, message, capsys):
log_function(message)
out, err = capsys.readouterr()
# Print the output so that py.test shows it when a test fails
print(err, end='', file=sys.stderr)
print(err, end="", file=sys.stderr)
# Assert the message send to the logger was output
assert message in err, 'Log message not output to STDERR'
assert message in err, "Log message not output to STDERR"
return err


Expand All @@ -40,11 +40,11 @@ def reset_loggers():
def test_logger(reset_loggers, capsys):
def function(logger, validator=None):
lines = [
assert_log_message(logger.debug, 'a debug message', capsys),
assert_log_message(logger.info, 'an info message', capsys),
assert_log_message(logger.warning, 'a warning message', capsys),
assert_log_message(logger.error, 'an error message', capsys),
assert_log_message(logger.critical, 'a critical message', capsys)
assert_log_message(logger.debug, "a debug message", capsys),
assert_log_message(logger.info, "an info message", capsys),
assert_log_message(logger.warning, "a warning message", capsys),
assert_log_message(logger.error, "an error message", capsys),
assert_log_message(logger.critical, "a critical message", capsys),
]

if validator is not None:
Expand All @@ -60,8 +60,8 @@ def function(logger, validator=None):
@pytest.fixture()
def create_and_test_logger(test_logger):
def function(*args, **kwargs):
validator = kwargs.pop('validator', None)
formatter_cls = kwargs.pop('formatter_class', colorlog.ColoredFormatter)
validator = kwargs.pop("validator", None)
formatter_cls = kwargs.pop("formatter_class", colorlog.ColoredFormatter)

formatter = formatter_cls(*args, **kwargs)

Expand Down

0 comments on commit 1297254

Please sign in to comment.