Python - logging with filters


Python tip:

You can use Filter from the logging module to add additional information to your log records.

For example, you can add the username of the system user who's running the program👇

import logging
import os


class UserRunningProgramFilter(logging.Filter):
    def filter(self, record):
        record.user = os.getenv("User")
        return True


if __name__ == "__main__":
    levels = (
        logging.DEBUG,
        logging.INFO,
        logging.WARNING,
        logging.ERROR,
        logging.CRITICAL,
    )
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)-15s %(name)-5s %(levelname)-8s Run by User: %(user)-20s %(message)s",
    )
    logger = logging.getLogger("mylogger")

    f = UserRunningProgramFilter()
    logger.addFilter(f)
    logger.debug("A debug message")

# => 2021-09-22 07:56:45,473 mylogger DEBUG    Run by User: johndoe                 A debug message