comparison velib_python/logger.py @ 8:9c0435a617db

Import velib_python
author Daniel O'Connor <darius@dons.net.au>
date Sun, 05 Dec 2021 14:35:36 +1030
parents
children
comparison
equal deleted inserted replaced
5:982eeffe9d95 8:9c0435a617db
1 #!/usr/bin/python3 -u
2 # -*- coding: utf-8 -*-
3
4 import logging
5 import sys
6
7 class LevelFilter(logging.Filter):
8 def __init__(self, passlevels, reject):
9 self.passlevels = passlevels
10 self.reject = reject
11
12 def filter(self, record):
13 if self.reject:
14 return (record.levelno not in self.passlevels)
15 else:
16 return (record.levelno in self.passlevels)
17
18 # Leave the name set to None to get the root logger. For some reason specifying 'root' has a
19 # different effect: there will be two root loggers, both with their own handlers...
20 def setup_logging(debug=False, name=None):
21 formatter = logging.Formatter(fmt='%(levelname)s:%(module)s:%(message)s')
22
23 # Make info and debug stream to stdout and the rest to stderr
24 h1 = logging.StreamHandler(sys.stdout)
25 h1.addFilter(LevelFilter([logging.INFO, logging.DEBUG], False))
26 h1.setFormatter(formatter)
27
28 h2 = logging.StreamHandler(sys.stderr)
29 h2.addFilter(LevelFilter([logging.INFO, logging.DEBUG], True))
30 h2.setFormatter(formatter)
31
32 logger = logging.getLogger(name)
33 logger.addHandler(h1)
34 logger.addHandler(h2)
35
36 # Set the loglevel and show it
37 logger.setLevel(level=(logging.DEBUG if debug else logging.INFO))
38 logLevel = {0: 'NOTSET', 10: 'DEBUG', 20: 'INFO', 30: 'WARNING', 40: 'ERROR'}
39 logger.info('Loglevel set to ' + logLevel[logger.getEffectiveLevel()])
40
41 return logger