Last active
October 11, 2023 11:15
-
-
Save mebaysan/f15b040b87f7658cf70f90e8827a5de9 to your computer and use it in GitHub Desktop.
Django custom logging in JSON
This file contains hidden or 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
# helpers.logging.formatter | |
import logging | |
import json | |
class JSONFormatter(logging.Formatter): | |
def format(self, record): | |
log_data = { | |
"timestamp": self.formatTime(record), | |
"level": record.levelname, | |
"message": record.getMessage(), | |
"logger_name": record.name, | |
"module": record.module, | |
"function": record.funcName, | |
"line_number": record.lineno, | |
} | |
return json.dumps(log_data) | |
# settings.py | |
# LOGGING | |
if DEBUG is False: | |
LOGGING = { | |
"version": 1, | |
"disable_existing_loggers": False, | |
"formatters": { | |
"verbose": {"format": "%(levelname)s %(asctime)s %(name)s %(message)s"}, | |
"json": { | |
"()": "helpers.logging.formatter.JSONFormatter", | |
}, | |
}, | |
"handlers": { | |
"console": {"class": "logging.StreamHandler", "formatter": "verbose"}, | |
"file": { | |
"level": "INFO", | |
"class": "logging.FileHandler", | |
"filename": "/var/log/my_app/my_app.log", | |
"formatter": "json", | |
}, | |
}, | |
"loggers": { | |
"": { | |
"handlers": ["console", "file"], | |
"level": "INFO", | |
"propagate": True, | |
}, | |
"django": { | |
"handlers": ["console"], | |
"level": "DEBUG", | |
"propagate": True, | |
}, | |
"my_app": { | |
"handlers": ["console"], | |
"level": "ERROR", | |
"propagate": True, | |
}, | |
}, | |
} | |
else: | |
LOGGING = { | |
"version": 1, | |
"disable_existing_loggers": False, | |
"formatters": { | |
"verbose": {"format": "%(levelname)s %(asctime)s %(name)s %(message)s"}, | |
"json": { | |
"()": "helpers.logging.formatter.JSONFormatter", | |
}, | |
}, | |
"handlers": { | |
"console": {"class": "logging.StreamHandler", "formatter": "verbose"}, | |
"file": { | |
"level": "INFO", | |
"class": "logging.FileHandler", | |
"filename": "my_app.log", | |
"formatter": "json", | |
}, | |
}, | |
"loggers": { | |
"": { | |
"handlers": ["file"], | |
"level": "INFO", | |
"propagate": True, | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment