【问题标题】:Python Log File is not created unless basicConfig is called on top before any functions除非在任何函数之前调用 basicConfig,否则不会创建 Python 日志文件
【发布时间】:2020-10-27 01:41:29
【问题描述】:

我有一个处理 csv 并将它们加载到数据库的脚本。我的实习生导师希望我们使用日志文件来捕获正在发生的事情,并且他希望它具有灵活性,以便人们可以使用 config.ini 文件来编辑他们想要创建日志文件的位置。结果我就是这样做的,使用一个配置文件,该文件在一个字典中使用键值对,我可以从中提取日志文件的路径。这些是我的代码中创建和使用日志文件的例外情况:

dirconfig_file = r"C:\Users\sys_nsgprobeingestio\Documents\dozie\odfs\venv\odfs_tester_history_dirs.ini"
start_time = datetime.now()

def process_dirconfig_file(config_file_from_sysarg):
    try:
        if Path.is_file(dirconfig_file_Pobj):
            parseddict = {}
            configsects_set = set()
            for sect in config.sections():
                configsects_set.add(sect)
                for k, v in config.items(sect):
                    # print('{} = {}'.format(k, v))
                    parseddict[k] = v
            print(parseddict)
            try:
                if ("log_dir" not in parseddict or parseddict["log_dir"] == "" or "log_dir" not in configsects_set):
                    raise Exception(f"Error: Your config file is missing 'logfile path' or properly formatted [log_file] section for this script to run. Please edit config file to include logfile path to capture errors")
    except Exception as e:
        #raise Exception(e)
        logging.exception(e)
        print(e)

parse_dict = process_dirconfig_file(dirconfig_file)
logfilepath = parse_dict["log_dir"]
log_file_name = start_time.strftime(logfilepath)
print(log_file_name)
logging.basicConfig(
    filename=log_file_name,
    level=logging.DEBUG,
    format='[Probe Data Quality] %(asctime)s - %(name)s %(levelname)-7.7s %(message)s'
    # can you explain this Tenzin?
)

if __name__ == '__main__':
    
    try:
        startTime = datetime.now()
        db_instance = dbhandler(parse_dict["db_string"])
        odfs_tabletest_dict = db_instance['odfs_tester_history_files']
        odf_history_from_csv_to_dbtable(db_instance)
        #print("test exception")
        print(datetime.now() - startTime)
    except Exception  as e:
        logging.exception(e)
        print(e)

这样做,不会创建任何文件。该脚本运行没有错误,但没有创建日志文件。我尝试了几件事,包括使用硬编码的日志文件名,而不是从配置文件中调用它,但它不起作用

唯一有效的方法是在任何方法之前创建日志文件。这是为什么呢?

【问题讨论】:

  • 你确定这段代码可以运行吗?你的内部 try 应该提出一个 SyntaxError 没有匹配的 except
  • @C.Nivs 它有效。为了让你们免于不必要的代码,我只做了非常少的提取。但是是的,代码有效。

标签: python python-3.x logging ini


【解决方案1】:

当您调用process_dirconfig_file 函数时,尚未设置日志记录配置,因此无法创建文件。该脚本从上到下执行。这类似于做这样的事情:

import sys

# default logging points to stdout/stderr kind of like this
my_logger = sys.stdout

my_logger.write("Something")

# Then you've pointed logging to a file
my_logger = open("some_file.log", 'w')

my_logger.write("Something else")

只有Something else 会写入我们的some_file.log,因为my_logger 事先已指向其他地方。

这里也发生了很多相同的事情。默认情况下,logging.<debug/info> 函数什么都不做,因为如果没有额外的配置,logging 不会对它们做任何事情。 logging.errorlogging.warninglogging.exception 将始终至少写入开箱即用的标准输出。

另外,我不认为内部try 是有效的Python,你需要一个匹配的except。而且我不会只打印该函数引发的异常,我可能会raise 并让程序崩溃:

def process_dirconfig_file(config_file_from_sysarg):
    try:
        # Don't use logging.<anything> yet
        ~snip~
    except Exception as e:
        # Just raise or don't use try/except at all until
        # you have a better idea of what you want to do in this circumstance
        raise

特别是因为您在验证其配置是否正确时尝试使用记录器。

解决办法?在确定它已准备就绪之前,请勿使用记录器。

【讨论】:

  • 所以我从配置文件中取出了配置,但是因为我在那个 process_dir_config 函数中调用了记录器,所以它没有写入它。所以看来我需要在该函数之前创建配置文件。我这样说是因为脚本将在服务器环境中运行,所以用户知道出了什么问题的唯一方法是打开一个日志文件。
  • 内部异常存在,我只是将其从代码中删除。但是,是的,我刚刚发现了原因,并感谢您提供额外的背景信息。我将日志信息从配置文件中移出,但只要在处理函数之后创建日志配置,它就不会创建日志文件。是不是因为除非主函数出现异常,否则什么都不会写,因此不会出现日志文件?
  • 设置记录器时,该文件应始终填充。您只需执行logging.basicConfig(filename='myfile.log') 就可以自己查看,这将创建一个空文件myfile.log。因此,如果在程序进入日志记录设置之前引发异常,则不会创建任何文件
  • 在这种情况下,除非发生错误,否则似乎不会创建文件
猜你喜欢
  • 1970-01-01
  • 2015-12-17
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多