Action: store a logger object in each Action.
[matthijs/projects/backupninja.git] / src / lib / backupninja / log.py
1 # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; -*-
2 # vim: set filetype=python sw=4 sts=4 expandtab autoindent:
3 #
4 #    Backupninja python reimplementation, based on original backupninja program
5 #    by riseup.net.
6 #    Copyright (C) 2010  Matthijs Kooijman <matthijs@stdin.nl>
7 #
8 #    This program is free software; you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation; either version 2 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License along
19 #    with this program; if not, write to the Free Software Foundation, Inc.,
20 #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 """ Sets up the python logging library for use with backupninja """
23
24 import logging
25 log = logging.getLogger()
26
27 def setup_logging(options):
28     """
29     Setup the logging library, so other modules can just use
30     logging.getLogger or the root logger directly.
31     
32     options are the parsed commandline options.
33     """
34     # We use the default options for now
35     level = logging.INFO
36     if(options.debug):
37         level = logging.DEBUG
38     logging.basicConfig(level=level)
39     log.debug("Initialized logging configuration")
40
41 def log_exception(log, msg="%s"):
42     """
43     This is a decorator that catches an exception, logs the exception
44     and a backtrace and then swallows it. log is the Logging instance to
45     log to (using the "error" level for the message, and "debug" for the
46     backtrace), msg is the message to log (which must contain a %s into
47     which the exception message is interpolated).
48     """
49     def decorator(f):
50         def inner(*args, **kwargs):
51             try:
52                 f(*args, **kwargs)
53             except Exception, e:
54                 log.error(msg, e)
55                 import traceback
56                 log.debug(traceback.format_exc())
57         return inner
58     return decorator