Redirect Python 'print' output to Logger

前端 未结 7 1885
北荒
北荒 2020-12-02 17:31

I have a Python script that makes use of \'Print\' for printing to stdout. I\'ve recently added logging via Python Logger and would like to make it so these print statement

7条回答
  •  情话喂你
    2020-12-02 17:42

    You have two options:

    1. Open a logfile and replace sys.stdout with it, not a function:

      log = open("myprog.log", "a")
      sys.stdout = log
      
      >>> print("Hello")
      >>> # nothing is printed because it goes to the log file instead.
      
    2. Replace print with your log function:

      # If you're using python 2.x, uncomment the next line
      #from __future__ import print_function
      print = log.info
      
      >>> print("Hello!")
      >>> # nothing is printed because log.info is called instead of print
      

提交回复
热议问题