source: main/waeup.sirp/trunk/src/waeup/sirp/utils/logger.py @ 6480

Last change on this file since 6480 was 6480, checked in by uli, 13 years ago

Remove confusing old implementation of WAeUPLogger.

File size: 6.1 KB
Line 
1##
2## logging.py
3## Login : <uli@pu.smp.net>
4## Started on  Mon Jun 13 01:25:07 2011 Uli Fouquet
5## $Id$
6##
7## Copyright (C) 2011 Uli Fouquet
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
19## along with this program; if not, write to the Free Software
20## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21##
22"""
23Convenience stuff for logging.
24"""
25import os
26import grok
27import logging
28from zope.interface import Interface, Attribute
29
30class ISiteLoggers(Interface):
31
32    loggers = Attribute("A list or generator of registered WAeUPLoggers")
33
34    def register(name, filename=None, site=None, **options):
35        """Register a logger `name` which logs to `filename`.
36
37        If `filename` is not given, logfile will be `name` with
38        ``.log`` as filename extension.
39        """
40
41    def unregister(name):
42        """Unregister a once registered logger.
43        """
44
45class SiteLoggers(object):
46
47    grok.implements(ISiteLoggers)
48
49    @property
50    def loggers(self):
51        return self._loggers.values()
52
53    def __init__(self):
54        self._loggers = dict()
55
56    def getLogger(self, filename):
57        waeup_logger = self._loggers.get(filename, None)
58        return waeup_logger.logger
59
60    def register(self, loggername, filename=None, site=None, **kw):
61        if loggername in self._loggers.keys():
62            raise KeyError('Logger "%s" exists already.' % loggername)
63        self._loggers[loggername] = WAeUPLogger(
64            loggername, filename=filename, site=site, **kw)
65        return
66
67    def unregister(self, name):
68        if name in self._loggers.keys():
69            del self._loggers[name]
70        return
71
72    def keys(self):
73        return self._loggers.keys()
74
75class ILogger(Interface):
76    """A logger cares for setup, update and restarting of a Python logger.
77    """
78
79    logger = Attribute("""A :class:`logging.Logger` instance""")
80
81
82    def __init__(name, filename=None, site=None, **options):
83        """Create a WAeUP logger instance.
84        """
85        pass
86
87    def setup():
88        """Create a Python :class:`logging.Logger` instance.
89
90        The created logger is based on the params given by constructor.
91        """
92        pass
93
94    def update(**options):
95        """Update the logger.
96
97        Updates the logger respecting modified `options` and changed
98        paths.
99        """
100
101class WAeUPLogger(object):
102
103    grok.implements(ILogger)
104
105    _logger = None
106
107    def __init__(self, name, filename=None, site=None, **options):
108        self.name = name
109        self.filename = filename
110        if filename is None:
111            if '.' in name:
112                name = name.rsplit('.', 1)[1]
113            self.filename = "%s.log" % name
114        self.site = site
115        self.max_bytes = options.get('maxBytes', 5 * 1024 ** 2)
116        self.backup_count = options.get('backupCount', 5)
117        self.options = options
118        return
119
120    @property
121    def logger(self):
122        if self._needSetup():
123            self._setup()
124        return logging.getLogger(self._loggername)
125
126    def setup(self):
127        return self._setup()
128
129    def update(self, **options):
130        self._logger = None # unset to be set up again on next access.
131        # XXX: set options
132        pass
133
134    def _needSetup(self):
135        if self._logger is None:
136            return True
137        if not '__app' in self._logger.name:
138            return False
139        if getattr(self.site, '__name__', None) is not None:
140            return True
141        return False
142
143    def _removeHandlers(self):
144        handlers = self._logger.handlers
145        for handler in handlers:
146            self._logger.removeHandler(handler)
147
148    def _setup(self):
149        if self.site is None:
150            self.site = grok.getSite()
151        self._loggername = self.name
152        if not '.' in self._loggername:
153            self._loggername = 'waeup.sirp.%s.%s' % ('%s', self._loggername)
154        if '%s' in self._loggername:
155            site_name = getattr(self.site, '__name__', '__app')
156            if site_name is None:
157                site_name = '__app'
158            self._loggername = self._loggername % (site_name,)
159        self._logger = logging.getLogger(self._loggername)
160        return self._update()
161
162    def _update(self):
163        self._removeHandlers() # Remove any old handlers
164        self._logdir = os.path.join(self.site['datacenter'].storage, 'logs')
165        if not os.path.exists(self._logdir):
166            os.mkdir(self._logdir)
167        filename = os.path.join(self._logdir, self.filename)
168
169        # Create a rotating file handler logger for datacenter.
170        default_handler = logging.handlers.RotatingFileHandler(
171            filename, maxBytes=self.max_bytes, backupCount=self.backup_count)
172        self.handler = self.options.get('handler', default_handler)
173
174        default_formatter = logging.Formatter(
175            '%(asctime)s - %(levelname)s - %(message)s')
176        formatter = self.options.get('formatter', default_formatter)
177        self.handler.setFormatter(formatter)
178
179        self._logger.addHandler(self.handler)
180        self._logger.propagate = self.options.get('propagate', False)
181        self._logger.setLevel(self.options.get('level', logging.DEBUG))
182        return self._logger
183
184#: A place where we store seen loggers.
185SiteLoggersRepository = dict()
186
187class SiteLoggersFinder(object):
188    grok.provides(ISiteLoggers)
189
190    def getLoggers(self, site=None):
191        if site is None:
192            site = grok.getSite()
193        if site not in SiteLoggersRepository.keys():
194            SiteLoggersRepository[site] = SiteLoggers()
195        return SiteLoggersRepository[site]
196
197grok.global_utility(SiteLoggersFinder, provides=ISiteLoggers)
Note: See TracBrowser for help on using the repository browser.