升级优化关于日志生成logging封装TimedRotatingFileHandler
1.变更升级:优化日志自定义输出到文件的level,以及文件夹生成用户自由控制
# coding=utf-8
import logging
import time
import os
import logging.handlers
import re def logger(appName,rootstdout=True,handlerList=None): log_fmt= "%(asctime)s --%(name)s-- [%(levelname)s]:\n%(message)s"
c_fmt="%(asctime)s --%(name)s-- %(filename)s.%(funcName)s():line %(lineno)d [%(levelname)s]:\n%(message)s"
date_format = "%Y-%m-%d %H:%M:%S %a"
# 设置控制台输出level
logging.basicConfig(level=logging.DEBUG,
format=c_fmt,
datefmt=date_format, )
levels=[]
if isinstance(handlerList,list):
if handlerList.__contains__("I") or handlerList.__contains__("Info"):
levels.append("Info")
if handlerList.__contains__("D") or handlerList.__contains__("Debug"):
levels.append("Debug")
if handlerList.__contains__("E") or handlerList.__contains__("Error"):
levels.append("Error")
if handlerList.__contains__("W") or handlerList.__contains__("Warning"):
levels.append("Warning")
if levels:
stamp = "dailylog.log"
logsdir=os.path.join(os.getcwd(),"logs")
if os.path.exists(logsdir):
for p in levels:
if os.path.exists(os.path.join(logsdir,p)):
pass
else:
os.mkdir(os.path.join(logsdir,p))
else:
os.mkdir(logsdir)
for p in levels:
os.mkdir(os.path.join(logsdir,p)) f_dict={}
for i in levels:
filename=os.path.join(logsdir,i,stamp)
f_dict[i]=filename
logger= logging.getLogger(appName) for k,v in f_dict.items():
handler=logging.handlers.TimedRotatingFileHandler(filename=v,when='MIDNIGHT', interval=1, backupCount=4)
handler.suffix = "%Y-%m-%d.log"
handler.extMatch = r"^\d{4}-\d{2}-\d{2}.log$"
handler.extMatch = re.compile(handler.extMatch)
h_fmt=logging.Formatter(log_fmt)
handler.setFormatter(h_fmt)
if k=="E" or k=="Error":
handler.setLevel(logging.ERROR)
elif k=="I" or k=="Info":
handler.setLevel(logging.INFO)
elif k== "W" or k=="Warning":
handler.setLevel(logging.WARNING)
elif k=="D" or k=="Debug":
handler.setLevel(logging.DEBUG)
else:
raise NameError("check your logLevel Name is corrected or not")
logger.addHandler(handler)
logger.propagate = rootstdout
return logger
else:
raise TypeError("check handlerList at least one corrected logLevel in:'Error','Info','Warning','Debug'")
else:
raise NameError("handlerList expected type is list but get type {}".format(type(handlerList).__name__))
if __name__ == "__main__":
logger=logger("root",rootstdout=True,handlerList=['E']) time.sleep(0.01)
try:
assert 1==2
except Exception as e:
logger.info("ddd",exc_info=True) logger.debug("bebug test")
logger.error("error test")
logger.warning("warning test")
升级优化关于日志生成logging封装TimedRotatingFileHandler的更多相关文章
- 优化升级logging封装RotatingFileHandler
1.升级优化,提供用户自定义日志level文件夹生成控制,提供日志错误显示到日志打印异常补获到日志 # coding=utf-8 import logging import time import o ...
- 采坑复盘:logging日志能用封装后的函数来打日志,发现filename一直显示封装logging函数的方法所在的文件名
问题: logging日志能用封装后的函数来打日志,发现filename一直显示封装logging函数的方法所在的文件名 原因: logging记录的是第一个函数执行所在的文件,那用封装的函数,首先执 ...
- Python之日志处理 logging模块
Python之日志处理(logging模块) 本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging四 ...
- python基础:日志模块logging,nnlog
python里面用来打印日志的模块,就是logging模块,logging模块可以在控制台打印日志,也可以写入文件中.也可以两个操作都执行 1.控制台输入 import logging#导入模块 lo ...
- python 重要的日志模块logging
一,logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...
- python日志模块logging学习
介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...
- Python日志库logging总结-可能是目前为止将logging库总结的最好的一篇文章
在部署项目时,不可能直接将所有的信息都输出到控制台中,我们可以将这些信息记录到日志文件中,这样不仅方便我们查看程序运行时的情况,也可以在项目出现故障时根据运行时产生的日志快速定位问题出现的位置. 1. ...
- Python日志库logging总结
转自 https://cloud.tencent.com/developer/article/1354396 在部署项目时,不可能直接将所有的信息都输出到控制台中,我们可以将这些信息记录到日志文件中 ...
- python重要的日志模块logging
一,logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 1.可以通过设置 ...
随机推荐
- margin相关基本知识
什么是 margin ? CSS 边距属性定义元素周围的空间.通过使用单独的属性,可以对上.右.下.左的外边距进行设置.也可以使用简写的外边距属性同时改变所有的外边距.——W3School 边界,元素 ...
- css边框颜色渐变
在实际开发中,我们经常遇见边框需要背景渐变的实现要求,那么如何去实现呢,今天给大家分享依稀几种情况 1.直角的背景渐变 <!DOCTYPE html> <html lang=&quo ...
- GridView双击行弹出窗口
protected void gvCustom_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == D ...
- Android onActivityResult和setResult
如果你想在Activity中得到新打开Activity关闭后返回的数据,你需要使用系统提供的startActivityForResult(Intent intent,int requestCode)方 ...
- 网络 互联网接入方法、Mbit与MB的转换
ADSL:非对称数字用户环路(绝大多数家庭接入方法,使用电话线).可以提供最高1Mbps的上行速率和最高8Mbps的下行速率.最新的ADSL2+可以提供最高24Mbps的下行速率. 千千兆TB 千兆G ...
- maven jstl、jsp、servlet依赖
jstl.jsp.servlet依赖 <dependency> <groupId>javax.servlet</groupId> <artifactId> ...
- Python Socket实现简单web服务器
#!/usr/bin/python env # coding:utf-8 import socket ip_port = ('127.0.0.1', 80) back_log = 10 buffer_ ...
- Oracle EBS 新增OAFM个数
在 $INST_TOP/ora/10.1.3/opmn/conf/opmn.xml中找到<process-type id="oafm" module-id="OC4 ...
- UIWebView如何加载本地图片
UIWebView如何加载本地图片 UIWebView加载本地图片是有实用价值的.比方说,有时候我们需要本地加载静态页来显示相关帮助信息,而这些帮助信息当中含有很多很多的富文本,用代码实现难度较大,这 ...
- [翻译] TGLStackedViewController
TGLStackedViewController A stack layout with gesture-based reordering using UICollectionView -- insp ...