0

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?

4
  • 1
    I think you're looking for the logging module: realpython.com/python-logging Commented Dec 5, 2019 at 16:48
  • Are the errors something you are throwing / checking yourself or do you want to generally store to disk whatever gets written to STDERR by a certain script? Commented Dec 5, 2019 at 16:53
  • @norok2 - not too sure what STDERR is Commented Dec 5, 2019 at 16:59
  • en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr) Commented Dec 5, 2019 at 17:03

2 Answers 2

1

Yes you can do that using python logging

Sign up to request clarification or add additional context in comments.

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.