python 使用装饰器并记录log的示例代码

yipeiwu_com6年前Python基础

1.首先定义一个log文件

# -*- coding: utf-8 -*-
import os
import time
import logging
import sys
log_dir1=os.path.join(os.path.dirname(os.path.dirname(__file__)),"logs")
today = time.strftime('%Y%m%d', time.localtime(time.time()))
full_path=os.path.join(log_dir1,today)
if not os.path.exists(full_path):
 os.makedirs(full_path)
log_path=os.path.join(full_path,"facebook.log")
def get_logger():
  # 获取logger实例,如果参数为空则返回root logger
  logger = logging.getLogger("facebook")
  if not logger.handlers:
   # 指定logger输出格式
   formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')
 
   # 文件日志
   file_handler = logging.FileHandler(log_path,encoding="utf8")
   file_handler.setFormatter(formatter) # 可以通过setFormatter指定输出格式
 
   # 控制台日志
   console_handler = logging.StreamHandler(sys.stdout)
   console_handler.formatter = formatter # 也可以直接给formatter赋值
 
   # 为logger添加的日志处理器
   logger.addHandler(file_handler)
   logger.addHandler(console_handler)
 
   # 指定日志的最低输出级别,默认为WARN级别
   logger.setLevel(logging.INFO)
  # 添加下面一句,在记录日志之后移除句柄
  return logger

2.然后定义一个装饰器文件

在这里引用wraps,一个装饰器的装饰器,目的为了保持引用进来的函数名字不发生变化

#!/usr/bin/env python 
# encoding: utf-8
from functools import wraps
from logger.log import get_logger
import traceback
def decoratore(func):
 @wraps(func)
 def log(*args,**kwargs):
  try:
   print("当前运行方法",func.__name__)
   return func(*args,**kwargs)
  except Exception as e:
   get_logger().error(f"{func.__name__} is error,here are details:{traceback.format_exc()}")
 return log

3.在使用的时候直接在函数上面引用即可

@decorator
def start():
 print("666")

以上这篇python 使用装饰器并记录log的示例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python opencv图片编码为h264文件的实例

python部分 #!/usr/bin/env Python # coding=utf-8 from ctypes import * from PyQt5.QtCore impo...

python paramiko模块学习分享

paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。paramiko支持Linux, Solaris, BSD, MacOS...

python 读取txt,json和hdf5文件的实例

一.python读取txt文件 最简单的open函数: # -*- coding: utf-8 -*- with open("test.txt","r",encoding="gbk"...

python向已存在的excel中新增表,不覆盖原数据的实例

每月需更新某个excel表格,进行两项操作,且不覆盖原有的sheet: 1. 在原来的excel表中新增sheet 2. 往原有的excel表中的某张sheet新增内容 基于python...

python使用tornado实现登录和登出

本文实例为大家分享了tornado实现登录和登出的具体代码,供大家参考,具体内容如下 main.py如下: import tornado.httpserver import torn...