日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

使用python logging的配置

發布時間:2023/12/15 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用python logging的配置 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用python logging的配置

簡介

在python中使用logging模塊,對log進行配置時,可以使用配置文件,而不用再python源碼中進行配置。
這樣方便更改logging的配置。


使用basicConfig進行配置

使用logging.basicConfig來加載配置文件。

import logging LOG_FILENAME="myapp.log" logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) logging.debug("this is a debugmsg!") logging.info("this is a infomsg!") logging.warn("this is a warn msg!") logging.error("this is a error msg!") logging.critical("this is a critical msg!")

使用config.fileConfig進行配置

使用logging.config.fileConfig來加載配置文件。

import logging import logging.config# 加載配置文件 logging.config.fileConfig("logging2.conf")#create logger logger = logging.getLogger("simpleExample") ## getLogger中的參數如果在配置文件中找不到,則缺省使用root配置。## log logger.debug("debug message") logger.info("info message") logger.warn("warn message") logger.error("error message") logger.critical("critical message")

可以看看fileConfig的具體定義:

def fileConfig(fname, defaults=None, disable_existing_loggers=True):"""Read the logging configuration from a ConfigParser-format file.This can be called several times from an application, allowing an end userthe ability to select from various pre-canned configurations (if thedeveloper provides a mechanism to present the choices and load the chosenconfiguration)."""import ConfigParsercp = ConfigParser.ConfigParser(defaults)if hasattr(fname, 'readline'):cp.readfp(fname)else:cp.read(fname)formatters = _create_formatters(cp)# critical sectionlogging._acquireLock()try:logging._handlers.clear()del logging._handlerList[:]# Handlers add themselves to logging._handlershandlers = _install_handlers(cp, formatters)_install_loggers(cp, handlers, disable_existing_loggers)finally:logging._releaseLock()

配置文件

這里是示例的配置文件

[loggers] keys=root,simpleExample[handlers] keys=consoleHandler,fileHandler[formatters] keys=simpleFormatter[logger_root] level=DEBUG handlers=fileHandler[logger_simpleExample] level=DEBUG handlers=consoleHandler,fileHandler qualname=simpleExample propagate=0[handler_consoleHandler] class=StreamHandler level=WARNING formatter=simpleFormatter args=(sys.stdout,)[handler_fileHandler] class=FileHandler level=DEBUG formatter=simpleFormatter args=('testbyconfig.log','a+')[formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=

配置說明[loggers]

在loggers中使用keys定義幾個logger,在code中使用。

[loggers] keys=root,simpleExample

實踐中需要注意的是,一般root強制定義。在code中getLogger(“loggerName”)如果不匹配loggerName時,會使用root。

具體的logger項目配置section,使用的section名以logger_連接上具體的名稱。如logger_root, logger_simpleExample。

這里是logging中的實現代碼

#--------------------------------------------------------------------------- # Utility functions at module level. # Basically delegate everything to the root logger. #---------------------------------------------------------------------------def getLogger(name=None):"""Return a logger with the specified name, creating it if necessary.If no name is specified, return the root logger."""if name:return Logger.manager.getLogger(name)else:return root# ... ...class Manager(object):"""There is [under normal circumstances] just one Manager instance, whichholds the hierarchy of loggers."""def __init__(self, rootnode):"""Initialize the manager with the root node of the logger hierarchy."""self.root = rootnodeself.disable = 0self.emittedNoHandlerWarning = 0self.loggerDict = {}self.loggerClass = Nonedef getLogger(self, name):"""Get a logger with the specified name (channel name), creating itif it doesn't yet exist. This name is a dot-separated hierarchicalname, such as "a", "a.b", "a.b.c" or similar.If a PlaceHolder existed for the specified name [i.e. the loggerdidn't exist but a child of it did], replace it with the createdlogger and fix up the parent/child references which pointed to theplaceholder to now point to the logger."""rv = Noneif not isinstance(name, basestring):raise TypeError('A logger name must be string or Unicode')if isinstance(name, unicode):name = name.encode('utf-8')_acquireLock()try:if name in self.loggerDict:rv = self.loggerDict[name]if isinstance(rv, PlaceHolder):ph = rvrv = (self.loggerClass or _loggerClass)(name)rv.manager = selfself.loggerDict[name] = rvself._fixupChildren(ph, rv)self._fixupParents(rv)else:rv = (self.loggerClass or _loggerClass)(name)rv.manager = selfself.loggerDict[name] = rvself._fixupParents(rv)finally:_releaseLock()return rv#... ...

配置說明[logger_name]

在這里配置要使用的logger-handlers: 可以使用consoleHandler,fileHandler……。

配置說明[handler_handlerName]

在這里配置要使用logger的handlers的對應的配置.
如class、format、level及對應的args;args是傳入class函數的參數。

如consoleHandler對應了

class=StreamHandler level=WARNING formatter=simpleFormatter args=(sys.stdout,)

而 handler_fileHandler 對應的配置

class=FileHandler level=DEBUG formatter=simpleFormatter args=('testbyconfig.log','a+')

配置說明[formatter_simpleFormatter]

這里配置日志的formatter,如:

format=%(asctime)s - %(name)s - %(levelname)s - %(message)s 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的使用python logging的配置的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。