1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2009, 2010, 2013, 2014, 2015 Jack Kaliko <kaliko@azylum.org>
4 # This file is part of sima
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.
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.
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/>.
22 Logging facility for sima.
25 # standard library import
29 from os import environ
35 DEBUG: '[{process}]{filename: >11}:{lineno: <3} {levelname: <7}: {message}',
36 INFO: '{levelname: <7}: {message}',
37 #logging.DEBUG: '{asctime} {filename}:{lineno}({funcName}) '
38 #'{levelname}: {message}',
40 DATE_FMT = "%Y-%m-%d %H:%M:%S"
43 logging.addLevelName(TRACE_LEVEL_NUM, 'TRACE')
44 def trace(self, message, *args, **kwargs):
45 # Yes, logger takes its '*args' as 'args'.
46 if self.isEnabledFor(TRACE_LEVEL_NUM):
47 self._log(TRACE_LEVEL_NUM, message, args, **kwargs)
49 logging.Logger.trace = trace
52 def set_logger(level='info', logfile=None):
55 level: in debug, info, warning,…
56 logfile: file to log to
60 if environ.get('TRACE', False):
61 user_log_level = TRACE_LEVEL_NUM
63 user_log_level = getattr(logging, level.upper())
64 if user_log_level > DEBUG:
65 log_format = LOG_FORMATS.get(INFO)
67 log_format = LOG_FORMATS.get(DEBUG)
68 logger = logging.getLogger(name)
69 formatter = logging.Formatter(log_format, DATE_FMT, '{')
70 logger.setLevel(user_log_level)
73 for hdl in logger.handlers:
74 hdl.setFormatter(formatter)
75 if isinstance(hdl, logging.FileHandler):
78 logger.removeHandler(hdl)
83 # Add timestamp for file handler
84 log_format = '{0} {1}'.format('{asctime}', log_format)
85 formatter = logging.Formatter(log_format, DATE_FMT, '{')
87 fileh = logging.FileHandler(logfile)
88 fileh.setFormatter(formatter)
89 logger.addHandler(fileh)
92 logger.info('Not changing logging handlers, only updating formatter')
94 # create console handler with a specified log level (STDOUT)
95 couth = logging.StreamHandler(sys.stdout)
96 couth.addFilter(lambda record: record.levelno < ERROR)
98 # create console handler with warning log level (STDERR)
99 cerrh = logging.StreamHandler(sys.stderr)
100 cerrh.setLevel(ERROR)
102 # add formatter to the handlers
103 cerrh.setFormatter(formatter)
104 couth.setFormatter(formatter)
106 # add the handlers to SIMA_LOGGER
107 logger.addHandler(couth)
108 logger.addHandler(cerrh) # Already added creating the handler‽ Still have to figure it out.
111 # vim: ai ts=4 sw=4 sts=4 expandtab