升级优化关于日志生成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.可以通过设置 ...
随机推荐
- Codeforces 1097 Alex and a TV Show
传送门 除了操作 \(3\) 都可以 \(bitset\) 现在要维护 \[C_i=\sum_{gcd(j,k)=i}A_jB_k\] 类比 \(FWT\),只要求出 \(A'_i=\sum_{i|d ...
- centos 删除文件和目录
每次都记不住,发个文章记录一下.直接rm就可以了,不过要加两个参数-rf 即:rm -rf 目录名字-r 就是向下递归,不管有多少级目录,一并删除-f 就是直接强行删除,不作任何提示的意思 删除文件夹 ...
- CSS预编译器:Sass(进阶),更快的前端开发
1.@if @if 指令是一个 SassScript,它可以根据条件来处理样式块,如果条件为 true 返回一个样式块,反之 false 返回另一个样式块 在 Sass 中除了 @if 之,还 ...
- ubuntu下使用python3的有些库时,解决"raise ImportError(str(msg) + ', please install the python3-tk package') ImportError: No module named '_tkinter', please install the python3-tk package"的错误
问题: 在Ubuntu下使用matplotlib这个库时,运行时出现如下错误: raise ImportError(str(msg) + ', please install the python3-t ...
- jQuery实现大图轮播
css样式: *{ margin: 0; padding: 0;}ul{ list-style:none;}.slideShow{ width: 620px; heigh ...
- idea 自动导入包设置
- MYSQL数据类型 表基本操作 表记录增删改 单表查询
一.数据类型 常用的数据类型如下: 整数:int,bit 小数:decimal 字符串:varchar,char 日期时间: date, time, datetime 枚举类型(enum) 特别说明的 ...
- shell黑名单
#/bin/bash netstat -ant | " | awk '{print $5}' | grep -v "^10" | cut -d ":" ...
- python-threading.Event实现事件功能--汽车过红绿灯(转载)
python-threading.Event实现事件功能 enent可以通过设置.等待.清除一个标识(flag),来进行线程间的控制线程可以通过获取这个标志位(flag)的状态(设置或未设置)来控制线 ...
- winform listbox增加鼠标双击事件
在Form.Designer.cs文件中对于listBox处理: listBox.MouseDoubleClick += new system.Windows.Forms.MouseEventHand ...