简体   繁体   中英

Executing and automatically storing all error messages into file

Is there an easy way to execute a python script and then have all error messages save to a type of log file (csv, txt, anything).

class MyClass():
    def __init__(self, something):
        self.something = something

    def my_function(self):
        # code here

Or is the only way to add try and except statements everywhere and write the error messages to a file?

是的,您可以使用 python 日志记录来做到这一点

Here's a specific example, using the info from https://realpython.com/python-logging/ with your code:

import logging

logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged to a file')

class MyClass():
     def __init__(self, something):
          self.something = something

     def my_function(self):
          logging.warning('my_function entered...')

After you instantiate your class and call my_function, you should get logging output in your log file (here app.log):

root - WARNING - This will get logged to a file
root - WARNING - my_function entered...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM