Python日志logging
logging
用于便捷记录日志且线程安全的模块
1、单文件日志
import logging logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10) logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log') 封装后:
import logging
import logging.handlers class LogFactory(object):
def __init__(self, filename):
self.filename = filename
self.log = logging.getLogger(self.filename)
self.log.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(self.filename, maxBytes=100*1024*1024, backupCount=1000)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(threadName)s [%(module)s.%(funcName)s, Line:%(lineno)d] %(message)s')
handler.setFormatter(formatter)
self.log.addHandler(handler)
# self.log.error(msg) def msg(self, msg):
self.log.info(msg) if __name__ == '__main__': log = LogFactory("sm_article.log") try:
log.msg("Begin to load articles and topics...")
log.msg('HHHHHHHHHHH') except Exception as e:
log.msg("Load catch error:%s" % e)
import logging # create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG) # create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG) # create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # add formatter to ch
ch.setFormatter(formatter) # add ch to logger
logger.addHandler(ch) # "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
屏幕输出的错误信息
日志等级:
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
注:只有【当前写等级】大于【日志等级】时,日志文件才被记录。
日志记录格式:
2、多文件日志
对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。
# 定义文件
file_1_1 = logging.FileHandler('l1_1.log', 'a')
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")
file_1_1.setFormatter(fmt) file_1_2 = logging.FileHandler('l1_2.log', 'a')
fmt = logging.Formatter()
file_1_2.setFormatter(fmt) # 定义日志
logger1 = logging.Logger('s1', level=logging.ERROR)
logger1.addHandler(file_1_1)
logger1.addHandler(file_1_2) # 写日志
logger1.critical('')
日志一
# 定义文件
file_2_1 = logging.FileHandler('l2_1.log', 'a')
fmt = logging.Formatter()
file_2_1.setFormatter(fmt) # 定义日志
logger2 = logging.Logger('s2', level=logging.INFO)
logger2.addHandler(file_2_1)
日志二
少了一句:
logger2.warning('warning')
如上述创建的两个日志对象
- 当使用【logger1】写日志时,会将相应的内容写入 l1_1.log 和 l1_2.log 文件中
- 当使用【logger2】写日志时,会将相应的内容写入 l2_1.log 文件中
根据时间进行日志切割
import logging
import os
import logging.handlers class Logger(logging.Logger):
"""
# my_log = Logger()
#
# # 输出日志
# # log.info("日志模块消息!")
# # log.debug("日志模块调试消息!")
# my_log.error("日志模块错误消息!")
""" def __init__(self, filename=None):
super(Logger, self).__init__(self)
# 日志文件名
if filename is None:
filename = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "zk_css.log")
self.filename = filename # 创建一个handler,用于写入日志文件 (每天生成1个,保留30天的日志)
# fh = logging.handlers.TimedRotatingFileHandler(self.filename, 'D', , )
fh = logging.handlers.WatchedFileHandler(self.filename)
fh.suffix = "%Y%m%d-%H%M.log"
fh.setLevel(logging.DEBUG) # 定义handler的输出格式
formatter = logging.Formatter(
'[%(asctime)s] - %(filename)s [Line:%(lineno)d] - [%(levelname)s]-[thread:%(thread)s]-[process:%(process)s] - [%(message)s]')
fh.setFormatter(formatter) # 给logger添加handler
self.addHandler(fh) try:
logpath = Config().get_content("log")["logpath"]
except Exception as e:
logpath = ""
if os.path.exists(logpath):
my_log = Logger(filename=logpath)
else:
my_log = Logger() my_log.error("adsfadf")
错误日志发邮件
#!/usr/bin/env python
# -*- coding:utf-8 -*- import logging, logging.handlers class EncodingFormatter(logging.Formatter):
def __init__(self, fmt, datefmt=None, encoding=None):
logging.Formatter.__init__(self, fmt, datefmt)
self.encoding = encoding errlog = logging.getLogger()
sh = logging.handlers.SMTPHandler("mail host (smtp host)",
'谁发的',
'发给谁',
"标题",
credentials=('用户名', '密码'),
secure=()
)
errlog.addHandler(sh)
sh.setFormatter(EncodingFormatter('%(message)s', encoding='utf-8')) errlog.error(u'你收到邮件了吗?')
总结
好吧,我承认我懒得二次更改了,发现自己的也不行,网上别人写的也不是我所需要的,而且千篇一律
最好无奈去看了官方文档,ok懂了,
然,最后总结了方法放在了github上面:https://github.com/renfanzi/Python-Tornado-Template
Python日志logging的更多相关文章
- django/python日志logging 的配置以及处理
日志在程序开发中是少不了的,通过日志我们可以分析到错误在什么地方,有什么异常.在生产环境下有很大的用处.在java 开发中通常用 log4j,logback 等三方组件.那么在 django中是怎么处 ...
- Python日志(logging)模块,shelve,sys模块
菜鸟学python第十七天 1.logging 模块 logging模块即日志记录模块 用途:用来记录日志 为什么要记录日志: 为了日后复查,提取有用信息 如何记录文件 直接打开文件,往里写东西 直接 ...
- python 日志logging设置按天进行保存,保存近7天,过期日志自动清理
参考文章(写的很详细):https://www.cnblogs.com/xujunkai/p/12364619.html 前言: 跑接口自动化或者其他程序运行时,如果只能保存一份log文件,可能会存在 ...
- Python日志输出——logging模块
Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...
- python日志模块logging
python日志模块logging 1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...
- Python同时向控制台和文件输出日志logging的方法 Python logging模块详解
Python同时向控制台和文件输出日志logging的方法http://www.jb51.net/article/66756.htm 1 #-*- coding:utf-8 -*- 2 import ...
- python 日志打印之logging使用介绍
python 日志打印之logging使用介绍 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7 简单的将日志打印到屏幕 import logging lo ...
- 【python】logging日志模块写入中文编码错误解决办法
一.问题: 使用python的logging模块记录日志,有时会遇到中文编码问题错误. 二.解决办法: 在logging.FileHandler(path) 中添加指定编码方式 encoding='u ...
- Python 中 logging 日志模块在多进程环境下的使用
因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新.请访问我的个人网站获取这篇文章的最新内容,Python 中 logging 日志模块在多进程环境下的使用 使用 Pytho ...
随机推荐
- nodejs中使用RabbitMq消息中心系统的方式
方式一:通过npm安装amqp库 方式二:通过rabbit.js库http://www.squaremobius.net/rabbit.js/ AMQP:高级消息队列协议,是应用层协议的一个开放标准, ...
- js中的按键事件
参考链接:http://blog.csdn.net/zhouziyu2011/article/details/53978293 <input type="text" id=& ...
- [转]Mac下配置基于SecurID的Cisco IPSec VPN全攻略(有图)
来自: http://www.eefocus.com/Kevin/blog/11-09/230878_53c71.html RSA的SecurID长的是这个样子滴: Mac里面,可以设置VPN, 方法 ...
- Servlet容器Tomcat中web.xml中url-pattern的配置详解[附带源码分析]
目录 前言 现象 源码分析 实战例子 总结 参考资料 前言 今天研究了一下tomcat上web.xml配置文件中url-pattern的问题. 这个问题其实毕业前就困扰着我,当时忙于找工作. 找到工作 ...
- html 元素分类
在讲解CSS布局之前,我们需要提前知道一些知识,在CSS中,html中的标签元素大体被分为三种不同的类型:块状元素.内联元素(又叫行内元素)和内联块状元素. 常用的块状元素有: <div> ...
- pyhton 学习
官方学习文档 https://docs.python.org/3/tutorial/
- 关于GeoWebCache的部署说明
最近因为工作需要学习了GeoWebCache,有了一些实战经验跟大家分享一下. 废话不多说,直接上问题! 1.切片的缓存问题 当地图服务(这里默认指WMS)的数据更新时,GeoWebCache的切片如 ...
- Html定位精要
Html定位基础 Html的布局是文档流模型,块元素独占一行,内联元素并列一行. 相对定位 position: relative 相对于自己定位 不脱离文档流,元素原有位置被保留 绝对定位 posit ...
- <<< html编码中js和html编码不一致导致乱码
在html中,有时把编码设置成UTF-8之后,引入js,页面不会有乱码,但是有关js的东西会出现乱码, 大概问题就是js默认编码不是UTF-8, 解决办法:将js文件用记事本打开,在另存为,保存的时候 ...
- oracle---plsql---示例laobai
select * from scott.emp; --1 列出emp表中各部门的部门号,最高工资,最低工资 select deptno,max(sal),min(sal) from scott.emp ...