Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log error to file, and not fail on exception

I am downloading a file from the net, and it fails even though I am doing:

for p in query:

try:  except IOError as e:    print e; 

If there is an error, I want to log it, and then continue on with the next file.

In this loop, I am trying to download an image, if for some reason the filename was bad, or the website was down, etc., I want to continue with the next item in the for loop.

Is there a more generic error that won't fail and continue processing?

Also, how can I log errors to a file?

like image 778
Blankman Avatar asked Aug 01 '10 21:08

Blankman


People also ask

Does logging error raise exception Python?

It depends on the situation, but logging and then raising an exception is generally considered an antipattern. It's redundant and clutters logs. Unless you're expecting something to catch that exception and suppress the message, don't log. Pythonic is not really a look as it is the formatting of code.

How do I create an exception to a log file?

To log a handled exceptionCreate the method that will generate the exception information. Use a Try...Catch block to catch the exception. Put the code that could generate an exception in the Try block. Uncomment the Dim and MsgBox lines to cause a NullReferenceException exception.

How do I create an error log in Python?

Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug().

How do you log error messages in Java?

We can display the Java error messages using the logger. error("Error Message") method.


1 Answers

You could use the logging module:

import logging logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG,                      format='%(asctime)s %(levelname)s %(name)s %(message)s') logger=logging.getLogger(__name__)  try:     1/0 except ZeroDivisionError as err:     logger.error(err) 

Running the script writes in /tmp/myapp.log:

% cat /tmp/myapp.log  2010-08-01 17:50:45,960 ERROR __main__ integer division or modulo by zero 
like image 179
unutbu Avatar answered Sep 28 '22 19:09

unutbu