python logger中的序言和结尾 [英] Prologue and epilogue in python logger
问题描述
我希望创建一个记录器类,在第一次记录时.getLogger()将编写一个序言,并且一旦该过程结束记录器并编写一个结语
我的代码:
logger = logging.getLogger('name')
logger.info('HI')
预期输出:
2014-09-29 10:50:40,187 - INFO - ** My prologue **
2014-09-29 10:50:40,187 - INFO - HI
2014-09-29 10:50:40,187 - INFO - ** My epilogue **
如前所述,我先前回答中的epiLoggers不是单子",必须在将要使用它们的模块之间传递.
解决此问题的选项包括
- 将logger.Logger子类化(如果实际上可行,我还没有研究过),
- 实施一种机制来创建和存储和检索EpiLogLogger,例如logger.getLogger(过于夸张的想法)
- 创建一个可在多个模块中使用的类似Singleton的epiLogger.
此解决方案适用于后者.
import logging
class epiLogger():
_initialised = {}
_finalised = {}
def __init__(self, name):
self.logger = logging.getLogger(name)
self.name = name
if not epiLogger._initialised.get(name):
self.logger.addHandler(logging.StreamHandler())
self.logger.setLevel(logging.INFO)
self.logger.info('** My Prologue **')
epiLogger._initialised[self.name] = True
def info(self, the_info):
self.logger.info(the_info)
def __del__(self):
if not self.__class__._finalised.get(self.name):
self.logger.info('** My Epilogue **')
self.__class__._finalised[self.name] = True
a = epiLogger("foo")
a.info("foo!")
a.info("bar!")
a.info("party!")
我知道这是一件好事,但请在此处阅读:
或者当然调查子类的logger.Logger :)> I wish to create a logger class that upon the first logging.getLogger() will write a prologue and once the process ends the logger with write an epilogue my code: The expected output:
As observed, the epiLoggers in my previous answers are not "singletons", and have to be passed around between modules that are going to use them. Options for getting around this include This solution does the latter. I know that this feels like a good thing to do, but read here: http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/. I would seriously ask yourself "actually, might it be best in the long run to pass each epiLogger around to where it belongs?" Or of course investigate subclassing logger.Logger :) 这篇关于python logger中的序言和结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!logger = logging.getLogger('name')
logger.info('HI')
2014-09-29 10:50:40,187 - INFO - ** My prologue **
2014-09-29 10:50:40,187 - INFO - HI
2014-09-29 10:50:40,187 - INFO - ** My epilogue **
import logging
class epiLogger():
_initialised = {}
_finalised = {}
def __init__(self, name):
self.logger = logging.getLogger(name)
self.name = name
if not epiLogger._initialised.get(name):
self.logger.addHandler(logging.StreamHandler())
self.logger.setLevel(logging.INFO)
self.logger.info('** My Prologue **')
epiLogger._initialised[self.name] = True
def info(self, the_info):
self.logger.info(the_info)
def __del__(self):
if not self.__class__._finalised.get(self.name):
self.logger.info('** My Epilogue **')
self.__class__._finalised[self.name] = True
a = epiLogger("foo")
a.info("foo!")
a.info("bar!")
a.info("party!")