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. Qt——透明无边框Widget的bug

    Experience 最近在封装一些类的时候,打算做一个窗口框架,能实现拖动.缩放.最大最小化.基本样式等功能,可不慎遇见一件无比蛋疼的事情,QWidget最小化后再恢复正常界面,最小化按钮居然仍处于 ...

  2. 40个让你的网站屌到爆的jQuery插件

    一 个插件的基本功能是执行一个含有元素集合的函数数组.每个方法和jQuery核心组成一个插件,如.fadeOut()或.addClass().一个 jQuery插件是一个基本的可以扩充jQuery 原 ...

  3. VMware 设备VMnet0 上的网桥暂时关闭。此虚拟机无法与主机或网格中的其他计算机通信【转】

    今天克隆了一个win7的虚拟机,移动到我的本地.打开时发现虚拟机网格连接图标出现X断开连接,于是网上收了一堆答案无一个可用的,决定自己解决这个问题,解决过程如下: 1.报错图如下:设备VMnet0 上 ...

  4. shell脚本每天自动备份mysql数据库

    一.mysql提供了一个mysqldump的工具可以方便的导出导入数据库信息: 二.使用命令行shell测试执行mysqldump,理解必备的参数,查看生成的sql备份文件是否符合需求: /usr/b ...

  5. ical4j 实现ICS文件的生成和解析

    iCalendar 简介 iCalendar,简称"iCal",是"日历数据交换"的标准(RFC 2445),该标准提供了一种公共的数据格式用于存储关于日历方面 ...

  6. Dedecms去掉URL中a目录的方法

    本文实例讲述了Dedecms去掉URL中a目录的方法.分享给大家,供大家参考.具体分析如下: 使用dedecms的朋友可能会发现自己的URL目录生成是会自动带有一个/A/目录了,那么要如何去掉URL中 ...

  7. Linux文件计数

    1.当前目录下的文件数 ls -l |grep "^-"|wc -l 2.当前目录的目录树 ls -l |grep "^d"|wc -l 3.当前目录文件数包含 ...

  8. Java基础-包名和文件夹名字必须对应

    .java文件夹中的包名必须与物理文件夹的对应. 如果修改包名或者文件夹名,双方都需要同时更新.

  9. BZOJ2815: [ZJOI2012]灾难

    传送门 学LCA的时候根本没意识到LCA可以有这么多玩法. 这玩意据说是个高级数据结构(支配树)的弱化版,蒟蒻没学过呀.所以出题人提出一个概念叫灾难树. 我理解的灾难树的意思实际上是属于DAG的一个子 ...

  10. lua学习例子

    extern "C"{ #include <lua.h> #include <lauxlib.h> #include <lualib.h> } ...