← Back to TIL

Python HTTP Logger

I recently had the a requirement of sending python logs to another service over HTTP, this is definitely far from best practice but in this case the logs are minimal and predictable so it didn't need a more robust solution

import requests
import logging

class HttpLogHandler(logging.Handler):
    def emit(self, record):
        log_entry = self.format(record)
        return requests.post(os.getenv("LOGS_URL"), json=[log_entry])


log_handler = HttpLogHandler()
logger = logging.getLogger("<logger name>")
logger.setLevel("INFO")
logger.addHandler(log_handler)