"None" 在 python 日志文件中

"None" in python log-file

我在 python 中使用 logging 模块。当我在命令行上使用错误的参数调用脚本时,日志文件在某个时候包含单个单词 "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())

在我 运行 脚本(参数错误)之后,日志文件如下所示:

Could not open viva file with arg1 arg2.

None
Could not open blank file with arg1 arg2.

None

有什么想法吗?

您正在使用 logging.exception() 没有异常:

logging.exception("Could not open viva file with %s %s.\n" % (s1, m1))

由于没有异常记录,所以添加了None。在此处使用 logging.error() 仅记录一条消息:

logging.error("Could not open viva file with %s %s", s1, m1)

您不需要插入字符串元素,logging 会在需要时为您完成。我还删除了 \n 换行符,这也是为您添加的。

在异常处理程序中 时,您在其他地方手动包含异常:

logging.exception("Could not open file:\n " + traceback.format_exc())

您不需要手动附加回溯,logging.exception() 会为您处理并包括回溯,格式正确。

只记录消息,仅此而已:

logging.exception("Could not open file")

来自logging.exception() documentation:

Exception info is always added to the logging message. This method should only be called from an exception handler.

大胆强调我的;您在异常处理程序之外使用了它,因此没有异常可用于记录。

它通过为您设置 exc_info keyword argument 来做到这一点:

  • exc_info* which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.