1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2009, 2010, 2013, 2014 Jack Kaliko <kaliko@azylum.org>
5 # This file is part of sima
7 # sima is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # sima is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with sima. If not, see <http://www.gnu.org/licenses/>.
23 Logging facility for sima.
26 # standard library import
32 logging.DEBUG: '{asctime} {filename: >10}:{lineno: <3} {levelname: <5}: {message}',
33 logging.INFO: '{asctime} {levelname: <7}: {message}',
34 #logging.DEBUG: '{asctime} {filename}:{lineno}({funcName}) '
35 #'{levelname}: {message}',
37 DATE_FMT = "%Y-%m-%d %H:%M:%S"
40 class LevelFilter(logging.Filter):# Logging facility
42 Enable logging between two log level by filtering everything < level.
45 def __init__(self, filt_level):
46 logging.Filter.__init__(self)
47 self.level = filt_level
49 def filter(self, record):
50 """Defines loglevel"""
51 return record.levelno <= self.level
54 def set_logger(level='info', logfile=None, name='sima'):
57 level: in debug, info, warning,…
58 file: provides to log to file
61 user_log_level = getattr(logging, level.upper())
62 if user_log_level > logging.DEBUG:
63 log_format = LOG_FORMATS.get(logging.INFO)
65 log_format = LOG_FORMATS.get(logging.DEBUG)
66 logg = logging.getLogger(name)
67 formatter = logging.Formatter(log_format, DATE_FMT, '{')
68 logg.setLevel(user_log_level)
71 fileh = logging.FileHandler(logfile)
72 #fileh.setLevel(user_log_level)
73 fileh.setFormatter(formatter)
74 if not logg.hasHandlers():
75 logg.addHandler(fileh)
77 if not logg.hasHandlers():
78 # create console handler with a specified log level (STDOUT)
79 couth = logging.StreamHandler(sys.stdout)
80 #couth.setLevel(user_log_level)
81 couth.addFilter(LevelFilter(logging.WARNING))
83 # create console handler with warning log level (STDERR)
84 cerrh = logging.StreamHandler(sys.stderr)
85 #cerrh.setLevel(logging.WARNING)
86 cerrh.setLevel(logging.ERROR)
88 # add formatter to the handlers
89 cerrh.setFormatter(formatter)
90 couth.setFormatter(formatter)
92 # add the handlers to SIMA_LOGGER
93 logg.addHandler(couth)
94 logg.addHandler(cerrh)
97 # vim: ai ts=4 sw=4 sts=4 expandtab