1 # -----------------------------------------------------------------------
2 # Copyright (C) 2007 Georgia Public Library Service
3 # Bill Erickson <billserickson@gmail.com>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 # -----------------------------------------------------------------------
17 import traceback, sys, os, re
18 from osrf.const import *
22 def osrfInitLog(level, facility=None, file=None):
23 """Initialize the logging subsystem."""
25 if facility: osrfInitSyslog(facility, level)
27 syslog(LOG_DEBUG, "syslog initialized")
30 # -----------------------------------------------------------------------
31 # Define wrapper functions for the log levels
32 # -----------------------------------------------------------------------
33 def osrfLogInternal(s): __osrfLog(OSRF_LOG_INTERNAL,s)
34 def osrfLogDebug(s): __osrfLog(OSRF_LOG_DEBUG,s)
35 def osrfLogInfo(s): __osrfLog(OSRF_LOG_INFO,s)
36 def osrfLogWarn(s): __osrfLog(OSRF_LOG_WARN,s)
37 def osrfLogErr(s): __osrfLog(OSRF_LOG_ERR,s)
40 frgx = re.compile('/.*/')
42 def __osrfLog(level, msg):
43 """Builds the log message and passes the message off to the logger."""
45 if int(level) > int(loglevel): return
47 # find the caller info for logging the file and line number
48 tb = traceback.extract_stack(limit=3)
53 if level == OSRF_LOG_INTERNAL: lvl = 'INT '; slvl=LOG_DEBUG
54 if level == OSRF_LOG_INFO: lvl = 'INFO'; slvl=LOG_INFO
55 if level == OSRF_LOG_WARN: lvl = 'WARN'; slvl=LOG_WARNING
56 if level == OSRF_LOG_ERR: lvl = 'ERR '; slvl=LOG_ERR
58 file = frgx.sub('',tb[0])
59 msg = '[%s:%d:%s:%s] %s' % (lvl, os.getpid(), file, tb[1], msg)
62 if level == OSRF_LOG_ERR:
63 sys.stderr.write(msg + '\n')
66 def osrfInitSyslog(facility, level):
67 """Connect to syslog and set the logmask based on the level provided."""
71 if facility == 'local0': facility = LOG_LOCAL0
72 if facility == 'local1': facility = LOG_LOCAL1
73 if facility == 'local2': facility = LOG_LOCAL2
74 if facility == 'local3': facility = LOG_LOCAL3
75 if facility == 'local4': facility = LOG_LOCAL4
76 if facility == 'local5': facility = LOG_LOCAL5
77 if facility == 'local6': facility = LOG_LOCAL6
78 # XXX add other facility maps if necessary
79 openlog(sys.argv[0], 0, facility)
81 # this is redundant...
82 mask = LOG_UPTO(LOG_ERR)
83 if level >= 1: mask |= LOG_MASK(LOG_WARNING)
84 if level >= 2: mask |= LOG_MASK(LOG_NOTICE)
85 if level >= 3: mask |= LOG_MASK(LOG_INFO)
86 if level >= 4: mask |= LOG_MASK(LOG_DEBUG)