python中logging
❶ python如何将logging类作为一个模块给其他模块使用
写个装饰器,里面定义logging的配置
a1 和a2 上面调用装饰器
❷ python 使用logging,生成的log文件是什么编码格式脚本的编码格式决定系统的编码格式决定
log的文件当然是byte格式。或者是无格式的。汉字编码取决于你自己设定的类型。
#coding:utf-8这个东西,只在python2下有效果。还需要编程器配合。你使用python自带的idle当然是没有问题的。
log中的汉字是一定要编码的。不编码你存贮不了。
编辑器本身的缺省编码格式要与你的源代码编码一致,不然看到的就是乱码。如果是idle,它会根据python脚本自动识别。
不过有些编辑器是有些不智能的。它不能理解python脚本第一行的提示。所以有时候,觉着很别扭自己要手工保持编辑器的编码与源码一致。还需要维护那个coding:utf-8
不过python3已将这一句去掉了。源代码全部要求使用utf-8编码(也许是utf-16),我很少用python3
❸ 怎么用logging调试python程序
Logging模块构成
组成
主要分为四个部分:
Loggers:提供应用程序直接使用的接口
Handlers:将Loggers产生的日志传到指定位置
Filters:对输出日志进行过滤
Formatters:控制输出格式
模块使用示例
简单例子
打印输出
In [5]: import logging
In [6]: logging.warning("FBI warning")
WARNING:root:FBI warning
In [7]: logging.info("information")
# 没有打印是因为默认级别是warning
❹ python程序中logging怎么用
简单将日志打印到屏幕:
[python] view plain
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
输出:
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
可见,默认情况下Python的
logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级
CRITICAL > ERROR > WARNING > INFO > DEBUG >
NOTSET),默认的日志格式为日志级别:Logger名称:用户输出消息。
灵活配置日志级别,日志格式,输出位置
[python] view plain
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w')
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
查看输出:
cat /tmp/test.log
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message
Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message
Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message
Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message
Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message
可见在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(mole)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
❺ 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文件,但发现控制台的信息会出现重复打印
loggin模块需要进行很多封装才好用,你这种情况应该是初始化有问题,给你贴一段代码你自己照抄下来用用试试。
#-*-coding:UTF8-*-
#
importos
importlogging
classLogger(object):
'''
@summary:日志处理对象,对logging的封装
'''
def__init__(self,name='Logger'):
self.logger=logging.getLogger(name)
self.init_logger()
definit_logger(self):
self.logger.setLevel(logging.DEBUG)
#屏幕输出日志
stream=logging.StreamHandler()
stream.setLevel(logging.INFO)
#日志样式
fm_stream=logging.Formatter("[ 33[1;%(colorcode)sm%(levelname)s 33[0m%(asctime)s%(myfn)s:%(mylno)d:%(myfunc)s%(mymole)s]%(message)s","%m-%d%H:%M:%S")
stream.setFormatter(fm_stream)
self.logger.addHandler(stream)
defupdate_kwargs(self,kwargs,colorcode):
try:
fn,lno,func=self.logger.findCaller()
fn=os.path.basename(fn)
exceptExceptionasddd:
fn,lno,func="(unknownfile)",0,"(unknownfunction)"
ifnot"extra"inkwargs:
kwargs["extra"]={}
kwargs["extra"]["myfn"]=fn
kwargs["extra"]["mylno"]=lno
kwargs["extra"]["myfunc"]=func
kwargs["extra"]["colorcode"]=colorcode
kwargs["extra"]["mymole"]=""
defdebug(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"0")#原色
self.logger.debug(msg,*args,**kwargs)
definfo(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"32")#绿色
self.logger.info(msg,*args,**kwargs)
defwarning(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"33")#黄色
self.logger.warning(msg,*args,**kwargs)
deferror(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"31")#红色
self.logger.error(msg,*args,**kwargs)
defcritical(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"31")#红色
self.logger.critical(msg,*args,**kwargs)
使用方法:
fromloggerimportLogger
Logger().info('xxxxx')
Logger().warning('xxxxx')
Logger().error('xxxxx')
❼ python 中 logging.info是干吗的
logging是python的日志库,是一个类
info是logging的一个属性
logging.info是输出日志的信息
logging.info('输出信息')
❽ python logging 定向不输出到屏幕
简答:你自己貌似自相矛盾:
既不让信息输出到standard i/o 也不让输出到文件,哪你想让其输出到哪里???
所以,你还是把你的问题搞清楚了,再来问吧。
正常的做法,是设置某个输出等级,高于某个等级,就不输出到标准io。
可以支持同时输出到对应的文件。
详细用法,我早就写好教程了,需要的自己去看:
【整理】Python中的logging模块的使用(可以实现同时输出信息到cmd终端窗口和log文件(txt)中)
(此处不给贴地址,自己用google搜标题,即可找到帖子地址的)
❾ python logging怎么使用
import logging
然和设置日志的最低警告级别,显示方式,返回句柄
❿ python 多线程logger问题
因为logging是threadsafe的,但不是process-safe(应该没有这个词儿,只是为了便于理解)的。这段代码就是多个进程共同操作一个日志文件。这种情况下,logging的行为就很难说了。
我测试了一下,日志中大概几百行。而且,可以看到一些顺序错乱现象:
Fri, 08 Aug 2014 01:19:38 logging_in_multithread.py[line:40] theadWorking ERROR 2
FFri, 08 Aug 2014 01:19:36 logging_in_multithread.py[line:40] theadWorking ERROR 11(注意这里的FFri)
把代码这样改:
fornuminrange(processNum):
p=Process(target=processWorking,args=('2',))
processs.append(p)
p.start()
p.join()
还有其他方法,比如:为logging实现一个FileHandler,以使logging在multiple process的环境下也能正常工作。这是我从网上了解到的做法,自己还没实践过。
Python Manual中logging Cookbook中有这么一段话:
Logging to a single file from multiple processes
Although logging is thread-safe, and logging to a single file from multiple threads in a single process is supported, logging to a single file from multiple processes is not supported, because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a SocketHandler, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.)
这段话中也提出了另外一种解决方案。