Created
April 2, 2014 08:06
-
-
Save nl5887/9929911 to your computer and use it in GitHub Desktop.
LogglyHandler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import traceback | |
LOGGLY_URL = "https://logs-01.loggly.com/inputs/{{ LOGGLY_ID }}/tag/{{ TAG }}/" | |
class LogglyHandler(logging.Handler): | |
def emit(self, record): | |
trace = None | |
exc = record.__dict__['exc_info'] | |
if exc: | |
trace = traceback.format_exc(exc) | |
from pyramid.threadlocal import get_current_request, get_current_registry | |
request = get_current_request() | |
try: | |
from pyramid.security import unauthenticated_userid | |
userid = unauthenticated_userid(request) | |
payload = { | |
'logger': record.__dict__.get('name'), | |
'level': record.__dict__.get('levelname'), | |
'trace': str(trace), | |
'module': record.__dict__.get('module'), | |
'pathname': record.__dict__.get('pathname'), | |
'lineno': record.__dict__.get('lineno'), | |
'func': str(record.__dict__.get('funcName')), | |
'statuscode': record.__dict__.get('statuscode'), | |
'message': str(record.__dict__.get('msg')), | |
'url': request.url if hasattr(request, 'url') else None, | |
'ip': request.client_addr if hasattr(request, 'client_addr') else None, | |
'referer': request.referer if hasattr(request, 'referer') else None, | |
'useragent': request.user_agent if hasattr(request, 'user_agent') else None, | |
'server': socket.gethostname(), | |
'userid': userid | |
} | |
headers = {'content-type': 'application/json', 'X-LOGGLY-TAG': socket.gethostname()} | |
import json | |
import socket | |
import requests | |
b= requests.post(LOGGLY_URL, data=json.dumps(payload), headers=headers) | |
if (b.json().get('response')!="ok"): | |
print b.json() | |
except Exception, exc: | |
print exc | |
print traceback.format_exc(exc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment