1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2009, 2010, 2013, 2014 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
31 logging.DEBUG: '{asctime} {filename: >11}:{lineno: <3} {levelname: <7}: {message}',
32 logging.INFO: '{asctime} {levelname: <7}: {message}',
33 #logging.DEBUG: '{asctime} {filename}:{lineno}({funcName}) '
34 #'{levelname}: {message}',
36 DATE_FMT = "%Y-%m-%d %H:%M:%S"
39 class LevelFilter(logging.Filter):# Logging facility
41 Enable logging between two log level by filtering everything < level.
44 def __init__(self, filt_level):
45 logging.Filter.__init__(self)
46 self.level = filt_level
48 def filter(self, record):
49 """Defines loglevel"""
50 return record.levelno <= self.level
53 def set_logger(level='info', logfile=None, name='sima'):
56 level: in debug, info, warning,…
57 file: provides to log to file
60 user_log_level = getattr(logging, level.upper())
61 if user_log_level > logging.DEBUG:
62 log_format = LOG_FORMATS.get(logging.INFO)
64 log_format = LOG_FORMATS.get(logging.DEBUG)
65 logg = logging.getLogger(name)
66 formatter = logging.Formatter(log_format, DATE_FMT, '{')
67 logg.setLevel(user_log_level)
70 fileh = logging.FileHandler(logfile)
71 #fileh.setLevel(user_log_level)
72 fileh.setFormatter(formatter)
73 if not logg.hasHandlers():
74 logg.addHandler(fileh)
76 if not logg.hasHandlers():
77 # create console handler with a specified log level (STDOUT)
78 couth = logging.StreamHandler(sys.stdout)
79 #couth.setLevel(user_log_level)
80 couth.addFilter(LevelFilter(logging.WARNING))
82 # create console handler with warning log level (STDERR)
83 cerrh = logging.StreamHandler(sys.stderr)
84 #cerrh.setLevel(logging.WARNING)
85 cerrh.setLevel(logging.ERROR)
87 # add formatter to the handlers
88 cerrh.setFormatter(formatter)
89 couth.setFormatter(formatter)
91 # add the handlers to SIMA_LOGGER
92 logg.addHandler(couth)
93 logg.addHandler(cerrh)
96 # vim: ai ts=4 sw=4 sts=4 expandtab