1 # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
2 # Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 from __future__ import print_function
23 import logging.handlers
30 import configparser as ConfigParser
35 CONF.register_cli_opts([
36 cfg.IntOpt('default-log-level', default=None, help='default log level'),
37 cfg.BoolOpt('verbose', default=False, help='show debug output'),
38 cfg.BoolOpt('use-stderr', default=True, help='log to standard error'),
39 cfg.BoolOpt('use-syslog', default=False, help='output to syslog'),
40 cfg.StrOpt('log-dir', default=None, help='log file directory'),
41 cfg.StrOpt('log-file', default=None, help='log file name'),
42 cfg.StrOpt('log-file-mode', default='0644',
43 help='default log file permission'),
44 cfg.StrOpt('log-config-file', default=None,
45 help='Path to a logging config file to use')
49 _EARLY_LOG_HANDLER = None
52 def early_init_log(level=None):
53 global _EARLY_LOG_HANDLER
54 _EARLY_LOG_HANDLER = logging.StreamHandler(sys.stderr)
56 log = logging.getLogger()
57 log.addHandler(_EARLY_LOG_HANDLER)
66 return os.path.join(CONF.log_dir,
67 os.path.basename(inspect.stack()[-1][1])) + '.log'
72 global _EARLY_LOG_HANDLER
74 log = logging.getLogger()
76 if CONF.log_config_file:
78 logging.config.fileConfig(CONF.log_config_file,
79 disable_existing_loggers=False)
80 except ConfigParser.Error as e:
81 print('Failed to parse %s: %s' % (CONF.log_config_file, e),
87 log.addHandler(logging.StreamHandler(sys.stderr))
88 if _EARLY_LOG_HANDLER is not None:
89 log.removeHandler(_EARLY_LOG_HANDLER)
90 _EARLY_LOG_HANDLER = None
93 if platform.system() == 'Darwin':
94 address = '/var/run/syslog'
97 syslog = logging.handlers.SysLogHandler(address=address)
98 log.addHandler(syslog)
100 log_file = _get_log_file()
101 if log_file is not None:
102 log.addHandler(logging.handlers.WatchedFileHandler(log_file))
103 mode = int(CONF.log_file_mode, 8)
104 os.chmod(log_file, mode)
106 if CONF.default_log_level is not None:
107 log.setLevel(CONF.default_log_level)
109 log.setLevel(logging.DEBUG)
111 log.setLevel(logging.INFO)