简体   繁体   中英

Pinpoint Logging Messages for Django Error Report

I have been trying to distinguish between loggings from the production server, development server, or local server. I have python-telegram-handler 2.2, which sends logs to a Telegram group chat via a bot.

The code is the same in all of those servers as localhost code gets merged to the development branch (which is responsible for the development server), and when the development branch is ready, it gets merged to the master branch, which is responsible for the production server. Is there a way to tweak the settings so that the telegram log tells us which server has the error? Thanks a lot!

Below is the LOGGING part of base.py in the settings directory.

settings/base.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },
    },
    'formatters': {
        'simple_trace': {
            'format': '%(asctime)s,%(msecs)d %(levelname)-8s %(message)s',
        }
    },
    'handlers': {
        'telegram': {
            'class': 'telegram_handler.TelegramHandler',
            'token': '1489551033:AAHbIvspcVR5zcslrbrJ9qNK2yZ1at0yIMA',
            'chat_id': '-429967971',
            'formatter': 'simple_trace'
        }
    },
    'loggers': {
        '': {
            'handlers': ['telegram'],
            'level': 'INFO',
            'propagate': True,
        },
    },
}

And I also have a middleware that sends logs of the request body whenever the responses are 400 or 500.

api/custommiddleware.py

import json
import logging
import base64
import http

from datetime import datetime


class ErrorCatchMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        try:
            jsonRequest = json.loads(request.body.decode('utf-8'))
        except Exception as e:
            jsonRequest = {}

        response = self.get_response(request)

        if (response.status_code == 400 or response.status_code == 500):

            logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s %(message)s',
            datefmt = '%Y-%m-%d:%H:%M:%S',
            level = logging.INFO
            )

            logger = logging.getLogger(__name__)
            logger.info({'request': jsonRequest})
            response_content = response.content
            logger.warning(response_content.decode('utf-8'))
            print(jsonRequest)
            print(response_content.decode('utf-8'))
            return response
        else:
            return response

The logs I get look like the following. 在此处输入图像描述

As you can see, the file does not say whether this error occurred in the production server, development server, or localhost. I must figure out a way to distinguish in which server such errors occur.

You may override formatter in according settings module, like this:

settings/production.py

LOGGING['formatters']['simple_trace']['format'] = 'Production: %s'%LOGGING['formatters']['simple_trace']['format']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM