pythonloggingloguru

Loguru: how to obfuscate data in logs


Using the python logger I can obfuscate data like this:

import logging
import re
import sys


class MySensitiveFormatter(logging.Formatter):
    """Formatter that removes sensitive information."""

    @staticmethod
    def _filter(s):
        """Remove credentials."""
        result = re.sub(r"pass: .*", "pass: xxx", s)
        return result

    def format(self, record):
        """Obfuscate sensitive information."""
        original = logging.Formatter.format(self, record)
        return self._filter(original)


stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setFormatter(MySensitiveFormatter())
logger = logging.getLogger("demo")
logger.setLevel("INFO")
logger.addHandler(stream_handler)

logger.info("This is a demo and here is the pass: secret")

prints => This is a demo and here is the pass: xxx

In loguru I cannot add a formatter/handler and filter removes the entire record (which is not what I want). How can I achieve this using loguru?


Solution

  • This is the correct way provided by the loguru team:

    def obfuscate_message(message: str):
        """Obfuscate sensitive information."""
        result = re.sub(r"pass: .*", "pass: xxx", s)
        return result
    
    def formatter(record):
        record["extra"]["obfuscated_message"] = obfuscate_message(record["message"])
        return "[{level}] {extra[obfuscated_message]}\n{exception}"
    
    logger.add(sys.stderr, format=formatter)
    

    See loguru issue for details.