‘壹’ python logging.conf是什么类型文件
下面的函数用于配置logging模块,它们位于logging.config模块中。你可以使用这些函数来配置,也可以在logging或是logging.handlers中声明它们来配置。
logging.config.dictConfig(config)
从dictionary中获取logging配置
logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)
从指定的fname的配置文件中读取logging配置文件
该函数可以在应用程序中多次调用
logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT)
在指定端口启动socket server并侦听新配置
logging.config.stopListening()
关闭先前正在侦听的server
Configuration file format
被fileConfiguration()所理解的配置文件格式基于configparser功能。配置文件必须包含[loggers], [handlers]和[formatters],它们分别代表日志文件中定义的每种类型的实体。对这3种实体,后面有一个单独的section来定义该实体如何配置。
因此,[loggers]节中名为log01的logger,相关的配置文件细节在[logger_log01]节中定义。类似地,[handlers]节中名为
hand01的handler将在[handler_hand01]节中声明,[formatters]节中的form01将在[formatter_form01]声明。root logger配置必须在[logger_root]节声明。
注意:fileConfig() API比dictConfig()旧,并不包含logging某些方面的功能。建议以后尽量使用dictConfig API。
配置文件的例子如下:
[loggers]
keys=root,log02,log03,log04,log05,log06,log07
[handlers]
keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
[formatters]
keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
root logger必须指定一个级别和handlers列表。示例如下:
[logger_root]
level=NOTSET
handlers=hand01
其中level可以是DEBUG, INFO, WARNING, ERROR, CRITICAL or NOTSET之一,仅对root logger来说,NOTSET意味着所有的log message
都会记录。对非root的logger,强制要求一些额外信息,比如
[logger_parser]
level=DEBUG
handlers=hand01
propagate=1
qualname=compiler.parser
当一个非root的logger中level被配置为NOSET,它将通过上一级的logger来确定当前logger的有效级别。propagete为1表示message必须传播到上一级logger中,为0表示不传。qualname表示该logger的层级channel名称,这就是说,应用程序使用该名称可以得到该logger对象。
handler类型很多,主要有StreamHandler,FileHandler,NullHandler,SysLogHandler,HTTPHandler等
handler节对应的配置示例如下:
[handler_hand01]
class=StreamHandler
level=NOTSET
formatter=form01
args=(sys.stdout,)
class表示该handler在logging包命名空间中的类名,level表示logger的级别,NONSET表示要记录所有日志。
formatter表示该handler的formatter的键名,假如空白的话,就使用默认值logging._defaultFormatter。假如formatter指定了该名字,必须在对应的section声明。args字段是handler类的构造函数的变量列表,参考相关handler构造函数,或者下面的例子,去观察通常的元素是如何构造的。比如:
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form02
args=('python.log', 'w')
下面是formatter的配置
[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
format字段是全局格式字符串,datefmt是strftime()兼容的date/time格式字符串,为空时使用默认的ISO8601格式,比如2003-01-23 00:29:50,411,class字段表示formatter的类名,
日志级别如下:
Level Numeric value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0
logging.handlers解读
logging模块中定义了这3个handler:StreamHandler, FileHandler and NullHandler
其它的handler都在logging.handler中定义,一并说明如下:
StreamHandler
该类位于logging包,将logging output输出到流中,比如sys.stdout,sys.stderr或任何支持write()和flush()方法的类文件对象
class logging.StreamHandler(stream=None)
假如指定了stream名称,日志将输出到流实例中,否则,日志输出到sys.stderr
FileHandler
该类位于logging包,将logging output输出到磁盘文件中,文件默认无限增长
class logging.FileHandler(filename, mode='a', encoding=None, delay=False)
打开指定的文件并记录日志,假如mode没有设置,默认使用'a'表示追加日志到文件中。
NullHandler
该对象什么也不处理
WatchedFileHandler
一个FileHandler实例,监视日志文件的变化,假如文件变化了,它会关闭并重新打开,不建议在Windows下使用
文件的变化可以发生,当应用程序使用newsyslog和logrotate来实现日志文件的回滚时。这个handle是在Unix/Linux下面,监视文件是否改变。(一个文件认为改变了,假如它的device厚实inode已经改变),将旧的文件关闭,这个流打开。
class logging.handlers.WatchedFileHandler(filename[, mode[, encoding[, delay]]])
指定的文件被打开,用来记录日志,假如mode未指示,默认使用a
RotatingFileHandler
支持磁盘文件的回滚
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
你可以使用 maxBytes和backupCount值去让日志文件在预设大小时回滚。只要日志文件在长度上接近maxBytes时,就会关闭旧日志文件,打开一个新的日志文件,实现回滚。假如maxBytes或backupCount为0,回滚不会发生。假如backupCount非零,系统会备份旧文件,文件名后加‘.1’, ‘.2’ 。比如,日志文件名为app.log,backupCount为5,将会得到app.log, app.log.1, app.log.2, 直到app.log.5这6个文件。写入日志的文件总是app.log,当这个文件填满时,就关闭它并重命名为app.log.1, 假如还存在app.log.1, app.log.2等文件,就逐一改名为app.log.2, app.log.3等等。
TimedRotatingFileHandler
支持在指定时间段内回滚日志
class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
回滚基于when和interval设置,when指定interval的类型,参见下表,大小写不敏感,默认按小时回滚
Value Type of interval
'S' Seconds
'M' Minutes
'H' Hours
'D' Days
'W0'-'W6' Weekday (0=Monday)
'midnight' Roll over at midnight
回滚扩展名使用strftime format %Y-%m-%d_%H-%M-%S或其头部子字符串,当使用基于weekday的回滚时,W0表示周一,……,W6表示周日,interval的值不会用到
backupCount表示备份数,当日志很多时,新日志会覆盖旧日志,删除逻辑使用interval值去决定删除哪些日志文件
utc为true,表示使用UTC时间,否则使用本地时间
SocketHandler
通过网络套接字输出日志,SocketHandler类的基类使用TCP socket
class logging.handlers.SocketHandler(host, port)
向指定地址和端口的远程主机发送日志
DatagramHandler
继承自基类SocketHandler类,使用UDP socket发送日志message
class logging.handlers.DatagramHandler(host, port)
SysLogHandler
发送日志到远程或是本地unix syslog
class logging.handlers.SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
NTEventLogHandler
发送日志消息到本地Windows NT, Windows 2000 or Windows XP event log
class logging.handlers.NTEventLogHandler(appname, dllname=None, logtype='Application')
SMTPHandler
通过SMTP将日志消息发送到email address
MemoryHandler
支持将日志message缓存到内存中,周期性刷新日志到target handler
class logging.handlers.BufferingHandler(capacity)
class logging.handlers.MemoryHandler(capacity, flushLevel=ERROR, target=None)
HTTPHandler
使用GET或是POST,将日志message发送到web server
class logging.handlers.HTTPHandler(host, url, method='GET')
‘贰’ python log中文乱码
Python log出现中文乱码的解决方法:修改“handle”的“encode”参数为“utf-8”,即在源码中修改“encoding='utf-8'”。
python log写入中文乱码,直接修改handle的encode参数为utf-8
即在源码中修改encoding='utf-8',因为 logging.basicConfig() 配置时实际上是用到了4大组件,只不过给了默认值,在loging.FileHandler()方法中默认是这样的。
只需在源码中修改。
推荐课程:零基础入门学习Python(小甲鱼)
‘叁’ python logging 意图:根据运行的不同时间来创建log文件,而不是固定命名,如:2013-06-13.log
原生loggging类+TimedRotatingFileHandler类实现按dayhoursecond切分
importlogging
fromlogging.
log=logging.getLogger(loggerName)
formatter=logging.Formatter('%(name)-12s%(asctime)slevel-%(levelname)-8sthread-%(thread)-8d%(message)s')#每行日志的前缀设置
fileTimeHandler=TimedRotatingFileHandler(BASIC_LOG_PATH+filename,"S",1,10)
fileTimeHandler.suffix="%Y%m%d.log"#设置切分后日志文件名的时间格式默认filename+"."+suffix如果需要更改需要改logging源码
fileTimeHandler.setFormatter(formatter)
logging.basicConfig(level=logging.INFO)
fileTimeHandler.setFormatter(formatter)
log.addHandler(fileTimeHandler)
try:
log.error(msg)
exceptException,e:
print"writeLogerror"
finally:
log.removeHandler(fileTimeHandler)
值 interval的类型
S 秒
M 分钟
H 小时
D 天
W 周
midnight 在午夜
‘肆’ python 使用logging,生成的log文件是什么编码格式脚本的编码格式决定系统的编码格式决定
log的文件当然是byte格式。或者是无格式的。汉字编码取决于你自己设定的类型。
#coding:utf-8这个东西,只在python2下有效果。还需要编程器配合。你使用python自带的idle当然是没有问题的。
log中的汉字是一定要编码的。不编码你存贮不了。
编辑器本身的缺省编码格式要与你的源代码编码一致,不然看到的就是乱码。如果是idle,它会根据python脚本自动识别。
不过有些编辑器是有些不智能的。它不能理解python脚本第一行的提示。所以有时候,觉着很别扭自己要手工保持编辑器的编码与源码一致。还需要维护那个coding:utf-8
不过python3已将这一句去掉了。源代码全部要求使用utf-8编码(也许是utf-16),我很少用python3
‘伍’ 如何动态修改python logging配置文件
配置文件:
#Configuration for log output
#Naiveloafer
#2012-06-04
[loggers]
keys=root,xzs
[handlers]
keys=consoleHandler,fileHandler,rotatingFileHandler
[formatters]
keys=simpleFmt
[logger_root]
level=DEBUG
#handlers=consoleHandler
#handlers=fileHandler
handlers=rotatingFileHandler
[logger_xzs]
level=DEBUG
handlers=rotatingFileHandler
qualname=xzs
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFmt
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFmt
args=("../log/p2pplayer.log", "a")
[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFmt
args=("../log/p2pplayer.log", "a", 20*1024*1024, 10)
[formatter_simpleFmt]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s - [%(filename)s:%(lineno)s]
datefmt=
测试代码:
def log_test02():
import logging
import logging.config
CONF_LOG = "../conf/p2pplayer_logging.conf"
logging.config.fileConfig(CONF_LOG); # 采用配置文件
logger = logging.getLogger("xzs")
logger.debug("Hello xzs")
logger = logging.getLogger()
logger.info("Hello root")
if __name__ == "__main__":
log_test02()
输出:
2012-06-04 15:28:05,751 - xzs - DEBUG - Hello xzs - [xlog.py:29]
2012-06-04 15:28:05,751 - root - INFO - Hello root - [xlog.py:32]
具体就不详细说明了,总之是能够运行的,这个文件配置搞了我两天时间。
特别是class=XXXX要注意!!!
‘陆’ python之配置日志的几种方式
1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数;
2)创建一个日志配置文件,然后使用fileConfig()函数来读取该文件的内容;
3)创建一个包含配置信息的dict,然后把它传递个dictConfig()函数;
‘柒’ python中log info 是什么文件
a. 利用sys.stdout将print行导向到你定义的日志文件中,例如:
import sys# make a of original stdout routestdout_backup = sys.stdout# define the log file that receives your log infolog_file = open("message.log", "w")# redirect print output to log filesys.stdout = log_fileprint "Now all print info will be written to message.log"# any command line that you will execute...
log_file.close()# restore the output to initial patternsys.stdout = stdout_backupprint "Now this will be presented on screen"
b. 利用logging模块(规范化日志输出,推荐!!)
由于logging模块的功能比较多,下面就放一些文档里介绍的简单的例子,更详细具体的用法请戳这里
需求
最好的实现方式
故障调查或者状态监测 logging.info()或logging.debug()(后者常用于针对性检测诊断的目的)
特定运行事件发出警告 logging.warning()
报告错误抑制不出发异常(常见于长时间运行的服务器进程的错误处理程序) logging.error(), logging.exception()或者logging.critical()
而以下是根据事件的严重性程度而应采取的logging函数的建议:
程度
使用场景
DEBUG 获得诊断问题是具体的信息
INFO 确认程序是否按正常工作
WARNING 在程序还正常运行时获取发生的意外的信息,这可能会在之后引发异常(例如磁盘空间不足)
ERROR 获取程序某些功能无法正常调用这类严重异常的信息
CRITICAL 获取程序无法继续运行的这类最严重异常信息
默认的等级是WARNING,也就是说logging函数在没有特别配置的前提下只追踪比WARNING程度更严重的异常。
下面就用一些例子来具体说明如何用logging函数记录日志信息:
# this is a simple exampleimport logging# define the log file, file mode and logging levellogging.basicConfig(filename='example.log', filemode="w", level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
查看example.log文件可以看到以下信息:
DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too
从多个文件记录日志
# myapp.pyimport loggingimport mylibdef main():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
mylib.do_something()
logging.info('Finished')if __name__ == '__main__':
main()
# mylib.pyimport loggingdef do_something():
logging.info('Doing something')
输出的信息为
INFO:root:StartedINFO:root:Doing somethingINFO:root:Finished
改变默认输出信息的格式
import logging# output format: output time - logging level - log messageslogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logging.warning('This message will appear in python console.')
在python console中直接打印以下输出:
2016-8-2 2:59:11, 510 - WARNING - This message will appear in python console
logging高级用法
可以通过构建logger或者读取logging config文件对logging函数进行任意配置。
构建logger法
以上程序结果会输出到python console中:
读取配置文件法
其中logging.conf文件格式为:(其实就是将前一种方法的各项配置参数写到logging.conf文件中)
与前面一样,上述文件输出结果为:
‘捌’ python logging 源文件在哪
首先,想到的是更改logging.basicConfig(filename=logfilename)参数,来实现变更日志文件名的目的。编写代码如下:
log_fmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
for i in range(1,4):
filename = str.format('mylog%d.txt' % i)
logging.basicConfig(format=log_fmt, level=logging.DEBUG, filename=filename)
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')12345678
运行结果没有达到预期的效果,只有日志文件mylog1.txt被创建,mylog2.txt和mylog3.txt都未被创建,连续3次的输出的内容都写入mylog1.txt中。说明logging.basicConfig()设置属性具有全局性,第一次设置之后,之后再设置将不再生效。查看官方文档,也确实是如此。
‘玖’ python中log文件和txt文件的区别
没区别啊。
log.txt是txt文件。
run.log是log文件。但两个只是后缀格式的不同。都是普通文本文件。没什么特别的。
log是日志的意思
‘拾’ Python 将运行结果保存到log文件中遇到的问题
这个简单啊。通过管道输出到另一个程序里去,另外一个程序同时打印并输出到out.log
这是我常用的办法。
还有一个笨办法,用自己的myprint代替所有的print语句。这样你可以同时输出到屏幕与文件了。
第三个办法是通过logging。这个模块支持多个listener,可以同时输出到屏幕与文件以及网络。