Home > Enterprise >  Logging error Traceback (most recent call last):File "/usr/lib/python3.7/logging/__init__.py&qu
Logging error Traceback (most recent call last):File "/usr/lib/python3.7/logging/__init__.py&qu

Time:07-19

I am trying to make a custom logging class.

import logging

logging_level = 'INFO'

class Logger:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.getLevelName(logging_level))
        formatter = logging.Formatter('%(asctime)s - %(name)s%(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S%p')
        file_handler = logging.FileHandler('logFile.log')
        file_handler.setFormatter(format)
        stream_handler = logging.StreamHandler() #if we want to print to consol
        stream_handler.setFormatter(format)
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler)

    
    def logInfo(self):
        self.logger.info("Hi")

log = Logger()
log.logInfo()

I keep receiving this error

--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.7/logging/__init__.py", line 1025, in emit
    msg = self.format(record)
  File "/usr/lib/python3.7/logging/__init__.py", line 869, in format
    return fmt.format(record)
AttributeError: 'builtin_function_or_method' object has no attribute 'format'
Call stack:
  File "/home/usr/.../python_scripts/Logger.py", line 22, in <module>
    log.logInfo()
  File "/home/usr/.../python_scripts/Logger.py", line 19, in logInfo
    self.logger.info("Hi")
Message: 'Hi'
Arguments: ()

I must be doing something wrong the the oo programming in python. IT makes the log file but it is empty.

CodePudding user response:

You had a typo in your logInfo method and in the "format" paramater which should have been formatter, I also changed a bit the setLevel method to use getLevelName so you could change it dynamically:

import logging

logging_level = 'INFO'

class Logger:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.getLevelName(logging_level))
        formatter = logging.Formatter('%(asctime)s - %(name)s%(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S%p')
        file_handler = logging.FileHandler('logFile.log')
        file_handler.setFormatter(formatter)
        stream_handler = logging.StreamHandler() #if we want to print to consol
        stream_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler)

    
    def logInfo(self):
        self.logger.info("Hi")

log = Logger()
log.logInfo()

Output

07/18/2022 06:24:39PM - __main__INFO: Hi
  • Related