2017-08-18 37 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 
>>> 
相关问题