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 ...
随机推荐
- python 类属性与方法
Python 类属性与方法 标签(空格分隔): Python Python的访问限制 Python支持面向对象,其对属性的权限控制通过属性名来实现,如果一个属性有双下划线开头(__),该属性就无法被外 ...
- 学习C++.Primer.Plus 11 使用类
1.操作符重载 重载操作符的几个限制: a) 重载的至少有一个操作数是用户定义的类型,这将防止用户为标准类型重载操作符. b) 不能违反操作符原有来的句法规则. c) ...
- 【原】KMeans与深度学习模型结合提高聚类效果
这几天在做用户画像,特征是用户的消费商品的消费金额,原始数据(部分)是这样的: id goods_name goods_amount 男士手袋 1882.0 淑女装 2491.0 女士手袋 345.0 ...
- 1128ORDER BY的原理
工作过程中,各种业务需求在访问数据库的时候要求有order by排序.有时候不必要的或者不合理的排序操作很可能导致数据库系统崩溃.如何处理好order by排序呢?本文从原理以及优化层面介绍 ord ...
- VS 团队资源管理 强制解锁锁定文件
故事是这样发生的: 以前有台电脑,在团队资源里看程序,可能冥冥中不小心按了个空格,so,文件被锁定 而我却没有发现 如果再给我一个机会,我只想说记得签入 然后,高潮来了 重装电脑 欣喜的装好新机子打开 ...
- cocos2d-x 3.10 PageView BUG
cocos2d-x 3.10 PageView 拖动滚动到下一个单元,没事件,3.11有修复.
- BZOJ 1968: [Ahoi2005]COMMON 约数研究
1968: [Ahoi2005]COMMON 约数研究 Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 2032 Solved: 1537[Submit] ...
- BZOJ 2038: [2009国家集训队]小Z的袜子(hose)
2038: [2009国家集训队]小Z的袜子(hose) Time Limit: 20 Sec Memory Limit: 259 MBSubmit: 7676 Solved: 3509[Subm ...
- mysql索引
1.创建索引 (PRIMARY KEY,INDEX,UNIQUE) mysql>ALTER TABLE tbl_name ADD INDEX index_name (column list); ...
- [转]eclipse快捷键
Ctrl+1 快速修复Ctrl+D: 删除当前行 Ctrl+Alt+↓ 复制当前行到下一行(复制增加)Ctrl+Alt+↑ 复制当前行到上一行(复制增加)Alt+↓ 当前行和下面一行交互位置(特别实用 ...