Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gauravjuvekar
Created July 11, 2017 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gauravjuvekar/58be9778aa32b8e2497931a99b7442b7 to your computer and use it in GitHub Desktop.
Save gauravjuvekar/58be9778aa32b8e2497931a99b7442b7 to your computer and use it in GitHub Desktop.
logging config with verboselogs and coloredlogs
#!/usr/bin/env python3
"""
Easliy set up a consistent logging configuration for all codes that use this
library.
The main code can be written as:
import logging
import coloredlogs
import argparse
...
parser = argparse.ArgumentParser(...)
...
# Set up other parser arguments.
...
this.module.configure_argparser(parser)
args = parser.parse_args()
this_module.log_config.install_with_args(args, coloredlogs)
logger = logging.getLogger(__name__)
...
"""
import logging
import verboselogs
def install_with_args(coloredlogs, args=None):
"""
Install the logging configuration by using the args (as output by
argparse.ArgumentParser), and a coloredlogs module imported from the main
program.
"""
verboselogs.install()
# Find the final log level
if args:
if args.quiet:
for times in range(args.quiet):
coloredlogs.decrease_verbosity()
elif args.verbose:
for times in range(args.verbose):
coloredlogs.increase_verbosity()
else:
coloredlogs.set_level(args.log_level)
else:
coloredlogs.set_level('INFO')
# Because bold black is not visible in solarized dark theme in
# gnome-terminal, we make levelname without any formatting
field_style = coloredlogs.DEFAULT_FIELD_STYLES
field_style['levelname'] = {}
# Make a format string depending on the final log level. See the logging
# module reference for more details.
format_str = "%(levelname)8s %(asctime)s.%(msecs)03d"
if coloredlogs.get_level() < coloredlogs.level_to_number('INFO'):
format_str += " %(name)s"
if coloredlogs.get_level() <= coloredlogs.level_to_number('SPAM'):
format_str += " %(pathname)s"
if coloredlogs.get_level() <= coloredlogs.level_to_number('DEBUG'):
format_str += " %(funcName)s():%(lineno)d"
if coloredlogs.get_level() <= coloredlogs.level_to_number('VERBOSE'):
format_str += " %(threadName)s"
format_str += ": %(message)s"
# Finally install it to the root logger, using the module imported from the
# main program.
coloredlogs.install(
level=coloredlogs.get_level(),
fmt=format_str,
field_style=field_style)
def configure_argparser(parser):
"""Adds arguments to a argparser.ArgumentParser to control the verbosity"""
log_config = parser.add_mutually_exclusive_group()
log_config.add_argument(
"--log-level",
choices=[
"CRITICAL",
"ERROR",
"WARNING",
"NOTICE",
"INFO",
"VERBOSE",
"DEBUG",
"SPAM"],
default="INFO",
help="Set the log level")
log_config.add_argument(
"--verbose", "-v",
action='count',
help="Increase the verbosity")
log_config.add_argument(
"--quiet", "-q",
action='count',
help="Decrease the verbosity")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment