Skip to content

Instantly share code, notes, and snippets.

@bwhaley
Last active July 6, 2021 11:18
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bwhaley/9380383 to your computer and use it in GitHub Desktop.
Save bwhaley/9380383 to your computer and use it in GitHub Desktop.
Python log handler for Sumo Logic HTTP source
import logging
import logging.config
import sumologger
from sumologger import SumoHTTPHandler
logging.config.dictConfig(sumologger.LOGGING)
logger = logging.getLogger("sumologger")
logger.debug("Nifty log message")
import logging.handlers
# GET method for sending data to Sumo HTTP Source
# http://help.sumologic.com/Help/Default.htm#Uploading_Files_to_an_HTTP_Source.htm
class SumoHTTPHandler(logging.Handler):
def __init__(self, url, host="collectors.sumologic.com", name=None, compressed=False):
"""
Similar to HTTPHandler but with some custom Sumo-friendly headers
"""
logging.Handler.__init__(self)
self.host = host
self.url = url
self.name = name
self.compressed = compressed
def emit(self, record):
try:
import httplib, urllib
host = self.host
h = httplib.HTTPS(host)
url = self.url
data = urllib.quote(self.format(record))
sep = "?"
url = url + "%c%s" % (sep, data)
h.putrequest("GET", url)
h.putheader("Host", host)
if self.compressed:
h.putheader("Content-Encoding", "gzip")
if self.name:
h.putheader("X-Sumo-Name", self.name)
h.endheaders()
h.getreply() #can't do anything with the result
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
LOGGING = {
'version': 1,
'handlers': {
'sumo':{
'level': "DEBUG",
'class': '__main__.SumoHTTPHandler',
'url': '/receiver/v1/.....', #Replace with your custom Sumo Hosted URL
}
},
'loggers': {
'sumologger': {
'handlers': ['sumo'],
'level': 'DEBUG'
}
}
}
@PaulNendick
Copy link

You just saved me having to write this myself - thanks 😀

@avelis
Copy link

avelis commented Aug 16, 2016

Thanks for also writing this. I eventually ended up using Python requests vs httplib. Still, this gist was vital to the foundation of what I ended up building as a solution. 👍

@palmerjoshua
Copy link

Does this handler make a new HTTP request for each log message? If so, how does that affect performance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment