Redirect Python 'print' output to Logger

前端 未结 7 1879
北荒
北荒 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:36

    Of course, you can both print to the standard output and append to a log file, like this:

    # Uncomment the line below for python 2.x
    #from __future__ import print_function
    
    import logging
    
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logger = logging.getLogger()
    logger.addHandler(logging.FileHandler('test.log', 'a'))
    print = logger.info
    
    print('yo!')
    

提交回复
热议问题