Home > Software engineering >  Add custom formatter tags in papertrail Logger in django
Add custom formatter tags in papertrail Logger in django

Time:05-17

settings Page:

"formatters": {
        "simple": {
            "format": "%(name)s %(asctime)s %(message)s",
            "datefmt": "%Y-%m-%dT%H:%M:%S",
        },
    },

If I write here code like this:

"formatters": {
            "simple": {
                "format": "%(name)s %(ip)s %(user)s %(client)s %(asctime)s %(message)s",
                "datefmt": "%Y-%m-%dT%H:%M:%S",
            },
        },

It is showing following Error:

--- Logging error ---
Traceback (most recent call last):
  File "C:\Program Files\Python10\lib\logging\__init__.py", line 440, in format
    return self._format(record)
  File "C:\Program Files\Python10\lib\logging\__init__.py", line 436, in _format
    return self._fmt % values
KeyError: 'ip'

CodePudding user response:

ip is not one of the available parameters: https://docs.python.org/3/library/logging.html#logrecord-attributes

CodePudding user response:

You can provide extra keys for your logger in views, like this:

def send_log(self, request, *args, **kwargs):
    extra = {
        "ip": visitor_ip_address(request),
        "username": request.user.username,
        "role": request.user.role,

    }

    logger.info('foo bar', extra=extra)
  • Related