importloggingfromdatetimeimportdatetimeimportcoloredlogs# Global variables for loggingLOG_TO_CONSOLE=TrueCONSOLE_LEVEL="INFO"LOG_TO_FILE=FalseFILE_LEVEL="INFO"
[docs]defconfigure_console_log(enabled=True,level="INFO"):""" Sets whether the log statements are displayed in the console logging, and, if enabled, the log level to use. If not explicitly configured, console logging is ON at the INFO level. Args: enabled (bool, optional): Whether to enable console logging. Defaults to True. level (str, optional): If `enabled` is True, sets the level that the logging module displays. This level is the minimum and all messages at a higher level are included. Valid values are - CRITICAL - ERROR - WARNING - INFO - DEBUG Defaults to "INFO". """globalLOG_TO_CONSOLEglobalCONSOLE_LEVELLOG_TO_CONSOLE=enabledCONSOLE_LEVEL=level_setup_logger()
[docs]defconfigure_file_log(enabled=True,level="INFO"):""" Sets whether the log statements are exported to a log file, and, if enabled, the log level to use. If not explicitly configured, file logging is OFF. Args: enabled (bool, optional): Whether to enable file logging. This argument defaults to True. level (str, optional): If `enabled` is True, sets the level that the logging module displays. This level is the minimum and all messages at a higher level are included. Valid values are - CRITICAL - ERROR - WARNING - INFO - DEBUG Defaults to "INFO". """globalLOG_TO_FILEglobalFILE_LEVELLOG_TO_FILE=enabledFILE_LEVEL=level_setup_logger()
def_setup_logger():""" Configures the root logger based on the default or user-specified settings. As needed, a StreamHandler is created for console logging or FileHandler is created for file logging. Either or both are attached to the root logger for use throughout FLORIS. Returns: logging.Logger: The root logger from the `logging` module. """# Create a logger object for florislogger=logging.getLogger(name="floris")logger.setLevel(logging.DEBUG)# level_styles = {'warning': {'color': 'red', 'bold': False}}fmt_console="%(name)s%(levelname)s%(message)s"fmt_file="%(asctime)s - %(name)s - %(levelname)s - %(message)s"file_name="floris_{:%Y-%m-%d-%H_%M_%S}.log".format(datetime.now())# Remove all existing handlers before adding new onesforhinlogger.handlers.copy():logger.removeHandler(h)# Configure and add the console handlerifLOG_TO_CONSOLE:console_handler=logging.StreamHandler()console_handler.setLevel(CONSOLE_LEVEL)console_format=coloredlogs.ColoredFormatter(# level_styles=level_styles,fmt=fmt_console)console_handler.setFormatter(console_format)console_handler.addFilter(TracebackInfoFilter(clear=True))logger.addHandler(console_handler)# Configure and add the file handlerifLOG_TO_FILE:file_handler=logging.FileHandler(file_name)file_handler.setLevel(FILE_LEVEL)file_format=logging.Formatter(fmt_file)file_handler.setFormatter(file_format)file_handler.addFilter(TracebackInfoFilter(clear=False))logger.addHandler(file_handler)returnlogger
[docs]classTracebackInfoFilter(logging.Filter):"""Clear or restore the exception on log records"""def__init__(self,clear=True):self.clear=clear
[docs]classLoggingManager:""" This class provide an easy access to the global logger. The virtual property here allows a simple and dynamic method for obtaining the correct logger for the calling class. """@propertydeflogger(self):returnlogging.getLogger("{}.{}".format(type(self).__module__,type(self).__name__))