Skip to content

Instantly share code, notes, and snippets.

@benauthor
Created October 21, 2016 14:40
Show Gist options
  • Save benauthor/920777f0d2f3e2915bfbed0404339ede to your computer and use it in GitHub Desktop.
Save benauthor/920777f0d2f3e2915bfbed0404339ede to your computer and use it in GitHub Desktop.
statsd logger sketch
import logging
import os
from logging.handlers import DatagramHandler
HOST_KEY = "STATSD_HOST"
PORT_KEY = "STATSD_PORT"
logger = logging.getLogger("test")
class StatsdHandler(DatagramHandler):
def _metric(self, record):
return "errors.{}.{}.{}_{}".format(
record.name, record.levelname, record.funcName, record.lineno
)
def _prepare_increment(self, metric):
return "{}:1|c".format(metric)
def emit(self, record):
"""
Increment a statsd counter for the error that occurred.
"""
try:
s = self._prepare_increment(self._metric(record))
self.send(s)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
logger.addHandler(StatsdHandler(os.environ[HOST_KEY], int(os.environ[PORT_KEY])))
def main():
try:
raise Exception("wow")
except Exception as e:
logger.error(e)
if __name__ == "__main__":
main()
@otoolep
Copy link

otoolep commented Oct 25, 2016

Adding lineno to the stat name will increase the cardinality a lot -- any edit to the source file might result in a new error. Therefore I wouldn't include lineno.

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