Reputation: 23
I have this method in my code but I want to pass the error to my log and to erase the print(e).
def get_used(self, obj):
try:
return '<a href="%(url)s">%(name)s</a>' % {'url': reverse('org', kwargs={'organization': obj.organization.slug}), 'name': obj.organization.name}
except Exception as e:
print(e)
return ''
I found this documentation about logging calls https://docs.djangoproject.com/en/2.1/topics/logging/ but really I'm not sure is the implementation is in this way.
def get_used(self, obj):
try:
return '<a href="%(url)s">%(name)s</a>' % {'url': reverse('org', kwargs={'organization': obj.organization.slug}), 'name': obj.organization.name}
except Exception as e:
logger = logging.getLogger(__name__)
logger.exception(e)
return ''
or another idea that is in my mind it's create logger = logging.getLogger(__name__) as global variable.
I'm some confused how to build the loggers and I need help to code this.
Thanks!!
Upvotes: 1
Views: 1221
Reputation: 398
This line from your code gives you a handle to the logger:
logger = logging.getLogger(__name__)
Now you can log messages acoording to severity with different functions, e.g.:
logger.debug("Very detailed information")
logger.info("Rather important information")
logger.warning("A warning")
Whether this gets printed or not depends on your loglevel and what handlers you have. Have a look in the official tutorial
In your case, this should probably work:
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(e)
return ''
Upvotes: 0