Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 2.7 : remove handler object or logger

I want to remove this logger.

backup.py

try:
        Logger = Log('PythonWork.backup') 
        Logger.info("backup task started")
        Logger.disabled=True
except Exception as e:
        errlogger = Error('PythonWork.backup')
        errlogger.error("Error: Error found back up service,failed.")
        Logger.error("backup task started")

I tried Logger.removeHandler() and Logger.propagate

my log function

def Log(LOG_NAME):
    logger = logging.getLogger(LOG_NAME)
    logger.setLevel(logging.DEBUG)
    filename=python.log
    fh = logging.FileHandler(filename)
    fh.setLevel(logging.INFO)
    logger.addHandler(fh)

    return logger

my Error function

 def Error(LOG_NAME):
    logger = logging.getLogger(LOG_NAME)
    logger.setLevel(logging.DEBUG)
    fileNameError=python.log
    fhError = logging.FileHandler(fileNameError)
    fhError.setLevel(logging.ERROR)
    logger.addHandler(fhError)

    return logger

In the backup.py file I dont want to excecute Logger object but it is executed. when I run this program and I want to stop or disable or remove that object.

like image 875
bob marti Avatar asked Oct 17 '25 02:10

bob marti


1 Answers

From your code, it seems the Log() function is creating a new log handler at each call - see the last lines:

fh = logging.FileHandler(filename)
fh.setLevel(logging.INFO)
logger.addHandler(fh)
^^^^^^^^^^^^^^^^^^^^^

So, you may have a myriad of FileHandler objects, removing one won't remove the others. I suspect this is your problem.

If you want to remove all handlers associated to a logger, you can do the following:

for handler in logger.handlers[:]:
    logger.removeHandler(handler)

Hope this helps.

like image 139
mguijarr Avatar answered Oct 20 '25 07:10

mguijarr