Debian Codegraph @

ipapython/ipa_log_manager.py

raw
1 # Authors: John Dennis <[email protected]>
2 #
3 # Copyright (C) 2011 Red Hat
4 # see file 'COPYING' for use and warranty information
5 #
6 # This program 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 # This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
18
19 import logging
20 import os
21 import re
22 import time
23
24 # Module exports
25 __all__ = ['standard_logging_setup',
26 'ISO8601_UTC_DATETIME_FMT',
27 'LOGGING_FORMAT_STDERR', 'LOGGING_FORMAT_STDOUT', 'LOGGING_FORMAT_FILE']
28
29 # Format string for time.strftime() to produce a ISO 8601 date time
30 # formatted string in the UTC time zone.
31 ISO8601_UTC_DATETIME_FMT = '%Y-%m-%dT%H:%M:%SZ'
32
33 # Logging format string for use with logging stderr handlers
34 LOGGING_FORMAT_STDERR = 'ipa: %(levelname)s: %(message)s'
35
36 # Logging format string for use with logging stdout handlers
37 LOGGING_FORMAT_STDOUT = '[%(asctime)s %(name)s] <%(levelname)s>: %(message)s'
38
39 # Logging format string for use with logging file handlers
40 LOGGING_FORMAT_FILE = '\t'.join([
41 '%(asctime)s',
42 '%(process)d',
43 '%(threadName)s',
44 '%(name)s',
45 '%(levelname)s',
46 '%(message)s',
47 ])
48
49 # Used by standard_logging_setup() for console message
50 LOGGING_FORMAT_STANDARD_CONSOLE = '%(name)-12s: %(levelname)-8s %(message)s'
51
52 # Used by standard_logging_setup() for file message
53 LOGGING_FORMAT_STANDARD_FILE = '%(asctime)s %(levelname)s %(message)s'
54
55
56 class Filter:
57 def __init__(self, regexp, level):
58 self.regexp = re.compile(regexp)
59 self.level = level
60
61 def filter(self, record):
62 return (not self.regexp.match(record.name) or
63 record.levelno >= self.level)
64
65
66 class Formatter(logging.Formatter):
67 def __init__(
68 self, fmt=LOGGING_FORMAT_STDOUT, datefmt=ISO8601_UTC_DATETIME_FMT):
69 super(Formatter, self).__init__(fmt, datefmt)
70 self.converter = time.gmtime
71
72
73 def standard_logging_setup(filename=None, verbose=False, debug=False,
74 filemode='w', console_format=None):
75 if console_format is None:
76 console_format = LOGGING_FORMAT_STANDARD_CONSOLE
77
78 root_logger = logging.getLogger()
79 root_logger.setLevel(logging.DEBUG)
80
81 # File output is always logged at debug level
82 if filename is not None:
83 umask = os.umask(0o177)
84 try:
85 file_handler = logging.FileHandler(filename, mode=filemode)
86 finally:
87 os.umask(umask)
88 file_handler.setLevel(logging.DEBUG)
89 file_handler.setFormatter(Formatter(LOGGING_FORMAT_STANDARD_FILE))
90 root_logger.addHandler(file_handler)
91
92 level = logging.ERROR
93 if verbose:
94 level = logging.INFO
95 if debug:
96 level = logging.DEBUG
97
98 console_handler = logging.StreamHandler()
99 console_handler.setLevel(level)
100 console_handler.setFormatter(Formatter(console_format))
101 root_logger.addHandler(console_handler)
102
103
104 def convert_log_level(value):
105 try:
106 level = int(value)
107 except ValueError:
108 try:
109 level = {
110 'debug': logging.DEBUG,
111 'info': logging.INFO,
112 'warn': logging.WARNING,
113 'warning': logging.WARNING,
114 'error': logging.ERROR,
115 'critical': logging.CRITICAL
116 }[value.lower()]
117 except KeyError:
118 raise ValueError('unknown log level (%s)' % value)
119 return level