loggingpython3
Ⅰ 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 意圖:根據運行的不同時間來創建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怎麼用
簡單將日誌列印到屏幕:
[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,看上去沒有問題,我懷疑是 log config 的問題
importlogging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s%(filename)s[line:%(lineno)d]%(message)s',
datefmt='%a,%d%b%Y%H:%M:%S',
filename='log.log',
filemode='w')
classA:
def__init__(self):
logging.info('A')
__c=C()
__d=D()
classB:
def__init__(self):
logging.info('B')
classC:
def__init__(self):
logging.info('C')
__e=E()
__f=F()
classD:
def__init__(self):
logging.info('D')
classE:
def__init__(self):
logging.info('E')
classF:
def__init__(self):
logging.info('F')
if__name__=='__main__':
a=A()
b=B()
Ⅵ python logging怎麼使用
import logging
然和設置日誌的最低警告級別,顯示方式,返回句柄
Ⅶ 怎麼用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
Ⅷ 操作資料庫的時候怎麼生成日誌文件 python3
日誌可以用來記錄應用程序的狀態、錯誤和信息消息,也經常作為調試程序的工具。它的重要性就不多說了,直接進入正題。
python提供了一個標準的日誌介面,就是logging模塊。日誌級別有DEBUG、INFO、WARNING、ERROR、CRITICAL五種。
首先來看logging簡單的使用方法。
這一看到此圖中使用了debug()、info()、warning()、error()、critical()五個方法,這五個方法分別用來記錄DEBUG、INFO、WARNING、ERROR、CRITICAL級別的日誌。但是你會發現debug()和info()方法沒有顯示任何信息,這是因為默認的日誌級別是ERROR ,所以低於此級別的日誌不會記錄。你還可能會疑惑輸出來的日誌怎麼這樣子?別急,往下看,慢慢來解釋。
下面我們來看怎麼修改一下日誌級別。
如圖上所示,可以使用basicConfig()方法,修改日誌級別,logging.DEBUG,logging.INFO,logging.WARNING,logging.ERROR,logging.CRITICAL分別代表著那五中日誌級別。可以看到圖中日誌級別設為INFO,那麼INFO級別以上的日誌都會被記錄。
下面再看下怎麼修改日誌的輸出格式。
查看下執行結果:
這個示例內容可能有點多了,沒關系,我們一點一點來。
首先程序中:
log_format = '%(filename)s [%(asctime)s] [%(levelname)s] %(message)s'
#這條是定義日誌格式的一個變數。顯示的條目可以是以下內容:
%(levelname):日誌級別的名字格式
%(levelno)s:日誌級別的數字表示
%(name)s:日誌名字
%(funcName)s:函數名字
%(asctime):日誌時間,可以使用datefmt去定義時間格式,如上圖。
%(pathname):腳本的絕對路徑
%(filename):腳本的名字
%(mole):模塊的名字
%(thread):thread id
%(threadName):線程的名字
logging.basicConfig(format=log_format,datefmt='%Y-%m-%d %H:%M:%S %p',level=logging.DEBUG) #設置日誌輸出格式和級別。
上面的示例都是將日誌輸出到屏幕上,能不能寫到一個日誌文件中呢?答案當然是肯定的,來看:
看下執行結果:
看了吧,日誌的設置都是使用basicConfig()方法,需要注意的是,日誌寫入文件的默認方式是『a』,也就是追加,如果想覆蓋文件,則使用如上圖那樣,使用filemode='w'。
以上是logging模塊最常用的了,基本上就夠用了。但是如果你覺得這些還不夠的話,看我下一篇博客。會講Logger、Handler、Formatter對象,logging模塊更高級的用法用法。
Ⅸ python如何將logging類作為一個模塊給其他模塊使用
寫個裝飾器,裡面定義logging的配置
a1 和a2 上面調用裝飾器