简体   繁体   中英

Logging module not working correctly on python 2.4

I'm having trouble using logging in python 2.4 with multiple stream handlers. This is running on a linux host running 64-bit kernel 2.6.32.

When I use basic logging like the following it works fine:

logging.basicConfig(filename=logfile, filemode="w", level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', format=logformat)
logging.info("Hello world")

For my current project, I want to log to a file and to the console (and eventually to syslog as well) and I can't get this to work. I don't get any errors, just nothing gets logged. The logfile gets created but is empty. (filesize=0)

Here is my code:

config = {
            'debug':            1,
            'verbose':          1,
            'logdir':           '/tmp',
            'logfilename':      'JobRunner.log'
         }

def initLogging(config):

    logfile   = os.path.join(config['logdir'], config['logfilename'])
    print "DEBUG: logfile=%s" % logfile
    loglevel  = logging.INFO
    logformat = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')

    if config['debug']:
        loglevel = logging.DEBUG

    if not os.path.exists(config['logdir']):
        os.makedirs(config['logdir'])

    try:
        logger = logging.getLogger('core')
        filelogger = logging.FileHandler(logfile, 'w')
        # dummy down my code and use the module var instead of using my loglevel var
        filelogger.setLevel(logging.DEBUG)
        filelogger.setFormatter(logformat)
        logger.addHandler(filelogger)
    except Exception, error:
        print "error: %s" % error

    try:
        if config['verbose']:
            console = logging.StreamHandler()
            console.setLevel(logging.DEBUG)
            console.setFormatter(logformat)
            logger.addHandler(console)
    except Exception, error:
        print "error: %s" % error

    try:
        logger.info("script initiated")
        logger.info("log file '%s' opened." % logfile)
    except Exception, error:
        print "error: %s" % error

    return logger

if __name__ == "__main__":
    log = initLogging(config)
    log.info("Hello")

I'm not sure where the issue is. This code matches several other accepted answers I've found on this site.

You need to set the level on the logger too :

logger.setLevel(logging.DEBUG if config['debug'] else logging.INFO)

otherwise it'll be configured for logging.WARNING and up only:

>>> log = initLogging({'logdir': '/tmp', 'logfilename': 'test.log',
                       'debug': False, 'verbose': True})
>>> log.getEffectiveLevel()
30
>>> log.setLevel(logging.INFO)
>>> log.info('Hello')
2014-08-07 18:13:19,035 INFO     Hello
>>> print open('/tmp/test.log').read()
2014-08-07 18:13:19,035 INFO     Hello

You would only set levels on the handlers if you wanted specific handlers to filter out messages; they are set to NOTSET initially so that they'll handle anything the logger handles.

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