try:
#do something that raises an exception...
except:
logging.error('Error Message')
I want more than just "Error Message" to show in the logs. I want to see the traceback, or at least what the exception was, in the logs as well. How do I do that?
Thanks!
logging.exception(msg[, *args])
Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This function should only be called from an exception handler.
http://docs.python.org/library/logging.html#logging.exception
This is what I use to log the entire stack trace:
import traceback
try:
# your code
except:
stacktrace = traceback.format_exc()
logging.error("%s", stacktrace)
I think this should help you
import logging
try:
#exception code
except Exception as e:
logging.error(e)
You can set the logging details to Debug,Info,Warning,Error or Critical and set in your application. Debug would give you a lot of details.
import logging
logging.getLogger().setLevel(logging.DEBUG)
And you can get the logs of the particular filter in your appengine web console under /logs.
Related
Let's say that I want to connect to database but getting an error on connect. In most of examples what I found people catch basic Error exception. But it also will catch any other mistake. So, the question is, what should I do to raise different user defined exceptions? In other words, how to throw user defined exception instead of predefined exception?
Like this:
class MySpecificException(Exception):
print('Handle exception here:')
try:
1/0
except ZeroDivisionError as e:
print('error text')
raise MySpecificException('SpecificException')
I'm using a library that is logging an error. But I'd like it to raise an exception instead.
Is there quick way to have an exception raised instead of just an error being logged?
The library I'm using is cssutils, but for simplicity, suppose my code looks like:
from foo import do_something
do_something(x)
and suppose do_something will log an error if x was unacceptable input. Is there some quick hack that would cause an exception to be raised if do_something logs an error? Or is the only way to edit foo's source?
It's not clear if you want to still log the error, but you can try something like:
if error_is_true:
raise Exception("error message...")
With log:
try:
my_function()
except Exception:
logger.exception("error msg...")
When I try to raise a HTTP exception status code 400 it only prints the json error message on the browser but does not state HTTP/1.1 400 BAD REQUEST in the console like it is supposed to. The exception raising works for all other parts of my program but it doesn't work when I do it in a try-catch for a runtime error.
My exception handler is exactly this:
http://flask.pocoo.org/docs/0.11/patterns/apierrors/
my try-catch:
try:
// run some program
catch RuntimeError as e:
raise InvalidUsage(e.message, status_code=400)
You should use the abort function of flask, something like:
from flask import abort
#app.route("/some_route")
def some_route():
try:
# do something
except SomeException:
abort(400, "Some message")
I have a java web service and python client using suds. My server raises custom exceptions which I would like to handle in the python script. Is it possible to catch them or it always will be caught as suds.WebFault exception?
suds.WebFault has fault field that has information about fault.
except suds.WebFault, e:
print e.fault.faultstring
print e.document
You can have your program to analyze server custom exception from WebFault and create new exception class(es) for every specific server exception then catch suds.WebFault exception, read server exception details and raise your custom exception.
class MyException(suds.WebFault):
pass
def convertServerException(e):
if e.fault.faultstring == 'exception1':
return MyException()
#...add more exception handling cases here
#...
try:
#...make a WebService call
except suds.WebFault, e:
print e
print e.fault
raise convertServerException(e)
It is running under DEBUG = True mode. Sometimes it can throw out an error message with traceback information when encounter an error but sometimes it just display the following lines:
Unhandled Exception
An unhandled exception was thrown by the application.
I have to switch to development server to see detail message.
How can I make it always display traceback message when an error is encountered?
Just connect to the got_request_exception signal and log the exception:
from django.core.signals import got_request_exception
import logging
def log(*args, **kwargs):
logging.exception('error')
got_request_exception.connect(log)
This will log the whole trace. In the dev server, it logs in the console.
Maybe you can use this snippet, this will log exceptions in apache's log:
utils.py:
def log_traceback(exception, args):
import sys, traceback, logging
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
logging.debug(exception)
logging.debug(args)
for tb in traceback.format_exception(exceptionType, exceptionValue, exceptionTraceback):
logging.debug(tb)
site_logging.py:
import logging
import sys
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
Put it in your settings.py :
import site_logging
And in your code:
from where.is.your.utils import log_traceback
try:
`do something`
except Exception, args:
log_traceback(Exception, args)
Are you using Apache?
Just out of interest is this your Production or Dev environment where you want to see the traceback?
From the DJango Book on security - Exposed error messages
Users deploying under Apache and mod_python should also make sure they have PythonDebug Off in their Apache conf files; this will ensure that any errors that occur before Django’s had a chance to load won’t be displayed publicly.
I assume you want PythonDebug On, this is recommended for Development only.
That's what DEBUG=True is for: to show the full traceback. The idea is that regular users do not want (nor do you want them to) see anything other than a simple error message.