Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JSON logs using Python `logging` library
from datetime import datetime
from pathlib import Path
import json_log_formatter
import logging
import os
class CustomJSONFormatter(json_log_formatter.JSONFormatter):
def json_record(self, message, extra, record):
if extra:
data = extra
if message:
data['message'] = message
else:
# Also support logger.info({'foo': 'bar'})
data = eval(message)
data['time'] = str(datetime.utcnow())
if record.exc_info:
data['exc_info'] = self.formatException(record.exc_info)
return data
def to_json(self, record):
return self.json_lib.dumps(record, ensure_ascii=False)
def create_logger(dirpath):
formatter = CustomJSONFormatter()
fp = Path(dirpath) / 'json_log_formatter.json'
if os.path.exists(fp):
os.remove(fp)
json_handler = logging.FileHandler(filename=fp, encoding='utf-8')
json_handler.setFormatter(formatter)
logger = logging.getLogger('logtests')
logger.addHandler(json_handler)
logger.setLevel(logging.INFO)
return fp
def use_logger():
logger = logging.getLogger('logtests')
logger.info({'one': "This is a message", "2": "произошла ошибка", "another": "ಠ_ಠ"})
logger.info("this is the message", extra={'yes': 'no'})
def main():
use_logger()
fp = create_logger(Path("logs"))
use_logger()
use_logger()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.