2017-08-18 58 views
1

我有一個由我的應用程序執行的python腳本。該腳本使用Python中內置的logging API。我遇到的問題是所有日誌消息中的文件名都寫爲<string>。當我在代碼片段中運行相同的代碼時,它運行良好。 下面是我用它來配置記錄代碼:Python日誌記錄API打印文件名爲'<string>'

import logging 
import os 
import sys 
from logging import FileHandler, StreamHandler 

logger = logging.getLogger('update_menu') 
logger.setLevel(logging.DEBUG) 

# create handlers and set level to debug 
fileHandler = FileHandler(filename='/home/fguimaraes/work/update_menu.log') 
fileHandler.setLevel(logging.DEBUG) 

consoleHandler = StreamHandler(stream=sys.stdout) 
consoleHandler.setLevel(logging.DEBUG) 

# create formatter 
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s;File:%(filename)s;Function:%(funcName)s;Line:%(lineno)d') 

# add formatter to log 
fileHandler.setFormatter(formatter) 
consoleHandler.setFormatter(formatter) 

# add log to logger 
logger.addHandler(fileHandler) 
logger.addHandler(consoleHandler) 
+0

你可以顯示記錄器調用嗎? – MrName

回答

1

這可能是因爲你的腳本被讀入內存,並作爲一個字符串使用例如執行exec,這意味着腳本沒有文件名。例如:

$ cat /tmp/test.py 
import logging 

logging.basicConfig(level=logging.DEBUG, format='%(filename)s: %(message)s') 
logging.debug('This is a test') 
[email protected]:~/projects/orbitilweb$ python /tmp/test.py 
test.py: This is a test 
$ python 
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> with open('/tmp/test.py') as f: data = f.read() 
... 
>>> exec data 
<string>: This is a test 
>>> 
相關問題