I am trying to close all the handlers at the end of my script, but for some reason logger.handlers is an empty list where the handlers should be therefore I cannot close them. Could someone explain how I can find and close my handlers?
import logging
from logging.config import dictConfig
logconfig = {
"version": 1,
"disable_existing_loggers": 0,
"root": {
"level": "DEBUG",
"handlers": [
"console",
"file",
"debugfile"
]
},
"loggers": {
},
"formatters": {
"precise": {
"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"
},
"brief": {
# Don't think we'll use.
"format": "%(levelname)-8s: %(name)-15s: %(message)s"
}
},
"handlers": {
"debugfile": {
"class": "logging.FileHandler",
"formatter": "precise",
"level": "DEBUG",
"mode": "a",
"filename": "debugAndUp.log"
},
"console": {
"class": "logging.StreamHandler",
"formatter": "precise",
"level": "DEBUG",
"stream": "ext://sys.stdout"
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "precise",
"level": "WARNING",
"backupCount": 3,
"maxBytes": 10240000,
"filename": "warningAndUp.log"
}
}
}
dictConfig(logconfig)
logger = logging.getLogger(__name__)
logger.debug('Test')
logger.handlers >> []
you just want have to remove __name__
logging.getLogger(__name__)
as it refers to main and there is no handler in this name . handler is registered under default "root" handler . It will give you access.
import logging
from logging.config import dictConfig
logconfig = {
"version": 1,
"disable_existing_loggers": 0,
"root": {
"level": "DEBUG",
"handlers": [
"console",
"file",
"debugfile"
]
},
"loggers": {
},
"formatters": {
"precise": {
"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"
},
"brief": {
# Don't think we'll use.
"format": "%(levelname)-8s: %(name)-15s: %(message)s"
}
},
"handlers": {
"debugfile": {
"class": "logging.FileHandler",
"formatter": "precise",
"level": "DEBUG",
"mode": "a",
"filename": "debugAndUp.log"
},
"console": {
"class": "logging.StreamHandler",
"formatter": "precise",
"level": "DEBUG",
"stream": "ext://sys.stdout"
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "precise",
"level": "WARNING",
"backupCount": 3,
"maxBytes": 10240000,
"filename": "warningAndUp.log"
}
}
}
logs = dictConfig(logconfig)
logger = logging.getLogger()
logger.debug('Test')
for handles in logger.handlers:
print(handles.name)
handles.close()
Output -> Handlers List :
console
file
debugfile