Python: How to write error in the console in txt file?

Refresh

6 days ago

Views

35 time

0

I have a python script which every 10 minutes sends me an email with everything written in the console. I am running this with the crontab in my ubuntu 18.04 vps. Sometimes it doesn't send the mail so I assume that when an error happens execution stops but how can I get the errors to be written in a txt file so I can analyze the error ?

2 answers

0

Logging Module

To demonstrate the approach with the logging module, this would be the general approach

import logging

# Create a logging instance
logger = logging.getLogger('my_application')
logger.setLevel(logging.INFO) # you can set this to be DEBUG, INFO, ERROR

# Assign a file-handler to that instance
fh = logging.FileHandler("file_dir.txt")
fh.setLevel(logging.INFO) # again, you can set this differently

# Format your logs (optional)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter) # This will set the format to the file handler

# Add the handler to your logging instance
logger.addHandler(fh)

try:
    raise ValueError("Some error occurred")
except ValueError as e:
    logger.exception(e) # Will send the errors to the file

And if I cat file_dir.txt

2019-03-14 14:52:50,676 - my_application - ERROR - Some error occurred
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: Some error occurred

Print to File

As I pointed out in the comments, you could accomplish this with print as well (I'm not sure you will be applauded for it)

# Set your stdout pointer to a file handler
with open('my_errors.txt', 'a') as fh:
    try:
        raise ValueError("Some error occurred")
    except ValueError as e:
        print(e, file=fh)

cat my_errors.txt

Some error occurred

Note that logging.exception includes the traceback in this case, which is one of the many huge benefits of that module

0

Вы можете использовать loggingмодуль как предложено в комментариях (возможно , превосходящих , но вне сферы моих знаний), или поймать ошибки с tryи , exceptкак:

try:
    pass
    #run the code you currently have
except Exception as e: # catch ALLLLLL errors!!!
    print(e) # or more likely you'd want something like "email_to_me(e)"

Хотя это , как правило , с неодобрением , чтобы поймать все исключения, потому что тогда должны программа потерпеть неудачу по любой причине он получит сожрал в exceptпункте поэтому лучше подход , чтобы выяснить , какие конкретно ошибки вы столкнулись , как IndexErrorи то просто поймать эту конкретную ошибку лайк:

try:
    pass
    #run the code you currently have
except IndexError as e: # catch only indexing errors!!!
    print(e) # or more likely you'd want something like "email_to_me(e)"