python - 尽管函数的其余部分运行正常,为什么我的 python 日志没有填充?

标签 python logging

我正在使用利用日志记录的 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/

相关文章:

python - tensorflow 中的 "stateful object"是什么?

java - log4j 不压缩日志文件

python 输入 : result depending on arguments

python - Pandas - 根据条件将值从一行复制到另一行

python - 在 Sphinx 中交叉引用 Python 对象有什么要求?

python-2.7 - Python Tornado 中的 AttributeError 配置日志到文件

c# - 在 nlog 中以编程方式创建数据库以启用 DatabaseTarget

python tkinter 绑定(bind) : How to prevent double events

c - 使用 syslog (linux) 在日志文件中写入错误类型

django - 如何让未捕获的异常出现在 Django 日志中