【发布时间】: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