导航:首页 > 编程语言 > pythonloginfo

pythonloginfo

发布时间:2022-09-01 20:26:17

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)s33[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 意图:根据运行的不同时间来创建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配置文件

配置文件:

#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中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函数进行任意配置。

⑤ 怎么把python运行结果保存到log

python test.py >1.log
将输出结果记录到1.log(覆盖写入)
python test.py >>1.log
将输出结果追加到1.log(每次追加)

⑥ 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读取CSV文件方法

#!/usr/bin/python
#-*-coding:UTF-8-*-

fromLogimportLoginfo
importcgi,os,csv,sys,re
reload(sys)
sys.setdefaultencoding('utf8')

print"Content-Type:text/htmlcharset=utf-8 "

fileitem=''
defget_cgi_file():
''''''
globalfileitem,device_id,maxDeviceID,maxDriverID,channelid,ChannelDeviceType
form=cgi.FieldStorage()
#获取文件名
fileitem=form['filename1']
#检测文件是否上传
iffileitem.filename:
#去掉文件路径,获取文件名称
fn=os.path.basename(fileitem.filename)
open(global_var.uploadfile_path,'wb').write(fileitem.file.read())
#message='文件"'+fn+'"上传成功!'
#printmessage
else:
message='没有文件上传!'
printmessage

defconvert_gbk2utf8():
data_list=[]
fd=open(global_var.uploadfile_path,'rb')
csvfd=csv.reader(fd)
forc1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14incsvfd:
c1_u=c1.decode('gb2312').encode('utf-8')
c2_u=c2.decode('gb2312').encode('utf-8')
c3_u=c3.decode('gb2312').encode('utf-8')
c4_u=c4.decode('gb2312').encode('utf-8')
c4_u=c4.decode('gb2312').encode('utf-8')
c5_u=c5.decode('gb2312').encode('utf-8')
c6_u=c6.decode('gb2312').encode('utf-8')
c7_u=c7.decode('gb2312').encode('utf-8')
c8_u=c8.decode('gb2312').encode('utf-8')
c9_u=c9.decode('gb2312').encode('utf-8')
c10_u=c10.decode('gb2312').encode('utf-8')
c11_u=c11.decode('gb2312').encode('utf-8')
c12_u=c12.decode('gb2312').encode('utf-8')
c13_u=c13.decode('gb2312').encode('utf-8')
c14_u=c14.decode('gb2312').encode('utf-8')
data_row_list=[c1_u,c2_u,c3_u,c4_u,c5_u,c6_u,c7_u,c8_u,c9_u,c10_u,c11_u,c12_u,c13_u,c14_u]
data_list.append(data_row_list)
fd.close()
#log.write_debug(data_list)
returndata_list

defanaly_csv_file(data_list):
forrownuminrange(len(data_list)):
ifrownum==0:
attrib=data_list[rownum]
else:
foriinrange(len(attrib)):
#这里循环取数据,依据是列名
ifattrib[i]=='你的列名':
printdata_list[rownum][i]

if__name__=='__main__':
log=Loginfo.Loginfo()
get_cgi_file()
try:
data_list=convert_gbk2utf8()
exceptExceptionase:
print("正在导入的表格列数不对,请检查!")
deleteDevice()

删了一些函数,这样应该可以看得懂吧,c14_u是列,有多少列就多少个,这是转换编码。analy_csv_file(data_list)里面对拿到的文件做处理

⑧ python 读取日志文件

#-*-coding:utf-8-*-


withopen('log.txt','r')asf:
foriinf:
ifdt.strftime(dt.now(),'%Y-%m-%d')ini:
#判断是否当天时间
if'ERROR'iniand'atcom.mytijian'ini:
#判断此行中是否含有'ERROR'及'atcom.mytijian'
if((dt.now()-dt.strptime(i.split(',')[0],'%Y-%m-%d%H:%M:%S')).seconds)<45*60:
#判断时间是为当前45分钟内
printi

⑨ 请教python 如何分日志级别分文件输出

利用sys.stdout将print行导向到你定义的日志文件中,例如:
import sys
# make a of original stdout route
stdout_backup = sys.stdout
# define the log file that receives your log info
log_file = open("message.log", "w")
# redirect print output to log file
sys.stdout = log_file
print "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 pattern
sys.stdout = stdout_backup
print "Now this will be presented on screen"

阅读全文

与pythonloginfo相关的资料

热点内容
云空间在哪个文件夹 浏览:924
编程游戏小猫抓小鱼 浏览:782
安卓dosbox怎么打开 浏览:772
服务器无影响是怎么回事 浏览:950
比德电子采购平台加密 浏览:200
加密货币400亿 浏览:524
植发2次加密 浏览:44
vc6查看编译的错误 浏览:595
心理大全pdf 浏览:1002
区域链加密币怎么样 浏览:343
查找命令符 浏览:95
压缩工具zar 浏览:735
白盘怎么解压 浏览:475
辰语程序员学习笔记 浏览:47
程序员被公司劝退 浏览:523
java三子棋 浏览:693
加密空间怎么强制进入 浏览:345
ug分割曲线命令 浏览:209
学码思程序员 浏览:610
自考云学习app为什么登不上 浏览:410