Home > Enterprise >  How to make the native functions visible on a custom class in python
How to make the native functions visible on a custom class in python

Time:01-25

I'm a new-bie to programming and have started learning classes. for my requirement i wrote a custom logging class and i'm trying to make the native functions of the logging module visible from another class on the same file. when i print dir(res) inside the customLogger it lists out all the native functions of the logging module . (as an exmaple info ()) but when i try to get the class object from another function, the native functions are not visibile.

The code that I had written is:

class customLogger():
    def __init__(self, logLevel = logging.DEBUG):
        self.logLevel = logLevel
        res = self.custLog(self.logLevel)
        print(dir(res) >>>> here the info() method is visible.
    
    def custLog(self, logLevel):
        logger_name = inspect.stack()[1][3]
        logger = logging.getLogger(logger_name)
        logger.setLevel(self.logLevel)
        fh = logging.FileHandler("iperf.log", mode='w')
        formatter = fh.setFormatter('%(asctime)s - %(levelname)s - %(name)s : %(message)s')
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        return logger
class iperf3():
    def __init__(self, server_ip):
        #Creationg the Logger
        log = customLogger(). >>>> here the info() method is not visible. can't i call the logging module functions from this class?
        print(f'The Value of log is : {log}')
        print(f'dir(log) is : {dir(log)}')

CodePudding user response:

If that's your entire class, you can replace it with a single function that takes a log level and returns the instance of Logger you want.

def make_logger(level):
    logger_name = inspect.stack()[1][3]
    logger = logging.getLogger(logger_name)
    logger.setLevel(level)
    fh = logging.FileHandler("iperf.log", mode='w')
    formatter = fh.setFormatter('%(asctime)s - %(levelname)s - %(name)s : %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    return logger
  •  Tags:  
  • Related