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.)
這段話中也提出了另外一種解決方案。