🔀 Add a basic logger to the template
Do not use `print()` anymore in the script to print stuff on STDOUT, use `logger.info()` instead. If script is run in crontab, it loggs to syslog.
This commit is contained in:
commit
b28a33345a
50
main.py
50
main.py
|
@ -12,9 +12,48 @@ This file is part of [`<GIT REPO NAME>`](<GIT REPO URL>)
|
|||
"""
|
||||
|
||||
import argparse
|
||||
from os import environ
|
||||
import logging
|
||||
import logging.handlers
|
||||
from os import environ, path
|
||||
import sys
|
||||
from pprint import pprint as pp
|
||||
|
||||
|
||||
logger = logging.getLogger(path.splitext(path.basename(sys.argv[0]))[0])
|
||||
|
||||
|
||||
def setup_logging(options):
|
||||
"""Configure logging."""
|
||||
root = logging.getLogger("")
|
||||
logger.setLevel(options.debug and logging.DEBUG or logging.INFO)
|
||||
format_debug = "%(levelname)s\t[%(name)s] %(message)s"
|
||||
format_default = "%(message)s"
|
||||
|
||||
if options.debug:
|
||||
# Logging with --debug option
|
||||
|
||||
if not sys.stderr.isatty():
|
||||
# Logging in a file when launched not in a terminal
|
||||
|
||||
facility = logging.handlers.SysLogHandler.LOG_DAEMON
|
||||
handler_syslog = logging.handlers.SysLogHandler(
|
||||
address="/dev/log", facility=facility
|
||||
)
|
||||
handler_syslog.setFormatter(logging.Formatter(format_default))
|
||||
root.addHandler(handler_syslog)
|
||||
|
||||
else:
|
||||
# Logging on terminal standard output
|
||||
|
||||
handler_console = logging.StreamHandler()
|
||||
handler_console.setFormatter(logging.Formatter(format_debug))
|
||||
root.addHandler(handler_console)
|
||||
|
||||
else:
|
||||
# Logging default setings
|
||||
|
||||
handler_console = logging.StreamHandler()
|
||||
handler_console.setFormatter(logging.Formatter(format_default))
|
||||
root.addHandler(handler_console)
|
||||
|
||||
|
||||
class CustomFormatter(
|
||||
|
@ -110,15 +149,16 @@ def main():
|
|||
2
|
||||
"""
|
||||
pargs = parse_args()
|
||||
setup_logging(pargs)
|
||||
|
||||
if pargs.foo:
|
||||
pp(i_am_foo())
|
||||
logger.info(i_am_foo())
|
||||
|
||||
elif pargs.bar:
|
||||
pp(i_am_bar(pargs.bar))
|
||||
logger.info(i_am_bar(pargs.bar))
|
||||
|
||||
if pargs.debug and pargs:
|
||||
pp(pargs)
|
||||
logger.debug(pargs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
Loading…
Reference in New Issue