4 # Copyright (C) 2006, 2007 Google Inc.
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 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 This module abstracts the logging handling away from the rest of the
25 Ganeti code. It offers some utility functions for easy logging.
29 # pylint: disable-msg=W0603,C0103
35 def SetupLogging(logfile, debug=False, stderr_logging=False, program=""):
36 """Configures the logging module.
39 fmt = "%(asctime)s: " + program + " "
41 fmt += ("pid=%(process)d/%(threadName)s %(levelname)s"
42 " %(module)s:%(lineno)s %(message)s")
44 fmt += "pid=%(process)d %(levelname)s %(message)s"
45 formatter = logging.Formatter(fmt)
47 root_logger = logging.getLogger("")
48 root_logger.setLevel(logging.NOTSET)
51 stderr_handler = logging.StreamHandler()
52 stderr_handler.setFormatter(formatter)
54 stderr_handler.setLevel(logging.NOTSET)
56 stderr_handler.setLevel(logging.CRITICAL)
57 root_logger.addHandler(stderr_handler)
59 # this can fail, if the logging directories are not setup or we have
60 # a permisssion problem; in this case, it's best to log but ignore
61 # the error if stderr_logging is True, and if false we re-raise the
62 # exception since otherwise we could run but without any logs at all
64 logfile_handler = logging.FileHandler(logfile)
65 logfile_handler.setFormatter(formatter)
67 logfile_handler.setLevel(logging.DEBUG)
69 logfile_handler.setLevel(logging.INFO)
70 root_logger.addHandler(logfile_handler)
71 except EnvironmentError, err:
73 logging.exception("Failed to enable logging to file '%s'", logfile)
75 # we need to re-raise the exception
79 # Backwards compatibility
86 """Write a message to stdout only, bypassing the logging system
92 sys.stdout.write(txt + '\n')
97 """Write a message to stderr only, bypassing the logging system
103 sys.stderr.write(txt + '\n')