blob: 94418778b84524df1cd3795b3ed7639f57df6749 [file] [log] [blame]
#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A helper module to set up logging for this library."""
__author__ = 'rogerm@google.com (Roger McFarlane)'
import logging
import optparse
import os
import sys
ROOT_NAME = 'syzygy'
VERBOSE = logging.DEBUG
NORMAL = logging.INFO
QUIET = logging.warning
def GetLogger(name=None):
"""Retrieves a logger object for this library, or a named submodule.
Args:
name: The (optional) name of the submodule. If not given, the logger
for the top level module/library is returned.
Returns:
A logger object.
"""
if name:
name = os.path.splitext(os.path.basename(name))[0]
return logging.getLogger('%s.%s' % (ROOT_NAME, name))
else:
return logging.getLogger(ROOT_NAME)
def AddCommandLineOptions(option_parser):
"""Adds the group of logging related options to the given option_parser.
Args:
option_parser: the option parser object to update. This is expected
to be an instance of optparse.OptionParser.
"""
group = optparse.OptionGroup(option_parser, 'Logging Options')
group.add_option('--log-verbose', action='store_true', default=False,
help='Log verbosely')
group.add_option('--log-file', help='Write the log to this file')
group.add_option('--log-append', action='store_true', default=False,
help='Append to log file')
group.add_option('--log-no-console', action='store_true', default=False,
help='No logging to stderr')
option_parser.add_option_group(group)
def AddStreamHandler(stream, level, logger=None):
"""Maps log entries occuring at level or higher to an output stream.
Args:
stream: The stream to write to. Any object capable of acting like
a File object can be used.
level: The logging level at which to bind the handler.
logger: The logger to which to attach the stream. By default it
if will be the top level logger for this package.
"""
if not logger:
logger = GetLogger()
handler = logging.StreamHandler(stream)
handler.setLevel(level)
handler.setFormatter(logging.Formatter(
'[%(asctime)s] %(levelname)-5s %(message)s','%Y-%m-%dT%H:%M:%S'))
logger.addHandler(handler)
def AddFileHandler(file_path, level, mode, logger=None):
"""Maps log entries occuring at level or higher to a named file.
Args:
file_path: The file to write to.
level: The logging level at which to bind the handler.
mode: The mode with which to open the log file ('a': append, 'w': write).
logger: The logger to which to attach the stream. By default it
if will be the top level logger for this package.
"""
if not logger:
logger = GetLogger()
handler = logging.FileHandler(file_path, mode)
handler.setLevel(level)
handler.setFormatter(logging.Formatter(
'[%(asctime)s:%(filename)s:%(lineno)s] %(levelname)-5s %(message)s',
'%Y-%m-%dT%H:%M:%S'))
logger.addHandler(handler)
def InitLogger(options):
"""Initialize the logging subsystem.
Args:
options: A command-line options object, typically generated by an
optparse.OptionParser instance with a call to its parse_args()
method.
"""
level = options.log_verbose and VERBOSE or NORMAL
logger = GetLogger()
logger.setLevel(level)
if not options.log_no_console:
AddStreamHandler(sys.stderr, level, logger=logger)
if options.log_file:
mode = options.log_append and 'a' or 'w'
AddFileHandler(options.log_file, level, mode, logger=logger)
class NullHandler(logging.Handler):
"""A do-nothing logging handler.
This allows the packages logging calls to work even if logging isn't
specifically enabled/configured for the package.
See: http://docs.python.org/library/logging.html#configuring-logging-for-a-library
"""
# pylint: disable=C0103
# -> our pylintrc expects Emit()
def emit(self, record):
pass
GetLogger().addHandler(NullHandler())