首页 技术 正文
技术 2022年11月9日
0 收藏 892 点赞 2,351 浏览 1251 个字

在调试logging的封装的时候,发现已经调用了logging封装的函数,在被其它函数再调用时,会出现重复的logging。原因是不同的地方创建了不同的handler,所以会重复,可以使用暴力方法解决

暴力方式就是每次创建新的对象就清空logger.handlers

我常用的封装如下

import logging
import time,os
'''
使用方法:
import mylog
log = mylog.Log().getlog()
log.debug("###")
'''
class Log(): def __init__(self,logger="mylog"):
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG)
self.log_time = "\\"+time.strftime("%Y-%m-%d_%H_%M", time.localtime())+".log"
# 在进程路径创建log文件夹
# self.log_path = os.path.join(os.getcwd() + "\\log")
# 固定在mylog上一级创建
self.log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)) + "\\log")
if os.path.exists(self.log_path) and os.path.isdir(self.log_path):
pass
else:
os.makedirs(self.log_path)
self.log_name = os.path.join(self.log_path + self.log_time) #因为多出调用logger会生成多个handlers,所以每次调用清空handler
self.logger.handlers = []
fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')
formatter = logging.Formatter('[%(levelname)s][%(asctime)s] [%(filename)s]->[%(funcName)s] line:%(lineno)d ---> %(message)s')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
self.logger.addHandler(fh) ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self.logger.addHandler(ch) fh.close() def getlog(self):
return self.loggerif __name__ == "__main__":
log = Log().getlog()
log.debug("hello")
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295