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. VPS搭建VPN、BLOG

    FQ的正确姿势,你掌握了多少?老司机带你去墙外看看,来开车了坐稳! 购买VPS主机(服务端) 推荐性价比较高的VPS 搬瓦工https://bandwagonhost.com/ 上面的链接如果你打不开 ...

  2. JSX语法简介

    React的核心机制之一就是可以在内存中创建虚拟的DOM元素.React利用虚拟DOM来减少对实际DOM的操作从而提升性能. JSX简介 JSX就是Javascript和XML结合的一种格式.Reac ...

  3. css点滴

    1.vertical-align这个属性用于块元素的垂直,居中,行元素用line-height. text-align比如li span时,text-align用于上一句的li的元素时,span才会居 ...

  4. Mybatis使用总结

    一.最基本的配置文件 <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurati ...

  5. maven 打包

    使用命令行形式打包 1.配置maven环境变量,在变量path中加入maven路径. 2.在要打包的项目目录下使用:Ctrl+shift+鼠标右键点击,点击 在此处打开命令行窗口. 在打开的命令行窗口 ...

  6. android MVC && MVP && MVVM分析和对比

    相关:http://www.cnblogs.com/wytiger/p/5305087.html 出处http://blog.csdn.net/self_study,对技术感兴趣的同鞋加群544645 ...

  7. C#-WinForm-Treeview-树状模型

    Treeview - 树状模型 利用递归添加数据 数据放入 treeView1.Nodes.Add() 中 public Form3() { InitializeComponent(); TreeNo ...

  8. sublimetext调试

    Package Control Sublime Text提供了绝对必要的包管理器.这是安装下面列出的所有插件和主题的最佳方式.继续,在包控制在安装插件. 进入命令面板(ctrl + shift+ p) ...

  9. 【BZOJ-1898】Swamp 沼泽鳄鱼 矩阵乘法

    1898: [Zjoi2005]Swamp 沼泽鳄鱼 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 1012  Solved: 566[Submit][S ...

  10. 大熊君大话NodeJS之 ------ Connect中间件第二季(源码分析)

    一,开篇分析 大家好,大熊君又回来了,今天这篇文章主要是对"Connect"中间件以及相关辅助中间件,做一个源码分析系列,我想上一篇文章大家也看了, 介绍了使用方式及用途,而这篇也 ...