我正在使用利用日志记录的 try- except 语句,但是,即使正在生成日志文件,也不会创建任何日志。
最初我的代码可以工作,但它的生产格式不正确:Try except 尝试运行脚本的语句,并在失败时将日志语句推送到日志。
我被告知“导入 -> 函数 -> 运行函数”+“函数应该有 try- except 日志记录,而不是相反”。
我已经修改了这个问题的代码来隔离问题:在此代码中,我们有一个打开 json.json 的脚本。打开 JSON 的脚本有效。日志记录是唯一的问题。
我哪里出错了?
重新排列代码时,脚本仍然运行,但不包括日志记录部分。
import logging
LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='C:\\Users\\MWSF\\Documents\\log_test.log',
level=logging.INFO,
format=LOG_FORMAT)
logger = logging.getLogger()
def get_filepath():
'''Find the file path, which is partly defined by the file name.'''
try:
return "C:\\Users\\MWSF\\Documents\\filename.json"
except Exception:
logger.error("Error occured while determining current JSON file path.")
else:
logger.info("Successfully determined current JSON file path.")
path = get_filepath()
预期结果:打开指定文件和名为 log_test.log
的日志的函数,其中包含以下信息:
INFO 2019-04-26 14:52:02,260 - 导入当前 JSON 文件。
实际结果:打开指定文件和名为 log_test.log
的日志的函数,其中包含以下信息:
最佳答案
将 return 放在“else”子句上,而不是放在“try”下。它导致函数退出而不是进行日志记录。
def get_filepath():
'''Find the file path, which is partly defined by the file name.'''
try:
#return "C:\\Users\\MWSF\\Documents\\filename.json"
path = "C:\\Users\\MWSF\\Documents\\filename.json"
except Exception:
logger.error("Error occured while determining current JSON file path.")
else:
logger.info("Successfully determined current JSON file path.")
return path
示例 log_test.log:
INFO 2019-04-29 12:58:53,329 - 成功确定当前 JSON 文件路径。
关于python - 尽管函数的其余部分运行正常,为什么我的 python 日志没有填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907246/