Skip to content
Browse files

Add configurable logging setup to alerts.init().

  • Loading branch information...
1 parent 167cdac commit d253f2e3970c55bd111040219f8996df5ce93d1e Logan Hanks committed
Showing with 101 additions and 23 deletions.
  1. +53 −4 alerts.py
  2. +48 −0 alerts_test.py
  3. +0 −19 tallier.py
View
57 alerts.py
@@ -1,6 +1,11 @@
#!/usr/bin/python
import ConfigParser
+import logging
+import logging.handlers
+import os
+import sys
+import time
import wessex
@@ -9,6 +14,13 @@
harold = None
config = None
+def init(config_path='production.ini'):
+ global config, harold
+ config = load_config(path=config_path)
+ if config.has_section('logging'):
+ configure_logging(config)
+ harold = get_harold(config)
+
def load_config(path='production.ini'):
config = ConfigParser.RawConfigParser()
config.read([path])
@@ -21,7 +33,44 @@ def get_harold(config):
return wessex.Harold(
host=harold_host, port=harold_port, secret=harold_secret)
-def init(config_path='production.ini'):
- global config, harold
- config = load_config(path=config_path)
- harold = get_harold(config)
+class StreamLoggingFormatter(logging.Formatter):
+ def formatTime(self, record, datefmt=None):
+ timestamp = time.strftime(datefmt)
+ return timestamp % dict(ms=(1000 * record.created) % 1000)
+
+def _get_logging_handler(config):
+ mode = config.get('logging', 'mode')
+ if mode == 'file':
+ return logging.FileHandler(config.get('logging', 'file'))
+ elif mode == 'stderr':
+ return logging.StreamHandler()
+ elif mode == 'syslog':
+ return logging.handlers.SysLogHandler(
+ config.get('logging', 'syslog_addr'))
+ else:
+ raise ValueError('unsupported logging mode: %r' % mode)
+
+def _get_logging_formatter(config):
+ mode = config.get('logging', 'mode')
+ if mode == 'syslog':
+ app_name = os.path.basename(sys.argv[0])
+ return logging.Formatter(
+ '%s: [%%(levelname)s] %%(message)s' % app_name)
+ else:
+ return StreamLoggingFormatter(
+ '%(levelname).1s%(asctime)s: %(message)s',
+ '%m%d %H:%M:%S.%%(ms)03d')
+
+def _get_logging_level(config):
+ if config.has_option('logging', 'level'):
+ return config.get('logging', 'level')
+ else:
+ return logging.INFO
+
+def configure_logging(config):
+ ch = _get_logging_handler(config)
+ ch.setFormatter(_get_logging_formatter(config))
+ logger = logging.getLogger()
+ logger.setLevel(_get_logging_level(config))
+ logger.addHandler(ch)
+ return logger
View
48 alerts_test.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+
+import ConfigParser
+import logging
+import tempfile
+import unittest
+
+import alerts
+
+class ConfigureLoggingTest(unittest.TestCase):
+ @staticmethod
+ def _config(**data):
+ config = ConfigParser.RawConfigParser()
+ config.add_section('logging')
+ for k, v in data.iteritems():
+ config.set('logging', k, v)
+ return config
+
+ def test_get_logging_handler(self):
+ def assertHandler(mode, expected_class):
+ with tempfile.NamedTemporaryFile() as f:
+ config = self._config(mode=mode, file=f.name,
+ syslog_addr='/dev/log')
+ self.assertTrue(
+ isinstance(
+ alerts._get_logging_handler(config), expected_class))
+
+ assertHandler('file', logging.FileHandler)
+ assertHandler('stderr', logging.StreamHandler)
+ # we can count on the alerts module importing logging.handlers
+ assertHandler('syslog', logging.handlers.SysLogHandler)
+
+ self.assertRaises(ValueError, assertHandler, 'asdf', None)
+
+ def test_get_logging_formatter(self):
+ f = alerts._get_logging_formatter(self._config(mode='syslog'))
+ self.assertFalse(isinstance(f, alerts.StreamLoggingFormatter))
+ f = alerts._get_logging_formatter(self._config(mode='not-syslog'))
+ self.assertTrue(isinstance(f, alerts.StreamLoggingFormatter))
+
+ def test_get_logging_level(self):
+ config = self._config()
+ self.assertEquals(logging.INFO, alerts._get_logging_level(config))
+ config = self._config(level='DEBUG')
+ self.assertEquals('DEBUG', alerts._get_logging_level(config))
+
+if __name__ == '__main__':
+ unittest.main()
View
19 tallier.py
@@ -438,27 +438,8 @@ def _parse_part(cls, key, part):
value_type = cls.COUNTER
return cls(key, value, value_type, sample_rate)
-def configure_logging(config):
- class LoggingFormatter(logging.Formatter):
- def formatTime(self, record, datefmt=None):
- timestamp = time.strftime(datefmt)
- return timestamp % dict(ms=(1000 * record.created) % 1000)
-
- logger = logging.getLogger()
- logger.setLevel(logging.INFO)
- if config.has_option('tallier', 'log_file'):
- ch = logging.FileHandler(config.get('tallier', 'log_file'))
- else:
- ch = logging.StreamHandler()
- ch.setLevel(logging.INFO)
- formatter = LoggingFormatter(
- '%(levelname).1s%(asctime)s: %(message)s', '%m%d %H:%M:%S.%%(ms)03d')
- ch.setFormatter(formatter)
- logger.addHandler(ch)
-
if __name__ == '__main__':
alerts.init()
- configure_logging(alerts.config)
master = Master.from_config(alerts.config, alerts.harold)
logging.info('Serving...')
master.start()

0 comments on commit d253f2e

Please sign in to comment.
Something went wrong with that request. Please try again.