How to log error to file, and not fail on exception

后端 未结 4 2021
忘了有多久
忘了有多久 2021-01-31 16:55

I am downloading a file from the net, and it fails even though I am doing:

for p in query:

try:

except IOError as e:
   print e;

If th

4条回答
  •  半阙折子戏
    2021-01-31 17:43

    You could use the logging module:

    import logging
    logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG, 
                        format='%(asctime)s %(levelname)s %(name)s %(message)s')
    logger=logging.getLogger(__name__)
    
    try:
        1/0
    except ZeroDivisionError as err:
        logger.error(err)
    

    Running the script writes in /tmp/myapp.log:

    % cat /tmp/myapp.log 
    2010-08-01 17:50:45,960 ERROR __main__ integer division or modulo by zero
    

提交回复
热议问题