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鏃ュ織妯″潡的主要内容,如果未能解决你的问题,请参考以下文章

LINUX7(鏃ュ織绠$悊)

Postgresql鏃ュ織鏀堕泦

CentOS 7涓嬫渶鏂扮増(6.2.4)ELK+Filebeat+Log4j鏃ュ織闆嗘垚鐜鎼缓瀹屾暣鎸囧崡

nginx鏃ュ織璇存槑

Apache鏃ュ織鍒嗗壊

Raft瀹炴垬鈥斺€旈泦缇ゆ垚鍛樺彉鏇翠笌鏃ュ織鍘嬬缉