Skip to content

Commit ee02d52

Browse files
committed
switch to std lib logging from print statements
1 parent 455bf5a commit ee02d52

2 files changed

Lines changed: 62 additions & 14 deletions

File tree

rabbit/conf.d/rabbitmq.pyconf

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,14 @@ modules {
3232
param zero_rates_when_idle {
3333
value = "True"
3434
}
35-
35+
# Where to log information from this module (syslog facility)
36+
param syslog_facility {
37+
value = "user"
38+
}
39+
# log level, WARNING is not expected to produce any output
40+
param log_level {
41+
value = "WARNING"
42+
}
3643
}
3744
}
3845

rabbit/python_modules/rabbitmq.py

Lines changed: 54 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import itertools
44
import json
5+
import logging
6+
import logging.handlers
57
import optparse
68
import os
79
import sys
@@ -88,8 +90,10 @@ def dig_it_up(obj,path):
8890
try:
8991
path = path.split(JSON_PATH_SEPARATOR)
9092
return reduce(lambda x,y:x[y],path,obj)
91-
except:
92-
print "Exception"
93+
except Exception, e:
94+
# not WARN because the False return is used for control flow
95+
# (zero assumed)
96+
log.debug('dig_it_up Exception %r path: %s' % (e, path))
9397
return False
9498

9599
def refreshStats(stats = ('nodes', 'queues'), vhosts = ['/']):
@@ -105,15 +109,15 @@ def refreshStats(stats = ('nodes', 'queues'), vhosts = ['/']):
105109
diff = now - last_update
106110

107111
if diff >= INTERVAL or not last_update:
108-
print "Fetching Results after %d seconds" % INTERVAL
112+
log.debug("Fetching Results after %d seconds" % INTERVAL)
109113
last_update = now
110114
for stat in stats:
111115
for vhost in vhosts:
112116
if stat in ('nodes'):
113117
vhost = '/'
114118
result_dict = {}
115119
urlstring = url_template.safe_substitute(stats = stat, vhost = vhost)
116-
print urlstring
120+
log.debug('urlspring: %s' % urlstring)
117121
result = json.load(urllib2.urlopen(urlstring))
118122
# Rearrange results so entry is held in a dict keyed by name - queue name, host name, etc.
119123
if stat in ("queues", "nodes", "exchanges"):
@@ -146,7 +150,8 @@ def getQueueStat(name):
146150
#Split a name like "rmq_backing_queue_ack_egress_rate.access"
147151

148152
#handle queue names with . in them
149-
print name
153+
154+
log.debug(name)
150155
stat_name, queue_name, vhost = name.split(METRIC_TOKEN_SEPARATOR)
151156

152157
vhost = vhost.replace('-', '/') #decoding vhost from metric name
@@ -175,7 +180,7 @@ def getNodeStat(name):
175180
result = compiled_results[('nodes', '/')]
176181
value = dig_it_up(result, keyToPath[stat_name] % node_name)
177182

178-
print name,value
183+
log.debug('name: %r value: %r' % (name, value))
179184
#Convert Booleans
180185
if value is True:
181186
value = 1
@@ -204,7 +209,9 @@ def str2bool(string):
204209
def metric_init(params):
205210
''' Create the metric definition object '''
206211
global descriptors, stats, vhost, username, password, urlstring, url_template, compiled_results, STATS, vhosts, zero_rates_when_idle
207-
print 'received the following params:'
212+
if log is None:
213+
setup_logging('syslog', params['syslog_facility'], params['log_level'])
214+
log.info('received the following params: %r' % params)
208215
#Set this globally so we can refresh stats
209216
if 'host' not in params:
210217
params['host'], params['vhost'],params['username'],params['password'],params['port'] = "localhost", "/", "guest", "guest", "15672"
@@ -228,7 +235,6 @@ def metric_init(params):
228235
opener.open(base_url)
229236
urllib2.install_opener(opener)
230237
url_template = Template(url)
231-
print params
232238

233239
refreshStats(stats = STATS, vhosts = vhosts)
234240

@@ -262,7 +268,7 @@ def buildQueueDescriptors():
262268
queues = list_queues(vhost)
263269
for queue in queues:
264270
name = "{1}{0}{2}{0}{3}".format(METRIC_TOKEN_SEPARATOR, metric, queue, vhost.replace('/', '-'))
265-
print name
271+
log.debug(name)
266272
d1 = create_desc({'name': name.encode('ascii','ignore'),
267273
'call_back': getQueueStat,
268274
'value_type': 'float',
@@ -271,14 +277,14 @@ def buildQueueDescriptors():
271277
'format': '%f',
272278
'description': 'Queue_Metric',
273279
'groups' : 'rabbitmq,queue'})
274-
print d1
280+
log.debug(d1)
275281
descriptors.append(d1)
276282

277283
def buildNodeDescriptors():
278284
for metric in NODE_METRICS:
279285
for node in list_nodes():
280286
name = "{1}{0}{2}{0}-".format(METRIC_TOKEN_SEPARATOR, metric, node)
281-
print name
287+
log.debug(name)
282288
d2 = create_desc({'name': name.encode('ascii','ignore'),
283289
'call_back': getNodeStat,
284290
'value_type': 'float',
@@ -287,7 +293,7 @@ def buildNodeDescriptors():
287293
'format': '%f',
288294
'description': 'Node_Metric',
289295
'groups' : 'rabbitmq,node'})
290-
print d2
296+
log.debug(d2)
291297
descriptors.append(d2)
292298

293299
buildQueueDescriptors()
@@ -300,6 +306,30 @@ def metric_cleanup():
300306
pass
301307

302308

309+
def setup_logging(handlers, facility, level):
310+
global log
311+
312+
log = logging.getLogger('gmond_python_rabbitmq')
313+
formatter = logging.Formatter(' | '.join(['%(asctime)s', '%(name)s', '%(levelname)s', '%(message)s']))
314+
if handlers in ['syslog', 'both']:
315+
sh = logging.handlers.SysLogHandler(address='/dev/log', facility=facility)
316+
sh.setFormatter(formatter)
317+
log.addHandler(sh)
318+
if handlers in ['stderr', 'both']:
319+
ch = logging.StreamHandler()
320+
ch.setFormatter(formatter)
321+
log.addHandler(ch)
322+
lmap = {
323+
'CRITICAL': logging.CRITICAL,
324+
'ERROR': logging.ERROR,
325+
'WARNING': logging.WARNING,
326+
'INFO': logging.INFO,
327+
'DEBUG': logging.DEBUG,
328+
'NOTSET': logging.NOTSET
329+
}
330+
log.setLevel(lmap[level])
331+
332+
303333
def parse_args(argv):
304334
parser = optparse.OptionParser()
305335
parser.add_option('--admin-host',
@@ -308,13 +338,24 @@ def parse_args(argv):
308338
parser.add_option('--admin-port',
309339
action='store', dest='admin_port', default=15672,
310340
help='')
341+
parser.add_option('--log',
342+
action='store', dest='log', default='stderr', choices=['stderr', 'syslog', 'both'],
343+
help='log to stderr and/or syslog')
344+
parser.add_option('--log-level',
345+
action='store', dest='log_level', default='WARNING',
346+
choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET'],
347+
help='log to stderr and/or syslog')
348+
parser.add_option('--log-facility',
349+
action='store', dest='log_facility', default='user',
350+
help='facility to use when using syslog')
311351

312352
return parser.parse_args(argv)
313353

314354

315355
def main(argv):
316356
""" used for testing """
317357
(opts, args) = parse_args(argv)
358+
setup_logging(opts.log, opts.log_facility, opts.log_level)
318359
### in config files we use '/' in vhosts names but we should convert '/' to '-' when calculating a metric
319360
parameters = {"vhost":"/", "username":"guest","password":"guest", "metric_group":"rabbitmq",
320361
"zero_rates_when_idle": "yes",
@@ -333,7 +374,7 @@ def main(argv):
333374
time.sleep(5)
334375
print '----------------------------'
335376
except KeyboardInterrupt:
336-
print 'KeyboardInterrupt, shutting down...'
377+
log.debug('KeyboardInterrupt, shutting down...')
337378
metric_cleanup()
338379

339380
if __name__ == "__main__":

0 commit comments

Comments
 (0)