Python logging setLoggerClass














































Python logging setLoggerClass



Python logging setLoggerClass


Description: It tells the logging system to use the class klass when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__(). This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior. After this call, as at any other time, do not instantiate loggers directly using the subclass, continue to use the logging.getLogger function API to get your loggers.


Code:
import logging

def create_logger():
    LoggerClass = logging.getLoggerClass()
    return LoggerClass
    

def assign_logger(*args, **kwargs):
    LoggerClass = kwargs["loggerclass"]
    loglevel = kwargs["level"]

    level_dict = {
        "DEBUG": logging.DEBUG,
        "INFO": logging.DEBUG,
        "WARNING": logging.DEBUG,
        "ERROR": logging.DEBUG,
        "CRITICAL": logging.DEBUG
    }

    level = loglevel.upper()
    if level not in level_dict:
        raise RuntimeError("{} Level not found".format(level))
    
    logging.setLoggerClass(klass=LoggerClass)
    formatter = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(message)s",
                                    datefmt="%a, %d %b %H:%M:%S")
    
    st_handler = logging.StreamHandler()
    st_handler.setFormatter(formatter)

    loggerObj = LoggerClass(name=__name__, level=level)
    loggerObj.addHandler(st_handler)

    return loggerObj


if __name__ == "__main__":
    Loggerclass = create_logger()
    log = assign_logger(loggerclass=Loggerclass, level="DEBUG")

    log.debug("This is DEBUG Message")
    log.info("This is INFO Message")
    log.warning("This is WARNING Message")
    log.error("This is ERROR Message")
    log.critical("This is CRITICAL Message")
Output:(Console)


Explanation: In this code we are creating logger class using getLoggerClass function and set that logger class for further development using setLoggerClass. We get logger class from create_logger function. After that we pass this logger class and log level to assign_logger as an arguments. In this function we check where level is valid or not, if it's not valid then it will give runtime error. We set this class using setLoggerClass with klass keyword. Then we create stream handler and set one format for how to display our log messages. We set the logger name as well as level to that logger class and return their object. So we can log our log messages using that logger class object.


So in this way we can set a logger class and use it's instance for log message of different level of log in our software.



Comments