简体   繁体   中英

Issue with null logger (logging)

I have an issue where my code breaks when I do not want any logging. I control whether or not I wish to see logging with a '-v' option. I also have a 'd' option which sets a debug mode as well.

Right now my code breaks when the '-v' option is not specified.

def initLogging(cfg):

    cformat   = logging.Formatter('%(asctime)s   %(message)s', "%Y-%m-%d %H:%M:%S %Z")
    clogger   = None

    try:

        if cfg['debug']:
            loglevel = logging.DEBUG
        else:
            loglevel = logging.INFO

        logger = logging.getLogger()
        logger.setLevel(loglevel)

        if not cfg['verbose']:
            logger.addHandler(logging.NullHandler())
            return
        else:
            clogger = logging.StreamHandler()
            clogger.setLevel(loglevel)
            clogger.setFormatter(cformat)
            logger.addHandler(clogger)

    except Exception, error:
        sys.stderr.write("Error: Unable to initialize logging:  %s\n" % error)
        sys.stderr.flush()
        sys.exit(1)

    logger.info("Script initiated.")

    return logger

The error I get is this:

'NoneType' object has no attribute 'info'

This occurs when it reaches a logger statement like this:

logger.info("get_repl_actions(): executing REST query 'GET %s'" % rurl)

How can I tweak this so that it works when script is called without '-v'?

Try the following:

if not cfg['verbose']:
     logger.addHandler(logging.NullHandler())
     return logger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM