3

I would like to add an extra variable to my logs, but only if this variable exists / is set.

Here's the solution I came up with:

import sys
from loguru import logger

def formatter(record):
    if "remote_ip" in record.get("extra", []):
        return "{time} | {level} | {extra[remote_ip]} | {message}\n"
    else:
        return "{time} | {level} | unset | {message}\n"

logger.remove(0)
logger.add(sys.stderr, format=formatter)

logger.bind(remote_ip="192.168.1.1").info("Request from client1")
logger.info("Internal message without remote_ip")
logger.bind(remote_ip="192.168.1.2").info("Request from client2")

Is this the right way to do this, or is there a better one?

One thing I don't like about this solution is that I can't easily move the logging format out of the code and into a config file.

I would prefer something like {extra.get(remote_ip, 'unset')} but this doesn't seem possible (or at least I haven't found a way to do it yet).

rmweiss
  • 716
  • 1
  • 6
  • 16

1 Answers1

1

I came up with a (probably?) better solution. Just create a new logger instance with a default value for "remote_ip" already set:

import sys
from loguru import logger

logger.remove(0)
logger.add(sys.stderr, format="{time} | {level} | {extra[remote_ip]} | {message}")

mylogger = logger.bind(remote_ip="unset")

mylogger.bind(remote_ip="192.168.1.1").info("Request from client1")
mylogger.info("Internal message without remote_ip")
mylogger.bind(remote_ip="192.168.1.2").info("Request from client2")
rmweiss
  • 716
  • 1
  • 6
  • 16