Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
logging.exception
#1
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!
Reply
#2
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...).
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  i am getting error while writing code for exception logging rkgupta51179 1 1,839 Nov-03-2019, 05:12 AM
Last Post: buran
  During handling of the above exception, another exception occurred Skaperen 7 26,866 Dec-21-2018, 10:58 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020