как отобразить точный номер строки (где произошла ошибка) в библиотеке журналов

В следующем коде ошибка находится в строке 7. Однако журнал отображает ошибку в строке 10, где упоминается ведение журнала.

import logging
import urllib2
logging.basicConfig(filename='example.log',level=logging.DEBUG,format='%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s')
def main():
    try:
        urls = "http://www.simplyhired.com/a/job-detaw/jobkey-67b4efe169eee7b2cf2ed47d49b1845070ea37/rid-racliggzfyjgqwfzrlvnqyjtcserhrri/cjp-3/pub_id-1002"
        site = urllib2.urlopen(urls).read()
        mathfail = 1/0
    except Exception, e:
        logging.critical(str(e))

main()

В журнале отображается следующее:

CRITICAL   2016-04-08 15:28:47,063 testt:10 main HTTP Error 404: Not Found

Я хочу, чтобы он отображал номер строки, в которой произошла ошибка, а не номер строки, в которой упоминается ведение журнала. Он должен отображать строку 7, а не строку 10


person dsl1990    schedule 08.04.2016    source источник


Ответы (2)


Это дает мне ожидаемый результат:

import logging
import urllib2
logging.basicConfig(filename='example.log',level=logging.DEBUG,format='%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s')
def main():
    try:
        urls = "http://www.simplyhired.com/a/job-detaw/jobkey-67b4efe169eee7b2cf2ed47d49b1845070ea37/rid-racliggzfyjgqwfzrlvnqyjtcserhrri/cjp-3/pub_id-1002"
        site = urllib2.urlopen(urls).read()
        mathfail = 1/0
    except Exception, e:
        logging.exception(str(e))

main()

вывод в файле журнала:

ERROR      2016-04-08 16:18:35,430 testt:10 main HTTP Error 404: Not Found
Traceback (most recent call last):
  File "testt.py", line 7, in main
    site = urllib2.urlopen(urls).read()
  File "/home/deepu/anaconda/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/home/deepu/anaconda/lib/python2.7/urllib2.py", line 437, in open
    response = meth(req, response)
  File "/home/deepu/anaconda/lib/python2.7/urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "/home/deepu/anaconda/lib/python2.7/urllib2.py", line 475, in error
    return self._call_chain(*args)
  File "/home/deepu/anaconda/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/home/deepu/anaconda/lib/python2.7/urllib2.py", line 558, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 404: Not Found
person dsl1990    schedule 08.04.2016

Я думаю, вы ищете дорожку стека

import logging
import urllib2
import traceback
logging.basicConfig(filename='example.log',level=logging.DEBUG,format='%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s')
def main():
    try:
        urls = "http://www.simplyhired.com/a/job-detaw/jobkey-67b4efe169eee7b2cf2ed47d49b1845070ea37/rid-racliggzfyjgqwfzrlvnqyjtcserhrri/cjp-3/pub_id-1002"
        site = urllib2.urlopen(urls).read()
        mathfail = 1/0
    except Exception:
        logging.critical(traceback.format_exc())

main()
person galaxyan    schedule 08.04.2016
comment
Это не то, что я ищу. Это должен быть лог. - person dsl1990; 09.04.2016
comment
@dsl1990, вы можете изменить его на logging.critical(traceback.format_exc()) - person galaxyan; 09.04.2016