Python Forum
logging.exception - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: logging.exception (/thread-2171.html)



logging.exception - tkj80 - Feb-24-2017

Hi,

I have the following code to log the completion status of my script:

import logging

try:
    logging.basicConfig(filename="C:/Users/AppData/Local/Programs/Python/Python35-32/myScript/log.txt", format='%(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)

    logging.info("Process initiated.")

    ##code to do things
    logging.info("Process complete. %s %s %s", "\n", "-"*100, "\n")

except Exception, e:
        logging.exception(e, exc_info=True)
I wanted to log error if it is raised. My question is, how do I output it to the same log.txt filed that I have from logging.basicConfig?

Thank you!


RE: logging.exception - Ofnuts - Feb-24-2017

It you get an exception, it is possibly/likely because you can't write to that file... so the right thing to do would be to report the problem elsewhere (terminal, etc...).


RE: logging.exception - snippsat - Feb-25-2017

The point of logging Ofnuts is to not display the error anywhere,other than in the log file.
There is method for exception logging.exception()
Good logging practice in Python

Try without path @tkj80 ,my.log should be in same folder as you run code.
And move line 4 out of try/except .
Eg:
import logging

logging.basicConfig(filename='my.log', filemode='w', level=logging.DEBUG)
try:
    n = 1/0
except Exception as error:
    logging.exception('msg')
my.log:
Output:
ERROR:root:msg Traceback (most recent call last):   File "log1.py", line 5, in <module>     n = 1/0 ZeroDivisionError: division by zero