python标准库-日志logging
1、模块级别
默认情况下logging模块将日志打印到了标准输出,且只显示了级别大于等于warning的日志信息,所以它的默认级别是warning.
日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
- #!/usr/bin/env python
- # _*_ coding: utf-8 _*_
- # __author__ ='kong'
- import logging
- import time
# 日志的输出级别- print logging.NOTSET
- print logging.DEBUG
print logging.INFO- print logging.WARNING
- print logging.ERROR
- print logging.CRITICAL
- time.sleep(1)
- logging.debug("debug message")
- # 默认的日志输出级别
- logging.warn("warn message")
- logging.error("error message")
- logging.critical("critical message")
输出
2、logging.basicConfi([**kwargs])
语法:
- def basicConfig(**kwargs):
- """
- Do basic configuration for the logging system.
- This function does nothing if the root logger already has handlers
- configured. It is a convenience method intended for use by simple scripts
- to do one-shot configuration of the logging package.
- The default behaviour is to create a StreamHandler which writes to
- sys.stderr, set a formatter using the BASIC_FORMAT format string, and
- add the handler to the root logger.
- A number of optional keyword arguments may be specified, which can alter
- the default behaviour.
- filename Specifies that a FileHandler be created, using the specified
- filename, rather than a StreamHandler.
- filemode Specifies the mode to open the file, if filename is specified
- (if filemode is unspecified, it defaults to 'a').
- format Use the specified format string for the handler.
- datefmt Use the specified date/time format.
- level Set the root logger level to the specified level.
- stream Use the specified stream to initialize the StreamHandler. Note
- that this argument is incompatible with 'filename' - if both
- are present, 'stream' is ignored.
- Note that you could specify a stream created using open(filename, mode)
- rather than passing the filename and mode in. However, it should be
- remembered that StreamHandler does not close its stream (since it may be
- using sys.stdout or sys.stderr), whereas FileHandler closes its stream
- when the handler is closed.
- """
logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为.
- 可用的参数:
filename: 用指定的文件名创建FileHandler,这样日志会被存储在指定的文件中
filemode:文件打开的方式,在指定了filename时使用,默认值为a
format:指定handler使用的日志显示格式
datefmt:指定日期时间格式
level:设置rootlogger的日志级别
stream:用指定的stream创建StreamHandler,可指定输出到sys.stderr,sys.stdout或者文件,默认sys.stderr- format参数可能用到的格式化串:
%(name)s:Logger的名字
%(levelno)s:数字形式的日志级别
%(levelname)s:文本形式的日志级别
%(pathname)s:调用日志输出函数的模块的文件名
%(module)s:调用日志输出函数的模块名
%(funcName)s:调用日志输出函数的函数名
%(lineno)d:调用日志输出函数的语句所在的代码行
%(created)f:当前时间,用UNIX标准的表示 时间的浮点数表示
%(relativeCreated)d:输出日志信息时,自Logger创建以来的毫秒数
%(asctime)s:字符串形式的当前时间。默认格式2003-07-12 16:23:26,345
%(thread)d:线程ID
%(threadName)s:线程名
%(process)d:进程ID
%(message)s:用户输出的消息
- datefmt格式:
%Y:年份的长格式,1999
%y:年份的短格式,99
%m:月份 01-12
%d:日期,01-31
%H:小时,0-23
%M:分钟,00-59
%S:秒,00-59
- 基本用法示例代码:
- #!/usr/bin/env python
- # _*_ coding: utf-8 _*_
- # __author__ ='kong'
- import logging
- class TestLogging(object):
- def __init__(self):
- logFormat = '%(asctime) -12s %(levelname) -8s %(name) -10s %(message) -12s'
- logFileName = './testLog.txt'
- logging.basicConfig(level = logging.INFO,format=logFormat,filename=logFileName,filemode='w')
- logging.debug("debug message")
- logging.info("info message")
- logging.error("error message")
- logging.critical("critical message")
- if __name__ == '__main__':
- T = TestLogging()
- 结果:
- 2017-01-15 12:26:42,424 INFO root info message
- 2017-01-15 12:26:42,424 ERROR root error message
- 2017-01-15 12:26:42,424 CRITICAL root critical message
自定义模块myLog
- #!/usr/bin/env python
# _*_ coding: utf-8 _*_
# __author__ ='kong'
import logging
import getpass
import sys- class MyLog(object):
def __init__(self):
# 为当前用户创建日志实例,设置默认日志级别
user = getpass.getuser()
self.logger = logging.getLogger(user)
self.logger.setLevel(logging.DEBUG)
Formatter = logging.Formatter('%(asctime) -12s %(levelname) -8s %(name) -10s %(message) -12s')
"""
Initialize the formatter with specified format strings.- Initialize the formatter either with the specified format string, or a
default as described above. Allow for specialized date formatting with
the optional datefmt argument (if omitted, you get the ISO8601 format).
"""
# 创建文件句柄,设置日志格式、日志级别
logFile = './' + sys.argv[0][0:3] + '.log'
logHand = logging.FileHandler(logFile)
logHand.setLevel(logging.ERROR) # 错误级别以上信息才会写到文件中
logHand.setFormatter(Formatter)
"""
Set the formatter for this handler.
"""
# 创建stream句柄,设置日志格式
logHandSt = logging.StreamHandler()
logHandSt.setFormatter(Formatter)
# 应用文件句柄和stream句柄,来处理日志
self.logger.addHandler(logHand)
self.logger.addHandler(logHandSt)
logging.basicConfig()
def debug(self,msg):
self.logger.debug(msg)- def info(self,msg):
self.logger.info(msg)- def warn(self,msg):
self.logger.warn(msg)- def error(self,msg):
self.logger.error(msg)- def critical(self,msg):
self.logger.critical(msg)- if __name__ == '__main__':
T = MyLog()
T.debug("debug message")
T.info("info message")
T.warn("warn message")
T.error("error message")
T.critical("crital message")
详见:
http://blog.csdn.net/zyz511919766/article/details/25136485/
http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html
示例参考:
- #!/usr/bin/env python
- # _*_ coding:utf- _*_
- import logging.config
- import datetime
- import os
- # 基路径
- BaseDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- # 时间模块
- ToDay = datetime.date.today()
- YsDay = ToDay - datetime.timedelta(days=)
- ToDay = ToDay.strftime('%Y-%m-%d')
- YsDay = YsDay.strftime('%Y-%m-%d')
- # 创建日志目录
- logdir = os.path.join(BaseDir,'log',ToDay)
- if not os.path.exists(logdir):os.makedirs(logdir)
- # 定义三种日志输出格式
- standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
- '[%(levelname)s][%(message)s]'
- simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
- id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
- def log_handle(logname='default'):
- LOG_PATH = os.path.join(logdir, logname + '.log') # 日志文件名称
- LOGGING_DIC = {
- 'version': ,
- 'disable_existing_loggers': False,
- 'formatters': {
- 'standard': {
- 'format': standard_format
- },
- 'simple': {
- 'format': simple_format
- },
- 'id_simple': {
- 'format': id_simple_format
- },
- },
- 'filters': {},
- 'handlers': {
- # 打印到终端的日志
- 'console': {
- 'level': 'DEBUG',
- 'class': 'logging.StreamHandler', # 打印到屏幕
- 'formatter': 'simple'
- },
- # 打印到文件的日志,收集info及以上的日志
- 'collect': {
- 'level': 'DEBUG',
- 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
- 'formatter': 'simple',
- 'filename': LOG_PATH, # 日志文件
- 'maxBytes': * * , # 日志大小 5M
- 'backupCount': ,
- 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
- },
- },
- 'loggers': {
- '': {
- 'handlers': ['console', 'collect'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
- 'level': 'DEBUG',
- 'propagate': False, # 向上(更高level的logger)传递
- },
- },
- }
- logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的 log 配置
- logger = logging.getLogger() # 生成一个log实例
- return logger
python标准库-日志logging的更多相关文章
- Python标准库之logging模块
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...
- python第六天 函数 python标准库实例大全
今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...
- 转--Python标准库之一句话概括
作者原文链接 想掌握Python标准库,读它的官方文档很重要.本文并非此文档的复制版,而是对每一个库的一句话概括以及它的主要函数,由此用什么库心里就会有数了. 文本处理 string: 提供了字符集: ...
- Python 标准库一览(Python进阶学习)
转自:http://blog.csdn.net/jurbo/article/details/52334345 写这个的起因是,还是因为在做Python challenge的时候,有的时候想解决问题,连 ...
- python 标准库大全
python 标准库 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 string ...
- Python 标准库 BaseHTTPServer 中文翻译
Python 标准库 BaseHTTPServer 中文翻译. 注意: BaseHTTPServer模块在Python3中已被合并到http.server,当转换你的资源为 Python3 时 2to ...
- Python标准库14 数据库 (sqlite3)
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python自带一个轻量级的关系型数据库SQLite.这一数据库使用SQL语言.S ...
- python标准库00 学习准备
Python标准库----走马观花 python有一套很有用的标准库.标准库会随着python解释器一起安装在你的电脑上的.它是python的一个组成部分.这些标准库是python为你准备的利器,可以 ...
- Python标准库:内置函数hasattr(object, name)
Python标准库:内置函数hasattr(object, name) 本函数是用来判断对象object的属性(name表示)是否存在.如果属性(name表示)存在,则返回True,否则返回False ...
随机推荐
- classpath获取--getResource()
在java中的API里,有两种方式来使用classpath读取资源. 1. Class的getResource() 2. ClassLoader的getResource() 但是两者有一定区别,运行以 ...
- hdu_5734_Acperience
题目连接:hdu_5734_Acperience 多校的题我还是贴官方题解的好,方便快捷,省事!! #include<cstdio> #include<cmath> #defi ...
- As3.0 视频缓冲、下载总结
来源:http://www.cuplayer.com/player/PlayerCodeAs/2012/0913404.html 利用NetStream的以下属性: bufferTime — 缓冲区大 ...
- Qt学习
博客 一去丶二三里的博客 http://blog.sina.com.cn/s/articlelist_2801495241_0_4.html
- 【转】Xshell 十个技巧
原文:http://www.cnblogs.com/wanhl/archive/2012/10/17/2727607.html 一.帐号密码保存.可以保存多个vps登陆信息,免去每次输入的烦恼. 二. ...
- http請求瀏覽器的緩存機制
轉載自:http://kb.cnblogs.com/page/73901/ 流程 当资源第一次被访问的时候,HTTP头部如下 (Request-Line) GET /a.html HTTP/1.1 H ...
- OPenGL中的缓冲区对象
引自:http://blog.csdn.net/mzyang272/article/details/7655464 在许多OpenGL操作中,我们都向OpenGL发送一大块数据,例如向它传递需要处理的 ...
- Android OpenGL ES(十四)gl10方法解析
Android 支持 OpenGL 列表 1.GL 2.GL 10 3.GL 10 EXT 4.GL 11 5.GL 11 EXT 6.GL 11 ExtensionPack 我们将使用 GL10 这 ...
- Tiny210编译和烧写u-boot步骤
当有多个交叉编译器是,不方便设置环境变量时,可以在编译命令中指定交叉编译器,具体如下: make ARCH=arm CROSS_COMPILE=/opt/FriendlyARM/toolschain/ ...
- C++的精髓——虚函数
虚函数为了重载和多态的需要,在基类中是由定义的,即便定义是空,所以子类中可以重写也可以不写基类中的函数! 纯虚函数在基类中是没有定义的,必须在子类中加以实现,很像java中的接口函数! 虚函数 引入原 ...