我想创建一个Python日志记录类,它可以作为一种常见的日志记录配置方法进行继承,但又可以从父类中单独控制基类的日志记录级别。这类似于How to use python logging in multiple modules。Vinay Sajip使用LogMixin的answer非常接近。下面是我稍微修改过的版本。
我的大多数类都继承了较小的类。例如:
文件名: LogMixin.py
import logging, logging.config
import yaml
class LogMixin(object):
__loggerConfigured = False
@property
def logger(self):
if not self.__loggerConfigured:
with open('log_config.yaml', 'rt') as f:
config = yaml.load(f.read())
logging.config.dictConfig(config)
self.__loggerConfigured = True
name = '.'.join([self.__class__.__name__])
return logging.getLogger(name)
文件名: Base.py
from LogMixin import LogMixin
class Base(LogMixin):
def __init__(self):
self.logger.debug("Debug Base")
def run_base(self):
self.logger.debug("Debug Running Base")
self.logger.info("Info Running Base")
if __name__ == '__main__':
my_base = Base()
my_base.run_base()
文件名: Parent.py
from Base import Base
class Parent(Base):
def __init__(self):
self.logger.debug("Debug Parent")
def run_parent(self):
self.logger.debug("Debug Running Parent")
self.logger.info("Info Running Parent")
if __name__ == '__main__':
my_parent = Parent()
my_parent.run_base()
my_parent.run_parent()
文件名: log_config.yaml
---
version: 1
disable_existing_loggers: False
# Configuring the default (root) logger is highly recommended
root:
level: WARNING
handlers: [console]
# Configuration for logger set with logging.getLogger(NAME)
loggers:
Base:
level: INFO
handlers: [console]
propagate: no
Parent:
level: DEBUG
handlers: [console]
propagate: no
formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
console:
class: logging.StreamHandler
formatter: simple
stream: ext://sys.stdout
...
我得到了通用日志配置的好处。但是,我希望独立控制Base和Parent的日志级别。使用上面的配置文件,我得到:
$ python Base.py
2015-03-16 00:06:23,716 - Base - INFO - Info Running Base
$ python Parent.py
2015-03-16 00:06:19,682 - Parent - DEBUG - Debug Parent
2015-03-16 00:06:19,682 - Parent - DEBUG - Debug Running Base
2015-03-16 00:06:19,682 - Parent - INFO - Info Running Base
2015-03-16 00:06:19,682 - Parent - DEBUG - Debug Running Parent
2015-03-16 00:06:19,682 - Parent - INFO - Info Running Parent
我理解为什么我得到了这个,我只有一个记录器“父母”。但是,总的来说,我更愿意得到以下内容:
$ python Base.py
2015-03-16 00:06:23,716 - Base - INFO - Info Running Base
$ python Parent.py
2015-03-16 00:06:19,682 - Parent - DEBUG - Debug Parent
2015-03-16 00:06:19,682 - Base - INFO - Info Running Base
2015-03-16 00:06:19,682 - Parent - DEBUG - Debug Running Parent
2015-03-16 00:06:19,682 - Parent - INFO - Info Running Parent
(请注意,没有与Base.py相关的调试)。
或者更好:
$ python Base.py
2015-03-16 00:06:23,716 - Base - INFO - Info Running Base
$ python Parent.py
2015-03-16 00:06:19,682 - Parent - DEBUG - Debug Parent
2015-03-16 00:06:19,682 - Parent.Base - INFO - Info Running Base
2015-03-16 00:06:19,682 - Parent - DEBUG - Debug Running Parent
2015-03-16 00:06:19,682 - Parent - INFO - Info Running Parent
(请注意,名称是Parent.Base,所以我可以看到继承。)使用一个简单的LogMixin类可以做到这一点吗?
发布于 2018-06-07 09:05:50
metaclass会更合适。当定义一个类时,它将获得自己的记录器。名称损坏确保每个类都使用自己的记录器。
import logging
import sys
logging.basicConfig(stream=sys.stdout)
class MetaBase(type):
def __init__(cls, *args):
super().__init__(*args)
# Explicit name mangling
logger_attribute_name = '_' + cls.__name__ + '__logger'
# Logger name derived accounting for inheritance for the bonus marks
logger_name = '.'.join([c.__name__ for c in cls.mro()[-2::-1]])
setattr(cls, logger_attribute_name, logging.getLogger(logger_name))
class Base(metaclass=MetaBase):
def __init__(self):
self.__logger.error('init base')
def func_base(self):
self.__logger.error('func base')
class Parent(Base):
def func_parent(self):
self.__logger.error('func parent')
p = Parent()
p.func_base()
p.func_parent()
结果如下:
ERROR:Base:init base
ERROR:Base:func base
ERROR:Base.Parent:func parent
与mix in相比,这种方法还有一些额外的好处。
getLogger
只需要继承基,不需要记得添加MixIn我简化了示例以演示关键概念。应该跨文件和配置文件工作。
https://stackoverflow.com/questions/29069655
复制相似问题