Redirect Python 'print' output to Logger

前端 未结 7 1881
北荒
北荒 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:56

    A much simpler option,

    import logging, sys
    logging.basicConfig(filename='path/to/logfile', level=logging.DEBUG)
    logger = logging.getLogger()
    sys.stderr.write = logger.error
    sys.stdout.write = logger.info
    

提交回复
热议问题