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的更多相关文章

  1. django/python日志logging 的配置以及处理

    日志在程序开发中是少不了的,通过日志我们可以分析到错误在什么地方,有什么异常.在生产环境下有很大的用处.在java 开发中通常用 log4j,logback 等三方组件.那么在 django中是怎么处 ...

  2. Python日志(logging)模块,shelve,sys模块

    菜鸟学python第十七天 1.logging 模块 logging模块即日志记录模块 用途:用来记录日志 为什么要记录日志: 为了日后复查,提取有用信息 如何记录文件 直接打开文件,往里写东西 直接 ...

  3. python 日志logging设置按天进行保存,保存近7天,过期日志自动清理

    参考文章(写的很详细):https://www.cnblogs.com/xujunkai/p/12364619.html 前言: 跑接口自动化或者其他程序运行时,如果只能保存一份log文件,可能会存在 ...

  4. Python日志输出——logging模块

    Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...

  5. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  6. Python同时向控制台和文件输出日志logging的方法 Python logging模块详解

    Python同时向控制台和文件输出日志logging的方法http://www.jb51.net/article/66756.htm 1 #-*- coding:utf-8 -*- 2 import ...

  7. python 日志打印之logging使用介绍

    python 日志打印之logging使用介绍 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7   简单的将日志打印到屏幕 import logging lo ...

  8. 【python】logging日志模块写入中文编码错误解决办法

    一.问题: 使用python的logging模块记录日志,有时会遇到中文编码问题错误. 二.解决办法: 在logging.FileHandler(path) 中添加指定编码方式 encoding='u ...

  9. Python 中 logging 日志模块在多进程环境下的使用

    因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新.请访问我的个人网站获取这篇文章的最新内容,Python 中 logging 日志模块在多进程环境下的使用 使用 Pytho ...

随机推荐

  1. AFNetWorking3.0源码分析

    分析: AFNetWorking(3.0)源码分析(一)——基本框架 AFNetworking源码解析 AFNetworking2.0源码解析<一> end

  2. cf Round 607

    A.Chain Reaction(DP+二分) 题意:一排有n个灯塔,每个灯塔给出坐标xi和力量yi,每次从最右边依次点亮灯塔,每点亮一个灯塔,它左边的距离它yi范围内的灯塔将受到损坏.现在允许在最右 ...

  3. manachor

    在原字符串每个字符间各插入一个未曾出现的字符,在字符串头插入另一个未出现的字符防止越界,求出的p[i]-1既为以i为中心的最长回文串的长度 void manacher(){ ,id; ;i<=n ...

  4. Jquery揭秘系列:Validation实现

    之前讲了一部分揭秘系列的东西,由于年初的时候在改项目,也没有写下去.现在开始闲下来了,会继续写没写完的东西,各种原生js实现Jquery的功能. 转入正题,说一下今天要讲的东西. 相信很多tx在项目里 ...

  5. 解决:error: .repo/manifests/: contains uncommitted changes

    repo sync同步时提示出错:          error: .repo/manifests/: contains uncommitted changes 解决方法: 1.cd 进入.repo/ ...

  6. bzoj2179: FFT快速傅立叶

    #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> ...

  7. wpf 客户端 添加qq客服咨询

    使用qq推广 站点:http://shang.qq.com/v3/widget.html 复制里面的html代码: <a target=" src="http://wpa.q ...

  8. CSS DIV自动适应高度

    当div需要设定自适应高度时,可用到的css属性,min-height:200px;代表的是当div的内容超出了200px时,就会自动适应高度,兼容所有浏览器(IE6除外),如果是IE6则需要设置&q ...

  9. SmohanTimeLine.js 酷炫的时间轴效果

    展示地址 点此下载 原文出处 一.参数说明 item : '.item', //项目元素 top : 30, //与下一行的间距 pointWidth : 22, //时间点宽度 cornerWidt ...

  10. 山东第一届省赛1001 Phone Number(字典树)

    Phone Number Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^ 题目描述 We know that if a phone numb ...