python记录程序输出及错误信息(log,logging)

您所在的位置:网站首页 logerror报错 python记录程序输出及错误信息(log,logging)

python记录程序输出及错误信息(log,logging)

2024-03-19 16:17| 来源: 网络整理| 查看: 265

记录日志的方法类型

logging记录日志的方式可以分为两种:

通过调用logging类的成员函数,直接记录日志实例化一个logger来实现更多的日志记录功能。 通过logging的类方法直接记录日志

由于一般的程序日志量不大,所以直接调用logging类的成员函数即可实现普通的日志记录。

import logging import time # 配置logging current_time = time.strftime("%H:%M:%S_%Y-%m-%d", time.localtime(time.time())) logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(filename)s:%(lineno)d - %(message)s', handlers=[ logging.FileHandler(f"./logs/runtime_log_{current_time}.log", mode="a"), # for logs write in file(mode:a为追加log,设置为w则表示每次清空,重新记录log) logging.StreamHandler() # for print at console ] ) def test(): try: something except Exception as e: # 尽量不要使用logging.error,而是使用logging.exception来记录具体异常 logging.exception("open zip file error: {}".format(lib_name)) continue if __name__ == '__main__': test() logging.info('work done: {}.'.format(work_id)) # 记录输出 如果想在同一项目下的其他py文件中使用logging,直接import logging,然后使用logging.info即可。子文件的输出也会根据main.py的配置格式输出到在main.py中定义的log文件中。

B站视频教程 Python日志库logging总结

读取log文件 import re # original plot map, attack_acc = [], [] file_path="./model_training.log" with open(file_path, "r") as f: for line in f: match1 = re.match(r".*Current_mAP = (.*), .*", line) # match1 = re.match(r".*Test:.*mAP (.*)", line) match2 = re.match(r".*Acc. is (.*).*", line) if match1: map.append(float(match1.group(1))) elif match2: attack_acc.append(float(match2.group(1))) print(map) print(attack_acc) 通过实例化一个logger来记录日志

上面的方式是使用了logging这个类来实现记录日志的,我们还可以实例化一个logger的方式来记录日志。推荐使用logger = logging.dictLogger()来实例化一个logger类。

这种方法的好处是可以实现更多细化的功能,如方便地配置多个Handler等。这种方法一般用于大型应用的日志记录。

感兴趣的话,可以去学习logging.dictLogger()的相关知识。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3