]> kaliko git repositories - mpd-sima.git/blob - sima/lib/logger.py
Clean some linter warnings and errors
[mpd-sima.git] / sima / lib / logger.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2009, 2010, 2013, 2014, 2015 kaliko <kaliko@azylum.org>
3 #
4 #  This file is part of sima
5 #
6 #  sima is free software: you can redistribute it and/or modify
7 #  it under the terms of the GNU General Public License as published by
8 #  the Free Software Foundation, either version 3 of the License, or
9 #  (at your option) any later version.
10 #
11 #  sima is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #  GNU General Public License for more details.
15 #
16 #  You should have received a copy of the GNU General Public License
17 #  along with sima.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 #
20
21 """
22 Logging facility for sima.
23 """
24
25 # standard library import
26 import logging
27 import sys
28
29 from os import getenv
30
31 DEBUG = logging.DEBUG
32 INFO = logging.INFO
33 ERROR = logging.ERROR
34 LOG_FORMATS = {
35         DEBUG: '[{process}]{filename: >11}:{lineno: <3} {levelname: <7}: {message}',
36         INFO:  '{levelname: <7}: {message}',
37         }
38 DATE_FMT = "%Y-%m-%d %H:%M:%S"
39
40 TRACE_LEVEL_NUM = 5
41 logging.addLevelName(TRACE_LEVEL_NUM, 'TRACE')
42 def trace(self, message, *args, **kwargs):
43     # Yes, logger takes its '*args' as 'args'.
44     if self.isEnabledFor(TRACE_LEVEL_NUM):
45         self._log(TRACE_LEVEL_NUM, message, args, **kwargs)
46
47 logging.Logger.trace = trace
48
49
50 def set_logger(level='info', logfile=None):
51     """
52     logger:
53         level: in debug, info, warning,…
54         logfile: file to log to
55     """
56     name = 'sima'
57     if getenv('TRACE', False):
58         user_log_level = TRACE_LEVEL_NUM
59     else:
60         user_log_level = getattr(logging, level.upper())
61     if user_log_level > DEBUG:
62         log_format = LOG_FORMATS.get(INFO)
63     else:
64         log_format = LOG_FORMATS.get(DEBUG)
65     logger = logging.getLogger(name)
66     formatter = logging.Formatter(log_format, DATE_FMT, '{')
67     logger.setLevel(user_log_level)
68     filehdl = False
69     if logger.handlers:
70         for hdl in logger.handlers:
71             hdl.setFormatter(formatter)
72             if isinstance(hdl, logging.FileHandler):
73                 filehdl = True
74             else:
75                 logger.removeHandler(hdl)
76
77     if logfile:
78         if filehdl:
79             logger.handlers = []
80         # Add timestamp for file handler
81         log_format = '{0} {1}'.format('{asctime}', log_format)
82         formatter = logging.Formatter(log_format, DATE_FMT, '{')
83         # create file handler
84         fileh = logging.FileHandler(logfile)
85         fileh.setFormatter(formatter)
86         logger.addHandler(fileh)
87     else:
88         if filehdl:
89             logger.info('Not changing logging handlers, only updating formatter')
90             return
91         # create console handler with a specified log level (STDOUT)
92         couth = logging.StreamHandler(sys.stdout)
93         couth.addFilter(lambda record: record.levelno < ERROR)
94
95         # create console handler with warning log level (STDERR)
96         cerrh = logging.StreamHandler(sys.stderr)
97         cerrh.setLevel(ERROR)
98
99         # add formatter to the handlers
100         cerrh.setFormatter(formatter)
101         couth.setFormatter(formatter)
102
103         # add the handlers to SIMA_LOGGER
104         logger.addHandler(couth)
105         logger.addHandler(cerrh)  # Already added creating the handler‽ Still have to figure it out.
106
107 # VIM MODLINE
108 # vim: ai ts=4 sw=4 sts=4 expandtab