pra*_*688 5 python logging python-3.x python-3.5
Logger我一直在尝试通过子类化来创建一个新类logging.Logger。Python版本是3.5
我的应用程序中有几个模块,并且仅在主模块中配置日志记录,在主模块中使用设置记录器类logging.setLoggerClass(...)
但是,当我从其他模块检索相同的 Logger 实例时,它仍然创建该类的新实例Logger,而不是我定义的子类实例。
例如我的代码是:
# module 1
import logging
class MyLoggerClass(logging.getLoggerClass()):
def __init__(name):
super(MyLoggerClass, self).__init__(name)
def new_logger_method(...):
# some new functionality
if __name__ == "__main__":
logging.setLoggerClass(MyLoggerClass)
mylogger = logging.getLogger("mylogger")
# configuration of mylogger instance
# module 2
import logging
applogger = logging.getLogger("mylogger")
print(type(applogger))
def some_function():
applogger.debug("in module 2 some_function")
Run Code Online (Sandbox Code Playgroud)
当执行此代码时,我希望applogger模块 2 中的类型为MyLoggerClass。我打算使用它new_logger_method来实现一些新功能。
但是,由于结果applogger是类型logging.Logger,因此当代码运行时,它会抛出Loggerhas no attribute named new_logger_method。
有人遇到过这个问题吗?
预先感谢您的任何帮助!普拉纳夫
如果logger您希望您的模块能够在任何环境中良好运行,您应该为您的模块(及其子模块)定义一个记录器,并将其用作其他更深层次的所有内容的主记录器,而不是尝试通过更改默认记录器工厂来影响全局在你的模块结构中。问题在于您明确想要使用logging.Logger与默认/全局定义的类不同的类,并且该logging模块没有提供一种简单的方法来进行基于上下文的工厂切换,因此您必须自己完成。
有很多方法可以做到这一点,但我个人的偏好是尽可能明确并定义您自己的logger模块,然后每当您需要获取自定义记录器时,您都可以将其导入到包中的其他模块中。logger.py在您的情况下,您可以在包的根目录下创建并执行以下操作:
import logging
class CustomLogger(logging.Logger):
def __init__(self, name):
super(CustomLogger, self).__init__(name)
def new_logger_method(self, caller=None):
self.info("new_logger_method() called from: {}.".format(caller))
def getLogger(name=None, custom_logger=True):
if not custom_logger:
return logging.getLogger(name)
logging_class = logging.getLoggerClass() # store the current logger factory for later
logging._acquireLock() # use the global logging lock for thread safety
try:
logging.setLoggerClass(CustomLogger) # temporarily change the logger factory
logger = logging.getLogger(name)
logging.setLoggerClass(logging_class) # be nice, revert the logger factory change
return logger
finally:
logging._releaseLock()
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以随意在其中包含其他自定义日志初始化逻辑。然后,您可以从其他模块(和子包)导入此记录器并使用它getLogger()来获取本地自定义记录器。例如,您需要的module1.py是:
from . import logger # or `from package import logger` for external/non-relative use
log = logger.getLogger(__name__) # obtain a main logger for this module
def test(): # lets define a function we can later call for testing
log.new_logger_method("Module 1")
Run Code Online (Sandbox Code Playgroud)
这涵盖了内部使用 - 只要您在所有模块/子模块中坚持这种模式,您就可以访问自定义记录器。
当涉及到外部使用时,您可以编写一个简单的测试来表明您的自定义记录器已创建,并且它不会干扰日志记录系统的其余部分,因此您的包/模块可以被声明为好公民。假设您module1.py位于一个名为的包中package,并且您想从外部对其进行整体测试:
import logging # NOTE: we're importing the global, standard `logging` module
import package.module1
logging.basicConfig() # initialize the most rudimentary root logger
root_logger = logging.getLogger() # obtain the root logger
root_logger.setLevel(logging.DEBUG) # set root log level to DEBUG
# lets see the difference in Logger types:
print(root_logger.__class__) # <class 'logging.RootLogger'>
print(package.module1.log.__class__) # <class 'package.logger.CustomLogger'>
# you can also obtain the logger by name to make sure it's in the hierarchy
# NOTE: we'll be getting it from the standard logging module so outsiders need
# not to know that we manage our logging internally
print(logging.getLogger("package.module1").__class__) # <class 'package.logger.CustomLogger'>
# and we can test that it indeed has the custom method:
logging.getLogger("package.module1").new_logger_method("root!")
# INFO:package.module1:new_logger_method() called from: root!.
package.module1.test() # lets call the test method within the module
# INFO:package.module1:new_logger_method() called from: Module 1.
# however, this will not affect anything outside of your package/module, e.g.:
test_logger = logging.getLogger("test_logger")
print(test_logger.__class__) # <class 'logging.Logger'>
test_logger.info("I am a test logger!")
# INFO:test_logger:I am a test logger!
test_logger.new_logger_method("root - test")
# AttributeError: 'Logger' object has no attribute 'new_logger_method'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3434 次 |
| 最近记录: |