logging鏃ュ織妯″潡
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了logging鏃ュ織妯″潡相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/function' title='function'>function
nap ESS .so Matter __name__ 杩涚▼ 澶囦唤 time涓€銆乴ogging妯″潡绠€浠?/h3>
logging妯″潡鏄疨ython鍐呯疆鐨勬爣鍑嗘ā鍧楋紝涓昏鐢ㄤ簬杈撳嚭杩愯鏃ュ織锛屽彲浠ヨ缃緭鍑烘棩蹇楃殑绛夌骇銆佹棩蹇椾繚瀛樿矾寰勩€佹棩蹇楁枃浠跺洖婊氱瓑锛涚浉姣攑rint锛屽叿澶囧涓嬩紭鐐癸細
- 鍙互閫氳繃璁剧疆涓嶅悓鐨勬棩蹇楃瓑绾э紝鍦╮elease鐗堟湰涓彧杈撳嚭閲嶈淇℃伅锛岃€屼笉蹇呮樉绀哄ぇ閲忕殑璋冭瘯淇℃伅锛?/li>
- print灏嗘墍鏈変俊鎭兘杈撳嚭鍒版爣鍑嗚緭鍑轰腑锛屼弗閲嶅奖鍝嶅紑鍙戣€呬粠鏍囧噯杈撳嚭涓煡鐪嬪叾瀹冩暟鎹紱logging鍒欏彲浠ョ敱寮€鍙戣€呭喅瀹氬皢淇℃伅杈撳嚭鍒颁粈涔堝湴鏂癸紝浠ュ強鎬庝箞杈撳嚭
浜屻€乴ogging妯″潡浣跨敤
2.1 鍩烘湰浣跨敤
閰嶇疆logging鐨勫熀鏈厤缃紝鍒版帶鍒跺彴杈撳嚭鏃ュ織锛?/p>
import logging logging.basicConfig(level = logging.INFO, format = 鈥?/span>%(asctime)s - %(name)s - %(levelname)s - %(message)s鈥?/span>) logger = logging.getLogger(__name__) logger.info("Start pribnt log") logger.debug("Do something") logger.warning("Something maybe fail") logger.info("Finish")
杩愯鏃舵帶鍒跺彴杈撳嚭锛?/p>
2018-09-26 14:19:27,895 - __main__ - INFO - Start print log 2018-09-26 14:19:27,895 - __main__ - WARNING - Something maybe fail 2018-09-26 14:19:27,895 - __main__ - INFO - Finish
logging涓彲浠ラ€夋嫨寰堝娑堟伅绾у埆锛屽debug銆乮nfo銆亀arning銆乪rror浠ュ強critical銆傞€氳繃璧嬩簣logger鎴栬€卙andler涓嶅悓绾у埆锛屽紑鍙戣€呭氨鍙互杈撳嚭閿欒淇℃伅鍒扮壒瀹氱殑璁板綍鏂囦欢锛屾垨鑰呭湪璋冭瘯鏃跺彧璁板綍璋冭瘯淇℃伅銆?/p>
渚嬪锛屾垜浠皢logger鐨勭骇鍒慨鏀逛负DEBUG锛岀湅杈撳嚭缁撴灉銆?/p>
logging.basicConfig(level = logging.DEBUG,format = 鈥?/span>%(asctime)s - %(name)s - %(levelname)s - %(message)s鈥?/span>)
鎺у埗鍙拌緭鍑猴紝鍙互鍙戠幇杈撳嚭浜哾ebug鐨勪俊鎭€?/p>
2018-09-26 14:23:38,786 - __main__ - INFO - Start print log 2018-09-26 14:23:38,786 - __main__ - DEBUG - Do something 2018-09-26 14:23:38,786 - __main__ - WARNING - Something maybe fail 2018-09-26 14:23:38,786 - __main__ - INFO - Finish
logging.basicConfig鍑芥暟鐨勫悇涓弬鏁帮細
filename锛氭寚瀹氭棩蹇楁枃浠跺悕锛?
filemode锛氬拰file鍑芥暟鎰忎箟鐩稿悓锛屾寚瀹氭棩蹇楁枃浠剁殑鎵撳紑妯″紡锛?lsquo;w’鎴栬€?lsquo;a’锛?
format锛氭寚瀹氳緭鍑虹殑鏍煎紡鍜屽唴瀹癸紝format鍙互杈撳嚭寰堝鏈夌敤鐨勪俊鎭€?br />datefmt锛氭寚瀹氭椂闂存牸寮忥紝鍚宻trftime()锛?br />level锛氳缃棩蹇楃骇鍒紝榛樿涓簂ogging.WARNNING锛?br />stream锛氭寚瀹氭棩蹇楃殑杈撳嚭娴侊紝鍙互鎸囧畾杈撳嚭鍒皊ys.stderr锛宻ys.stdout鎴栬€呮枃浠讹紝榛樿杈撳嚭鍒皊ys.stderr锛屽綋stream鍜宖ilename鍚屾椂鎸囧畾鏃讹紝sreaam琚拷鐣ャ€?br />
format鍙傛暟锛氫綔鐢? %(levelno)s锛氭墦鍗版棩蹇楃骇鍒殑鏁板€? %(levelname)s锛氭墦鍗版棩蹇楃骇鍒殑鍚嶇О %(pathname)s锛氭墦鍗板綋鍓嶆墽琛岀▼搴忕殑璺緞锛屽叾瀹炲氨鏄痵ys.argv[0] %(filename)s锛氭墦鍗板綋鍓嶆墽琛岀▼搴忓悕 %(funcName)s锛氭墦鍗版棩蹇楃殑褰撳墠鍑芥暟 %(lineno)d锛氭墦鍗版棩蹇楃殑褰撳墠琛屽彿 %(asctime)s锛氭墦鍗版棩蹇楃殑鏃堕棿 %(thread)d锛氭墦鍗扮嚎绋婭D %(threadName)s锛氭墦鍗扮嚎绋嬪悕绉? %(process)d锛氭墦鍗拌繘绋婭D %(message)s锛氭墦鍗版棩蹇椾俊鎭?/pre>
2.2 灏嗘棩蹇楀啓鍒版枃浠?/h4>
2.2.1 灏嗘棩蹇楀啓鍏ュ埌鏂囦欢
璁剧疆logging锛屽垱寤轰竴涓狥ileHendle锛屽苟瀵硅緭鍑烘秷鎭殑鏍煎紡杩涜璁剧疆锛屽皢鍏舵坊鍔犲埌logger锛岀劧鍚庡皢鏃ュ織鍐欏叆鍒版寚瀹氱殑鏂囦欢涓€?/p>
import logging logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail") logger.info("Finish")
log.txt涓殑鏃ュ織鏁版嵁涓猴細
2018-09-26 15:01:14,201 - __main__ - INFO - Start print log 2018-09-26 15:01:14,203 - __main__ - WARNING - Something maybe fail 2018-09-26 15:01:14,203 - __main__ - INFO - Finish
2.2.2 灏嗘棩蹇楀悓鏃惰緭鍑哄埌鎺у埗鍙板拰鏃ュ織鏂囦欢
logger涓坊鍔燬treamHandler锛屽彲灏嗘棩蹇楄緭鍑哄埌鎺у埗鍙?/p>
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(鈥?(asctime)s - %(name)s - %(levelname)s - %(message)s鈥?
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
杩欐牱鍦╨og.txt鍜屾帶鍒跺彴閮藉彲浠ョ湅鍒帮細
2018-09-26 15:20:17,000 - __main__ - INFO - Start print log 2018-09-26 15:20:17,002 - __main__ - WARNING - Something maybe fail. 2018-09-26 15:20:17,002 - __main__ - INFO - Finish
鍙互鍙戠幇锛宭ogging鏈変竴涓棩蹇楀鐞嗙殑涓诲璞★紝鍏朵粬鏂瑰紡閮芥槸閫氳繃addHandler娣诲姞杩涘幓锛宭ogging涓寘鍚玥andler涓昏鏈変互涓嬪嚑绉嶏細
handler鍚嶇О锛氫綅缃紱浣滅敤 StreamHandler锛歭ogging.StreamHandler锛涙棩蹇楄緭鍑哄埌娴侊紝鍙互鏄痵ys.stderr锛宻ys.stdout鎴栬€呮枃浠? FileHandler锛歭ogging.FileHandler锛涙棩蹇楄緭鍑哄埌鏂囦欢 BaseRotatingHandler锛歭ogging.handlers.BaseRotatingHandler锛涘熀鏈殑鏃ュ織鍥炴粴鏂瑰紡 RotatingHandler锛歭ogging.handlers.RotatingHandler锛涙棩蹇楀洖婊氭柟寮忥紝鏀寔鏃ュ織鏂囦欢鏈€澶ф暟閲忓拰鏃ュ織鏂囦欢鍥炴粴 TimeRotatingHandler锛歭ogging.handlers.TimeRotatingHandler锛涙棩蹇楀洖婊氭柟寮忥紝鍦ㄤ竴瀹氭椂闂村尯鍩熷唴鍥炴粴鏃ュ織鏂囦欢 SocketHandler锛歭ogging.handlers.SocketHandler锛涜繙绋嬭緭鍑烘棩蹇楀埌TCP/IP sockets DatagramHandler锛歭ogging.handlers.DatagramHandler锛涜繙绋嬭緭鍑烘棩蹇楀埌UDP sockets SMTPHandler锛歭ogging.handlers.SMTPHandler锛涜繙绋嬭緭鍑烘棩蹇楀埌閭欢鍦板潃 SysLogHandler锛歭ogging.handlers.SysLogHandler锛涙棩蹇楄緭鍑哄埌syslog NTEventLogHandler锛歭ogging.handlers.NTEventLogHandler锛涜繙绋嬭緭鍑烘棩蹇楀埌Windows NT/2000/XP鐨勪簨浠舵棩蹇? MemoryHandler锛歭ogging.handlers.MemoryHandler锛涙棩蹇楄緭鍑哄埌鍐呭瓨涓殑鎸囧畾buffer HTTPHandler锛歭ogging.handlers.HTTPHandler锛涢€氳繃"GET"鎴栬€?span style="color: #800000;">"POST"杩滅▼杈撳嚭鍒癏TTP鏈嶅姟鍣?/pre>
2.2.3 鏃ュ織鍥炴粴
浣跨敤RotatingFileHandler锛屽彲浠ュ疄鐜版棩蹇楀洖婊氾細
# -*- coding:utf-8 -*- import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) # 瀹氫箟涓€涓猂otatingFileHandler锛屾渶澶氬浠戒笁涓棩蹇楁枃浠? 姣忎釜鏃ュ織鏂囦欢鏈€澶?k rHandler = RotatingFileHandler("log.txt",maxBytes = 1*1024,backupCount = 3) rHandler.setLevel(logging.INFO) formatter = logging.Formatter(鈥?/span>%(asctime)s - %(name)s - %(levelname)s - %(message)s鈥?/span>) rHandler.setFormatter(formatter) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(formatter) logger.addHandler(rHandler) logger.addHandler(console) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")
鍙互鍦ㄥ伐绋嬬洰褰曚腑鐪嬪埌锛屽浠界殑鏃ュ織鏂囦欢锛?/p>
log.txt log.txt.1 log.txt.2 log.txt.3
2.3 璁剧疆娑堟伅鐨勭瓑绾?/h4>
鍙互璁剧疆涓嶅悓鐨勬棩蹇楃瓑绾э紝鐢ㄤ簬鎺у埗鏃ュ織鐨勮緭鍑猴細
鏃ュ織绛夌骇锛氫娇鐢ㄨ寖鍥?
FATAL锛氳嚧鍛介敊璇?
CRITICAL锛氱壒鍒碂绯曠殑浜嬫儏锛屽鍐呭瓨鑰楀敖銆佺鐩樼┖闂翠负绌猴紝涓€鑸緢灏戜娇鐢?
ERROR锛氬彂鐢熼敊璇椂锛屽IO鎿嶄綔澶辫触鎴栬€呰繛鎺ラ棶棰?
WARNING锛氬彂鐢熷緢閲嶈鐨勪簨浠讹紝浣嗘槸骞朵笉鏄敊璇椂锛屽鐢ㄦ埛鐧诲綍瀵嗙爜閿欒
INFO锛氬鐞嗚姹傛垨鑰呯姸鎬佸彉鍖栫瓑鏃ュ父浜嬪姟
DEBUG锛氳皟璇曡繃绋嬩腑浣跨敤DEBUG绛夌骇锛屽绠楁硶涓瘡涓惊鐜殑涓棿鐘舵€?/span>
2.4 鎹曡幏traceback
python涓殑traceback妯″潡琚敤浜庤窡韪敤浜庡紓甯歌繑鍥炰俊鎭紝鍙互鍦╨ogging涓褰晅raceback
# -*- coding:utf-8 -*- import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter(鈥?/span>%(asctime)s - %(name)s - %(levelname)s - %(message)s鈥?/span>) handler.setFormatter(formatter) console = logging.StreamHandler() console.setLevel(logging.INFO) logger.addHandler(handler) logger.addHandler(console) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") try: open("sklearn.txt", "rb") except (SystemExit, KeyboardInterrupt): raise except Exception: logger.error("Falid to open sklearn.txt from logger.error", exc_info = True) logger.info("Finish")
鎺у埗鍙板拰鏃ュ織鏂囦欢log.txt涓緭鍑猴細
Start print log Something maybe fail. Falid to open sklearn.txt from logger.error Traceback (most recent call last): File "D:/myproject/test.py", line 23, in <module> open("sklearn.txt", "rb") IOError: [Errno 2] No such file or directory: 鈥?/span>sklearn.txt鈥?/span> Finish
涔熷彲浠ヤ娇鐢╨ogger.exception(msg,_args)锛屽畠绛変环浜巐ogger.error(msg,exc_info=True,_args)
灏?/p>
logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)
鏇存敼涓猴細
logger.exception("Faild to open sklearn.txt from logger.exception")
鎺у埗鍙板拰鏃ュ織鏂囦欢log.txt杈撳嚭锛?/p>
Start print log Something maybe fail. Faild to open sklearn.txt from logger.exception Traceback (most recent call last): File "D:/myproject/test.py", line 23, in <module> open("sklearn.txt", "rb") IOError: [Errno 2] No such file or directory: 鈥?/span>sklearn.txt鈥?/span> Finish
2.5 澶氭ā鍧椾娇鐢╨ogging
涓绘ā鍧梞ainModule.py
import logging import subModule logger = logging.getLogger("mainModule") logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter(鈥?/span>%(asctime)s - %(name)s - %(levelname)s - %(message)s鈥?/span>) handler.setFormatter(formatter) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(formatter) logger.addHandler(handler) logger.addHandler(console) logger.info("creating an instance of subModule.subModuleClass") a = subModule.SubModuleClass() logger.info("calling subModule.subModuleClass.doSomething") a.doSomething() logger.info("done with subModule.subModuleClass.doSomething") logger.info("calling subModule.some_function") subModule.som_function() logger.info("done with subModule.some_function")
瀛愭ā鍧梥ubModule.py
import logging module_logger = logging.getLogger("mainModule.sub") class SubModuleClass(object): def __init__(self): self.logger = logging.getLogger("mainModule.sub.module") self.logger.info("creating an instance in SubModuleClass") def doSomething(self): self.logger.info("do something in SubModule") a = [] a.append(1) self.logger.debug("list a = " + str(a)) self.logger.info("finish something in SubModuleClass") def som_function(): module_logger.info("call function some_function")
杈撳嚭锛?/p>
2018-09-26 16:23:13,884 - mainModule - INFO - creating an instance of subModule.subModuleClass 2018-09-26 16:23:13,885 - mainModule.sub.module - INFO - creating an instance in SubModuleClass 2018-09-26 16:23:13,885 - mainModule - INFO - calling subModule.subModuleClass.doSomething 2018-09-26 16:23:13,885 - mainModule.sub.module - INFO - do something in SubModule 2018-09-26 16:23:13,885 - mainModule.sub.module - INFO - finish something in SubModuleClass 2018-09-26 16:23:13,885 - mainModule - INFO - done with subModule.subModuleClass.doSomething 2018-09-26 16:23:13,885 - mainModule - INFO - calling subModule.some_function 2018-09-26 16:23:13,885 - mainModule.sub - INFO - call function some_function 2018-09-26 16:23:13,885 - mainModule - INFO - done with subModule.some_function
棣栧厛鍦ㄤ富妯″潡瀹氫箟浜唋ogger鈥榤ainModule鈥橈紝骞跺瀹冭繘琛屼簡閰嶇疆锛屽氨鍙互鍦ㄨВ閲婂櫒杩涚▼閲岄潰鐨勫叾浠栧湴鏂归€氳繃getLogger(鈥榤ainModule鈥?寰楀埌鐨勫璞¢兘鏄竴鏍风殑锛屼笉闇€瑕侀噸鏂伴厤缃紝鍙互鐩存帴浣跨敤銆傚畾涔夌殑璇ogger鐨勫瓙logger锛岄兘鍙互鍏变韩鐖秎ogger鐨勫畾涔夊拰閰嶇疆锛屾墍璋撶殑鐖跺瓙logger鏄€氳繃鍛藉悕鏉ヨ瘑鍒紝浠绘剰浠モ€榤ainModule鈥樺紑澶寸殑logger閮芥槸瀹冪殑瀛恖ogger锛屼緥濡傗€榤ainModule.sub鈥樸€?/p>
瀹為檯寮€鍙戜竴涓猘pplication锛岄鍏堝彲浠ラ€氳繃logging閰嶇疆鏂囦欢缂栧啓濂借繖涓猘pplication鎵€瀵瑰簲鐨勯厤缃紝鍙互鐢熸垚涓€涓牴logger锛屽鈥楶ythonAPP鈥橈紝鐒跺悗鍦ㄤ富鍑芥暟涓€氳繃fileConfig鍔犺浇logging閰嶇疆锛屾帴鐫€鍦╝pplication鐨勫叾浠栧湴鏂广€佷笉鍚岀殑妯″潡涓紝鍙互浣跨敤鏍筶ogger鐨勫瓙logger锛屽鈥楶ythonAPP.Core鈥橈紝鈥楶ythonAPP.Web鈥樻潵杩涜log锛岃€屼笉闇€瑕佸弽澶嶇殑瀹氫箟鍜岄厤缃悇涓ā鍧楃殑logger銆?/p>
以上是关于logging鏃ュ織妯″潡的主要内容,如果未能解决你的问题,请参考以下文章