Login

Simple Syslog Logging Class with Decorator

Author:
barnardo
Posted:
July 16, 2010
Language:
Python
Version:
1.2
Score:
-1 (after 1 ratings)

Simple logging decorator. Logs the function name along with the message.

Jul 14 16:10:42 mtzion test_func: 1 two

Define SYSLOG_FACILITY in settings.py.

import syslog
SYSLOG_FACILITY = syslog.LOG_LOCAL1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import syslog
from <app-name> import settings

class SysLogging:
    def __init__(self, facility, prefix=None):
        self.facility = facility
        if prefix:
            syslog.openlog(prefix)
    def _logit(self, priority, message):
        syslog.syslog(self.facility | priority, '%s' % (message))
    def debug(self, message):
        self._logit(syslog.LOG_DEBUG, message)
    def info(self, message):
        self._logit(syslog.LOG_INFO, message)
    def notice(self, message):
        self._logit(syslog.LOG_NOTICE, message)
    def warning(self, message):
        self._logit(syslog.LOG_WARNING, message)
    def error(self, message):
        self._logit(syslog.LOG_ERR, message)
    def crit(self, message):
        self._logit(syslog.LOG_CRIT, message)
    def alert(self, message):
        self._logit(syslog.LOG_ALERT, message)
    def emerg(self, message):
        self._logit(syslog.LOG_EMERG, message)

def syslogging(func):
    def caller(*args, **kwargs):
        if 'logger' not in kwargs:
            kwargs['logger'] = SysLogging(settings.SYSLOG_FACILITY, func.__name__)
        return func(*args, **kwargs)
    return caller

@syslogging
def test_func(arg1, arg2=None, logger=None):
    logger.info('%s %s' % (arg1, arg2))

if __name__ == '__main__':
    test_func(1, 'two')

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.