简体   繁体   中英

Loguru: extra variable that's not always set

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).

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")

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