USEGEAR

导航

Python的日志

Python的日志,看上去啰啰嗦嗦的。请大神写了个通俗易懂简单方便通用的日志:

import logging
# 配置日志记录级别和输出方式 
logging.basicConfig(level=logging.DEBUG, filename='mylog.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')
def log_exceptions(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logging.exception(f"Exception in function {func.__name__}: {str(e)}")
       raise # 抛出异常,以保持原始行为 
return wrapper @log_exceptions def demo_function1(): # 函数1的逻辑代码
  print(1 / 0)
@log_exceptions def demo_function2(): # 函数2的逻辑代码 # 更多的被装饰函数...

 查看你的日志:

2023-07-10 14:42:25,757 - ERROR - Exception in function demo_function1: division by zero
Traceback (most recent call last):
  File "G:\Python爬虫\mylog.py", line 10, in wrapper
    return func(*args, **kwargs)
  File "G:\Python爬虫\mylog.py", line 19, in demo_function1
    print(1 / 0)
ZeroDivisionError: division by zero

 

posted on 2023-07-10 14:39  USEGEAR  阅读(14)  评论(0编辑  收藏  举报