Attributeerror: ‘module’ object has no attribute ‘handlers’ — Python sub module import problem

You want to log using Python’s logging module and use RotatingFileHandler to process the log so that new log files are regenerated if they exceed the specified size.

>

import logging

logger = logging.getLogger('mylogger')
logger.setLevel(logging.INFO)

fh=logging.handlers.RotatingFileHandler('/tmp/test.log', mode = 'a', maxBytes=10240, backupCount=3, encoding='utf-8')

formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

logger.addHandler(fh)

logger.info('hello logging')
logger.warning('hello logging')
logger.error('hello logging')
logger.critical('hello logging')

run times error:

AttributeError: ‘module’ object has no attribute ‘handlers’


import logging
import logging.handlers
……

Rerun, the program output normally.

import Logging
import Logging
import Logging
import Logging
import Logging
import Logging
import Logging
import Logging
import Logging
import Logging
import Logging
Therefore, it is necessary to explicitly import the logging.handlers submodule in the access TAB.

but sometimes, when importing some package does not require additional action will automatically import its module, this is because the set of packages for these operations in py files. In other cases, something else you import might also import logging.handlers. Anyway, just make sure that before visiting

The corresponding submodule has already been imported. Sometimes a module that looks like a package is not, such as OS and OS.Path. OS is not a package, it just provides another module called path, which you can access through os.path.


Read More: