from requests_futures.sessions import FuturesSession import logging import logging.handlers import traceback from fpsweeper import config session = FuturesSession() def callback(session, resp): """Post callback. When the post has been dispatched to loggly, handle the response (in our case we don't have anything to do). Args: session (FutureSession): the session that triggered the request. resp (object): the response of the request to the service. """ pass class DSNHandler(logging.Handler): def __init__(self, dsn): logging.Handler.__init__(self) self.dsn = dsn def get_full_message(self, record): """Get the full message for a record. Some of our systems might still require this data to be sent to loggly, so instead of sending the message of the record, we send the exception information. Args: record (LogRecord): the record to log. Return: mixed: the string or an object (dictionary). """ if record.exc_info: return '\n'.join(traceback.format_exception(*record.exc_info)) else: return record.msg def emit(self, record): """Emit a record. From the documentation: do whatever it takes to actually log the specified logging record. Here: we send it to the provider. The payload matches Orchard format. Args: record (LogRecord): the record to log. """ try: payload = { 'tag': 'ows1', 'timestamp': record.created, 'level': record.levelname, 'correlation_id': record.correlation_id, 'message': self.get_full_message(record), 'service': config.SERVICE_NAME, 'service_version': config.SERVICE_VERSION, 'environment': config.environment, 'meta': { 'file_name': record.filename, 'function_name': record.funcName, 'line': record.lineno } } session.post(self.dsn, data=payload, background_callback=callback) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)