]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/python/osrf/log.py
906fd54ab8119a46a128aab685286560e38cad70
[OpenSRF.git] / src / python / osrf / log.py
1 # -----------------------------------------------------------------------
2 # Copyright (C) 2007  Georgia Public Library Service
3 # Bill Erickson <erickson@esilibrary.com>
4
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.
9
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 # -----------------------------------------------------------------------
15
16 import traceback, sys, os, re, threading, time
17 from osrf.const import OSRF_LOG_DEBUG, OSRF_LOG_ERR, OSRF_LOG_INFO, \
18     OSRF_LOG_INTERNAL, OSRF_LOG_TYPE_FILE, OSRF_LOG_TYPE_STDERR, \
19     OSRF_LOG_TYPE_SYSLOG, OSRF_LOG_WARN, OSRF_LOG_ACT
20 LOG_SEMAPHORE = threading.BoundedSemaphore(value=1)
21
22
23 LOG_LEVEL = OSRF_LOG_DEBUG
24 LOG_TYPE = OSRF_LOG_TYPE_STDERR
25 LOG_FILE = None
26 FRGX = re.compile('/.*/')
27
28 _xid = '' # the current XID
29 _xid_pfx = '' # our XID prefix
30 _xid_ctr = 0
31 _xid_is_client = False # true if we are the request origin
32
33
34 def initialize(level, facility=None, logfile=None, is_client=False, syslog_ident=None):
35     """Initialize the logging subsystem."""
36     global LOG_LEVEL, LOG_TYPE, LOG_FILE, _xid_is_client 
37
38     _xid_is_client = is_client
39     LOG_LEVEL = level
40
41     if facility: 
42         try:
43             import syslog
44         except ImportError:
45             sys.stderr.write("syslog not found, logging to stderr\n")
46             return
47
48         LOG_TYPE = OSRF_LOG_TYPE_SYSLOG
49         initialize_syslog(facility, syslog_ident)
50         return
51         
52     if logfile:
53         LOG_TYPE = OSRF_LOG_TYPE_FILE
54         LOG_FILE = logfile
55
56 def make_xid():
57     global _xid, _xid_pfx, _xid_is_client, _xid_ctr
58     if _xid_is_client:
59         if not _xid_pfx:
60             _xid_pfx = "%s%s" % (time.time(), os.getpid())
61         _xid = "%s%d" % (_xid_pfx, _xid_ctr)
62         _xid_ctr += 1
63          
64 def clear_xid():
65     global _xid
66     _xid =  ''
67
68 def set_xid(xid):
69     global _xid
70     _xid = xid
71
72 def get_xid():
73     return _xid
74
75 # -----------------------------------------------------------------------
76 # Define wrapper functions for the log levels
77 # -----------------------------------------------------------------------
78 def log_internal(debug_str):
79     __log(OSRF_LOG_INTERNAL, debug_str)
80 def log_debug(debug_str):
81     __log(OSRF_LOG_DEBUG, debug_str)
82 def log_info(debug_str):
83     __log(OSRF_LOG_INFO, debug_str)
84 def log_warn(debug_str):
85     __log(OSRF_LOG_WARN, debug_str)
86 def log_error(debug_str):
87     __log(OSRF_LOG_ERR, debug_str)
88 def log_activity(debug_str):
89     __log(OSRF_LOG_ACT, debug_str)
90
91 def __log(level, msg):
92     """Builds the log message and passes the message off to the logger."""
93     global LOG_LEVEL, LOG_TYPE
94
95     try:
96         import syslog
97     except:
98         if level == OSRF_LOG_ERR:
99             sys.stderr.write('ERR ' + msg)
100         return
101         
102     if int(level) > int(LOG_LEVEL): return
103
104     # find the caller info for logging the file and line number
105     tb = traceback.extract_stack(limit=3)
106     tb = tb[0]
107     lvl = 'DEBG'
108
109     if level == OSRF_LOG_INTERNAL:
110         lvl = 'INT '
111     if level == OSRF_LOG_INFO:
112         lvl = 'INFO'
113     if level == OSRF_LOG_WARN:
114         lvl = 'WARN'
115     if level == OSRF_LOG_ERR:
116         lvl = 'ERR '
117     if level == OSRF_LOG_ACT:
118         lvl = 'ACT '
119
120     filename = FRGX.sub('', tb[0])
121     msg = '[%s:%d:%s:%s:%s:%s] %s' % (lvl, os.getpid(), filename, tb[1], threading.currentThread().getName(), _xid, msg)
122
123     if LOG_TYPE == OSRF_LOG_TYPE_SYSLOG:
124         __log_syslog(level, msg)
125     else:
126         if LOG_TYPE == OSRF_LOG_TYPE_FILE:
127             __log_file(msg)
128         else:
129             sys.stderr.write("%s\n" % msg)
130
131     if level == OSRF_LOG_ERR and LOG_TYPE != OSRF_LOG_TYPE_STDERR:
132         sys.stderr.write(msg + '\n')
133
134 def __log_syslog(level, msg):
135     ''' Logs the message to syslog '''
136     import syslog
137
138     slvl = syslog.LOG_DEBUG
139     if level == OSRF_LOG_INTERNAL:
140         slvl = syslog.LOG_DEBUG
141     if level == OSRF_LOG_INFO or level == OSRF_LOG_ACT:
142         slvl = syslog.LOG_INFO
143     if level == OSRF_LOG_WARN:
144         slvl = syslog.LOG_WARNING
145     if level == OSRF_LOG_ERR:
146         slvl = syslog.LOG_ERR
147
148     syslog.syslog(slvl, msg)
149
150 def __log_file(msg):
151     ''' Logs the message to a file. '''
152
153     global LOG_TYPE
154
155     epoch = time.time()
156     timestamp = time.strftime('%Y-%M-%d %H:%m:%S', time.localtime(epoch))
157     timestamp += '.%s' % str('%0.3f' % epoch)[-3:] # grab the millis
158
159     logfile = None
160     try:
161         logfile = open(LOG_FILE, 'a')
162     except:
163         sys.stderr.write("cannot open log file for writing: %s\n" % LOG_FILE)
164         LOG_TYPE = OSRF_LOG_TYPE_STDERR
165         return
166     try:
167         LOG_SEMAPHORE.acquire()
168         logfile.write("%s %s\n" % (timestamp, msg))
169     finally:
170         LOG_SEMAPHORE.release()
171         
172     logfile.close()
173
174 def initialize_syslog(facility, ident=None):
175     """Connect to syslog and set the logmask based on the level provided."""
176
177     import syslog
178     if not ident:
179         ident = sys.argv[0]
180
181     if facility == 'local0':
182         facility = syslog.LOG_LOCAL0
183     if facility == 'local1':
184         facility = syslog.LOG_LOCAL1
185     if facility == 'local2':
186         facility = syslog.LOG_LOCAL2
187     if facility == 'local3':
188         facility = syslog.LOG_LOCAL3
189     if facility == 'local4':
190         facility = syslog.LOG_LOCAL4
191     if facility == 'local5':
192         facility = syslog.LOG_LOCAL5
193     if facility == 'local6':
194         facility = syslog.LOG_LOCAL6
195     if facility == 'local7':
196         facility = syslog.LOG_LOCAL7
197
198     syslog.openlog(str(ident), 0, facility)
199