"""Load PyTorch Lightning Loggers."""# Copyright (C) 2022 Intel Corporation# SPDX-License-Identifier: Apache-2.0importloggingimportosimportwarningsfromtypingimportIterable,List,Unionfromomegaconf.dictconfigimportDictConfigfromomegaconf.listconfigimportListConfigfrompytorch_lightning.loggersimportCSVLogger,LightningLoggerBasefrom.tensorboardimportAnomalibTensorBoardLoggerfrom.wandbimportAnomalibWandbLogger__all__=["AnomalibTensorBoardLogger","AnomalibWandbLogger","configure_logger","get_experiment_logger",]AVAILABLE_LOGGERS=["tensorboard","wandb","csv"]logger=logging.getLogger(__name__)classUnknownLogger(Exception):"""This is raised when the logger option in `config.yaml` file is set incorrectly."""
[docs]defconfigure_logger(level:Union[int,str]=logging.INFO):"""Get console logger by name. Args: level (Union[int, str], optional): Logger Level. Defaults to logging.INFO. Returns: Logger: The expected logger. """ifisinstance(level,str):level=logging.getLevelName(level)format_string="%(asctime)s - %(name)s - %(levelname)s - %(message)s"logging.basicConfig(format=format_string,level=level)# Set Pytorch Lightning logs to have a the consistent formatting with anomalib.forhandlerinlogging.getLogger("pytorch_lightning").handlers:handler.setFormatter(logging.Formatter(format_string))handler.setLevel(level)
[docs]defget_experiment_logger(config:Union[DictConfig,ListConfig])->Union[LightningLoggerBase,Iterable[LightningLoggerBase],bool]:"""Return a logger based on the choice of logger in the config file. Args: config (DictConfig): config.yaml file for the corresponding anomalib model. Raises: ValueError: for any logger types apart from false and tensorboard Returns: Union[LightningLoggerBase, Iterable[LightningLoggerBase], bool]: Logger """logger.info("Loading the experiment logger(s)")# TODO remove when logger is deprecated from projectif"logger"inconfig.project.keys():warnings.warn("'logger' key will be deprecated from 'project' section of the config file."" Please use the logging section in config file.",DeprecationWarning,)if"logging"notinconfig:config.logging={"logger":config.project.logger,"log_graph":False}else:config.logging.logger=config.project.loggerifconfig.logging.loggerin[None,False]:returnFalselogger_list:List[LightningLoggerBase]=[]ifisinstance(config.logging.logger,str):config.logging.logger=[config.logging.logger]forexperiment_loggerinconfig.logging.logger:ifexperiment_logger=="tensorboard":logger_list.append(AnomalibTensorBoardLogger(name="Tensorboard Logs",save_dir=os.path.join(config.project.path,"logs"),log_graph=config.logging.log_graph,))elifexperiment_logger=="wandb":wandb_logdir=os.path.join(config.project.path,"logs")os.makedirs(wandb_logdir,exist_ok=True)name=(config.model.nameif"category"notinconfig.dataset.keys()elsef"{config.dataset.category}{config.model.name}")logger_list.append(AnomalibWandbLogger(project=config.dataset.name,name=name,save_dir=wandb_logdir,))elifexperiment_logger=="csv":logger_list.append(CSVLogger(save_dir=os.path.join(config.project.path,"logs")))else:raiseUnknownLogger(f"Unknown logger type: {config.logging.logger}. "f"Available loggers are: {AVAILABLE_LOGGERS}.\n"f"To enable the logger, set `project.logger` to `true` or use one of available loggers in config.yaml\n"f"To disable the logger, set `project.logger` to `false`.")returnlogger_list