loguru icon indicating copy to clipboard operation
loguru copied to clipboard

Custom Serialize function and contextual data

Open Lukehi opened this issue 2 years ago • 1 comments

I am struggling to understand how to create a custom serialize function for a custom format and still include contextual data whilst logging.

The following will produce a log entry with the format I would like:

import sys
import json
from loguru import logger
import os
from datetime import datetime


def serialize(record):
    subset = {
        "timestamp": datetime.utcnow().isoformat(),
        "src_name": os.environ.get('SOURCE_NAME', ''),
        "workload_name": os.environ.get('WORKLOAD_NAME', ''),
        "hostname":  os.environ.get('HOSTNAME', ''),
        "automaton_profile": os.environ.get('AUTOMATON_PROFILE', ''),
        "automaton_name": os.environ.get('AUTOMATON_NAME', ''),
        "message": record["message"]
    }
    return json.dumps(subset)


def patching(record):
    record["extra"]["serialized"] = serialize(record)


logger.remove(0)

logger = logger.patch(patching)
logger.add(sys.stderr, format="{extra[serialized]}")
logger.info('test')

However, now say I would like to add a dictionary {'a': 1, 'b':2} to the log output. I can't find a way to do this.

Any help would be appreciated.

Luke

Lukehi avatar Nov 30 '23 11:11 Lukehi

Hi @Lukehi.

When you say the following:

I would like to add a dictionary {'a': 1, 'b':2} to the log output

What does that mean exactly? How would you like to add them? How should they appear in the serialized format you crafted?

Maybe you could use logger.bind() and extend your format with the populated extra dict:

import sys
import json
from loguru import logger
import os
from datetime import datetime


def serialize(record):
    subset = {
        "timestamp": datetime.utcnow().isoformat(),
        "src_name": os.environ.get('SOURCE_NAME', ''),
        "workload_name": os.environ.get('WORKLOAD_NAME', ''),
        "hostname":  os.environ.get('HOSTNAME', ''),
        "automaton_profile": os.environ.get('AUTOMATON_PROFILE', ''),
        "automaton_name": os.environ.get('AUTOMATON_NAME', ''),
        "message": record["message"],
        "data": record["extra"],
    }
    return json.dumps(subset)


def patching(record):
    record["extra"]["serialized"] = serialize(record)


logger.remove(0)

logger = logger.patch(patching)
logger.add(sys.stderr, format="{extra[serialized]}")
logger.info('test')
logger.bind(a=1, b=2).info("With contextual data")

Delgan avatar Dec 02 '23 09:12 Delgan