Python:使用数据类字段参数初始化Logger



这是我的Logger类:

import logging
import os
import datetime

class Logger:
_logger = None
def __new__(cls, user: str, *args, **kwargs):
if cls._logger is None:
cls._logger = super().__new__(cls, *args, **kwargs)
cls._logger = logging.getLogger("crumbs")
cls._logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] [%(filename)s] [%(funcName)s] [%(lineno)d]: %(message)s')
now = datetime.datetime.now()
directory_name = f'./log/{now.strftime("%Y-%m-%d")}'
base_log_name = f'/{user}'
log_file_extension = '.log'
if not os.path.isdir(directory_name):
os.mkdir(directory_name)
file_handler = logging.FileHandler(f'{directory_name}{base_log_name}{now.strftime("%d-%m-%Y")}{log_file_extension}', 'w', 'utf-8')
stream_handler = logging.StreamHandler()
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
cls._logger.addHandler(file_handler)
cls._logger.addHandler(stream_handler)
return cls._logger

这是我的class,接受用户argument我想用我的用户名在file name中创建我的log文件:

@dataclass(kw_only=True)
class RunningJobManager:
user: str = field(init=True)
password: str = field(init=True)
logging: Logger = field(init=False, default_factory=Logger(user=user))

所以目前我的用户fieldLogger类中是dataclasses.Field而不是string的类型。我也尝试使用default代替default_factory

我得到了这个错误:

目前我的代码崩溃OSError, [Errno 22]无效参数:G:日志 2023-01-20 my_project 字段(name = None, type = None,默认= & lt; dataclasses._MISSING_TYPE对象在0 x0000017b1e78db10> default_factory = & lt; dataclasses。_MISSING_TYPE对象在0 x0000017b1e78db10> init = True, repr = True,散列= None,比较= True,元数据= mappingproxy ({}), kw_only = & lt; dataclasses._MISSING_TYPEobject at 0x0000017B1E78DB10>,_field_type=None)20-01-2023.log'

在这一行:

file_handler = logging.FileHandler(f'{directory_name}{base_log_name}{now.strftime("%d-%m-%Y")}{log_file_extension}', 'w', 'utf-8')

编辑

"stdout_handler": {
"formatter": "std_out",
"class": "logging.StreamHandler",
"level": "DEBUG"
}

下面是dictConfig的例子:

import logging
import os
from dataclasses import dataclass, field
from logging import Logger
from logging.config import dictConfig

@dataclass(kw_only=True)
class AbstractJobManager:
user: str = field(init=True)
@property
def logger(self) -> Logger:
return logging.getLogger('crumbs')
def __post_init__(self):
if not os.path.isdir('log'):
os.mkdir('log')
# some config from YAML, TOML or hardcoded - doesn't matter...
config = {
'version': 1,
'loggers': {
'crumbs': {
'level': 'INFO',
'handlers': ['file_handler'],
},
},
'handlers': {
'file_handler': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': f'./log/{self.user}.log',  # I skipped %Y-%m-%d...
'backupCount': 3,
'formatter': 'simple',
},
},
'formatters': {
'simple': {
'format': '%(pathname)s:%(lineno)d %(asctime)s - %(levelname)s - %(message)s',
},
},
}
dictConfig(config)

@dataclass(kw_only=True)
class RunningJobManager(AbstractJobManager):
password: str = field(init=True)
def run(self):
self.logger.info('user = %s, password = %s', self.user, self.password)

RunningJobManager(user='falukky', password='Hello World!').run()
RunningJobManager(user='ridley', password='scott').run()
RunningJobManager(user='jimi', password='hendrix').run()

这不是数据类处理依赖于其他字段的字段初始化的方式。fielddefault_factory形参应该是一个零参数可调用对象。标准库文档声明:

default_factory:如果提供,它必须是一个零参数的可调用对象,当需要该字段的默认值时将被调用…

换句话说,不可能传递任何参数给default_factory

使用其他字段的值初始化字段的正确方法是使用__post_install__方法:

@dataclass(kw_only=True)
class RunningJobManager:
user: str = field(init=True)
password: str = field(init=True)
logging: Logger = field(init=False, default=None)
def __post_init__(self):
if self.logging is None:
self.logging = Logger(self.user)

相关内容

  • 没有找到相关文章

最新更新