I have a Django application where I want to update the standard logging to structured JSON format. I can get this working fine by adding my logging config and some business logic into settings.py
, but I want to keep the business logic separate.
Is there any Django built-in file (akin to the settings.py
) that allows you to add some logic that Django will pick up, or can I load a file with this additional logic from settings.py
?
Here is what I have:
settings.py
LOGGING = {
'version': 1,
'formatters': {
'structured': {
'format':'%(json_structured)s',
'datefmt': "%H:%M:%S"
}
},
'handlers': {
...
},
'loggers': {
...
}
}
# Below is what I want to move from settings.py
class JsonDateTimeEncoder(JsonStringFallbackEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%S%z')
else:
return super().default(obj)
std_record_factory = logging.getLogRecordFactory()
def structured_log_record_factory(*args, **kwargs) -> logging.LogRecord:
record = std_record_factory(*args, **kwargs)
record.json_structured = json.dumps(
{
'level': record.levelname,
...
},
cls=JsonDateTimeEncoder,
)
return record
logging.setLogRecordFactory(structured_log_record_factory)
I know I can load the LOGGING
config from file, but not sure how best to achieve this with the additional logic.