jwi*_*jwi 4 python logging python-2.7
我logging在python中使用该模块.当我在命令行上使用错误的参数调用脚本时,日志文件在某些时候包含单词"None",我不知道它来自何处.
这是我的代码切割,我在那里执行logging.exception:
# Show script where to find blank- and viva-data / set argv
vz = glob.glob("/home/jw/cmp_blank_viva/*csv")
skript, s1, m1 = argv
# Define script-functions and logging-config
logging.basicConfig(level=logging.ERROR, filename='cmp_blank_viva.log', format='%(asctime)s:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
def open_data(vz, s1, m1):
try:
checker = []
for i in vz:
if "drhot_viva_check_%s" % m1 in i:
blank_data = csv.reader(open(i, 'r'))
checker.append(1)
else:
pass
if 1 not in checker:
logging.exception("Could not open viva file with %s %s.\n" % (s1, m1))
checker = []
for i in vz:
if "hoteldaten_%s_%s" % (m1, s1) in i:
viva_data = csv.DictReader(open(i, 'r'), delimiter = ';')
checker.append(1)
else:
pass
if 1 not in checker:
logging.exception("Could not open blank file with %s %s.\n" % (s1, m1))
return blank_data, viva_data
except IOError:
logging.exception("Could not open file:\n " + traceback.format_exc())
except IndexError:
logging.exception("Could not open file:\n " + traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)
运行脚本(使用错误的参数)后,日志文件如下所示:
Could not open viva file with arg1 arg2.
None
Could not open blank file with arg1 arg2.
None
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
logging.exception() 当没有例外时你正在使用:
logging.exception("Could not open viva file with %s %s.\n" % (s1, m1))
Run Code Online (Sandbox Code Playgroud)
由于没有日志异常,None因此添加了.使用logging.error()此处仅记录消息:
logging.error("Could not open viva file with %s %s", s1, m1)
Run Code Online (Sandbox Code Playgroud)
您不需要插入字符串元素,logging在需要时为您执行此操作.我也删除了\n换行符,也为你添加了换行符.
其他地方要手动包括异常,当你是在一个异常处理程序:
logging.exception("Could not open file:\n " + traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)
您无需手动附加回溯,logging.exception()为您处理此回溯并包含正确格式化的回溯.
只需记录消息,仅此而已:
logging.exception("Could not open file")
Run Code Online (Sandbox Code Playgroud)
始终将异常信息添加到日志记录消息中.只应从异常处理程序调用此方法.
大胆强调我的; 您在异常处理程序之外使用它,因此没有可用的异常记录.
它通过为您设置exc_info关键字参数来实现:
- exc_info*,如果它不计算为false,则会将异常信息添加到日志消息中.如果提供了异常元组(以返回的格式
sys.exc_info()),则使用它; 否则,sys.exc_info()调用以获取异常信息.