Skip to content

Instantly share code, notes, and snippets.

@mzpqnxow
Last active September 12, 2021 00:33
Show Gist options
  • Save mzpqnxow/e72f1170de6efd4de7954aacd0f0452f to your computer and use it in GitHub Desktop.
Save mzpqnxow/e72f1170de6efd4de7954aacd0f0452f to your computer and use it in GitHub Desktop.
Customize Python log formatting by log level
"""
A simple example of formatting log messages differently based on their
Python log level. It seems a basic feature for a logging library that
as far as I can tell is missing from stdlib logging
So the usual route is overriding the logging.Formatter class as shown
below. Sovling the problem this way isn't novel or unusual as nearly
all of the stdblib classes are meant to be extended, but it would
be nice if you could just pass a dictionary of log levels and their
respective formats.
I've yet to find a "good" logging package on PyPi, let me know of any
you may know..
-AG
--
The behavior here that is modified:
* In the stdlib, CRITICAL and FATAL are actually the same log level.
this Formatter will always print FATAL as the log level even when
CRITICAL is used as the entry-point
* INFO level messages are essentially printed as if they were invoked
using the `print` built-in, but still will be logged to file, or
syslog, or wherever based on what logger you apply it to. Does
an informational message have to either be completely ugly and
full of debug info OR be absent from the logfile? If you use
this approach you don't have to deal with the trade-off
Obviously, this can be used in any way, this is just an example
-AG
"""
import logging
class LevelBasedormatter(logging.Formatter):
def __init__(self, fmt):
logging.Formatter.__init__(self, fmt)
def format(self, record):
format_orig = self._fmt
if record.levelname == "WARNING":
record.levelname = "WARN"
if record.levelno == logging.INFO:
format_orig = self._fmt
self._fmt = "%(message)s"
r = logging.Formatter.format(self, record)
self._fmt = format_orig
return r
elif record.levelno == logging.CRITICAL or record.levelno == logging.ERROR or record.levelno == logging.WARN:
if record.levelno == logging.FATAL:
record.levelname = "FATAL"
self._fmt = "\n... %(levelname)s, %(message)s\n"
r = logging.Formatter.format(self, record)
return r
else:
return logging.Formatter.format(self, record)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment