導航:首頁 > 編程語言 > 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相關的資料

熱點內容
大尺很色床戲電影 瀏覽:432
鄭州阿里程序員 瀏覽:131
韓國愛情推理片全部復制 瀏覽:462
台灣影視國語 瀏覽:571
穿越之我那三千個兄弟訓誡 瀏覽:486
連母親都收的小說 瀏覽:839
葉子媚演過尺較大的電影在線觀看 瀏覽:832
app反感怎麼解決 瀏覽:332
極光設置app是什麼 瀏覽:79
app廣告怎麼賺錢 瀏覽:917
男主被系統控制的小說下載 瀏覽:951
鈦2電影高清完整版 瀏覽:440
linux啟動項目命令 瀏覽:531
乳山迷霧txt全文閱讀全文小說 瀏覽:885
vm同步命令 瀏覽:14
安卓轉移到ios王者榮耀怎麼登 瀏覽:955
工業壓縮機品牌 瀏覽:182
蘋果系統怎麼更改app的圖標 瀏覽:668
泰劇女同電影 瀏覽:435
人造變異女的電影 瀏覽:237