我有一个记录器类,在调用每个记录功能之前,我需要检查记录器是否已配置。如果是,则__logger_configured
类变量将为true。鉴于每次调用静态方法时都需要检查此方法,因此我想对所有静态方法进行包装,并检查此成员变量。
这很棘手,因为:
我该怎么做?
class Logger:
__logger_configured = False
# Other stuff...
# Logger now configured. Other static member functions are unlocked.
Logger.__logger_configured = True
###########################
####### Decorators ########
###########################
# We don't want checkLoggerStatus to be a member function of Logger. Hence
# Hence, make it a staticmethod of a private nested class.
class _Decorators:
@staticmethod
def check_logger_status(func, logger_status: bool):
def wrapper(*args, **kwargs):
if not logger_status:
raise ValueError('[ERROR] -- The Logger has not yet been configured. '
'Please first configure the logger '
'via its config_logger staticmethod')
else:
func(*args, **kwargs)
return wrapper
##########################
### Logging Facilities ###
##########################
# Other stuff...
@staticmethod
@_Decorators.check_logger_status(__logger_configured)
def log_info(operation: str):
Logger.update_time()
# Write to file
with open(Logger.__filename, Logger.__filemode) as ourFile:
ourFile.write('[INFO] {} -- {}'.format(Logger.__last_update, operation))
# Other stuff...