How to add custom parameter into Python logging formatter?

前端 未结 2 1629
梦如初夏
梦如初夏 2021-02-05 17:43

I\'m using standard Python logging module with Flask framework. I want to write logs to file with the all records of users actions with custom parameter - %(username)s to loggin

2条回答
  •  自闭症患者
    2021-02-05 18:09

    Isn't the easier way to just subclass a Formatter and add your custom attribute to the LogRecord just before formatting?

    For instance I use this code:

    # A custom formatter to add the timestamp from the simulated clock.
    class _Formatter(logging.Formatter):
      def format(self, record):
        record.simulated_clock = clock.get_time()
        return super(_Formatter, self).format(record)
    
    # Creates a logger object.
    def _create_logger():
      logger = logging.getLogger("simulation")
      logger.setLevel(kLevel)
      ch = logging.StreamHandler()
      ch.setLevel(kLevel)
      formatter = _Formatter("%(simulated_clock)s - %(levelname)s - %(message)s")
      ch.setFormatter(formatter)
      logger.addHandler(ch)
    
      return logger
    

    I don't consider myself a Python expert, but it works for me....

提交回复
热议问题