logging: Abbreviate log-level names to 4 characters.

These are long enough to still be self-explanatory (the only one I'm
at all in doubt about there is DEBG; I avoided "DBUG" because it reads
"BUG" which suggests a high-priority message, and those are the
opposite of that), while saving a good bit of horizontal space
vs. padding everything to the 8 characters of "CRITICAL".

Also add a linter exception to allow easy-to-read alignment here,
similar to several existing exceptions for other alignment cases.
This commit is contained in:
Greg Price
2017-09-27 14:53:48 -07:00
parent 412f6e70d8
commit 0d5f77cf86
2 changed files with 21 additions and 1 deletions

View File

@@ -40,6 +40,11 @@ def check_pep8(files):
# these may make the code less readable.
'E226',
# "multiple spaces after ':'"
# This is the `{}` analogue of E221, and these are similarly being used
# for alignment.
'E241',
# "unexpected spaces around keyword / parameter equals"
# Many of these should be fixed, but many are also being used for
# alignment/making the code easier to read.

View File

@@ -159,11 +159,25 @@ def find_log_origin(record):
else:
return logger_name
log_level_abbrevs = {
'DEBUG': 'DEBG',
'INFO': 'INFO',
'WARNING': 'WARN',
'ERROR': 'ERR',
'CRITICAL': 'CRIT',
}
def abbrev_log_levelname(levelname):
# type: (str) -> str
# It's unlikely someone will set a custom log level with a custom name,
# but it's an option, so we shouldn't crash if someone does.
return log_level_abbrevs.get(levelname, levelname[:4])
class ZulipFormatter(logging.Formatter):
# Used in the base implementation. Default uses `,`.
default_msec_format = '%s.%03d'
_fmt = '%(asctime)s %(levelname)-8s [%(zulip_origin)s] %(message)s'
_fmt = '%(asctime)s %(zulip_level_abbrev)-4s [%(zulip_origin)s] %(message)s'
def __init__(self):
# type: () -> None
@@ -174,6 +188,7 @@ class ZulipFormatter(logging.Formatter):
if not getattr(record, 'zulip_decorated', False):
# The `setattr` calls put this logic explicitly outside the bounds of the
# type system; otherwise mypy would complain LogRecord lacks these attributes.
setattr(record, 'zulip_level_abbrev', abbrev_log_levelname(record.levelname))
setattr(record, 'zulip_origin', find_log_origin(record))
setattr(record, 'zulip_decorated', True)
return super().format(record)