2016-04-08 22 views
2

在以下代碼中,錯誤位於第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行

回答

0

這給了我所期望的輸出:

在日誌文件中
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 
0

我認爲你正在尋找堆棧跟蹤

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() 
+0

這不是我要找的。它必須是日誌。 – dsl1990

+0

@ dsl1990您可以將其更改爲logging.critical(traceback.format_exc()) – galaxyan

相關問題