Gabor Urban wrote:
Hi guys,

I have embarassing problem using the logging module. I would like to
encapsulate the creation and setting up  of the logger in a class, but
it does not seem working.

Here are my relevant parts of the code:

--
import sys
import logging

class LogClass:
    def __init__(self, fileName, loggerName = 'classLog'):
        self.Logger = logging.getLogger(loggerName)
        self.traceName = fileName
        handler = logging.FileHandler(self.traceName,'a')
        formatter = logging.Formatter("%(name)s %(asctime)s
%(filename)s %(lineno)d %(levelname)s %(message)s")
        handler.setFormatter(formatter)
        self.Logger.addHandler(handler)
        self.Handler = handler

    def closeLog(self):
        self.Handler.flush()
        self.Handler.close()

    def fetchLogger(self):
        return self.Logger

if __name__ == "__main__":
    name = 'testlog.trc'
    classLog = LogClass(name)
    logger = classLog.fetchLogger()
    logger.info("Created")
    logger.debug("Test")
    logger.info("Created .. ")
    logger.debug("Test data")
    classLog.closeLog()

--

The trace file is created properly but contains no lines at all. If I
put the code directly in __main__, it works fine.

What did I miss? Any ideas are wellcome.

Gabor
As pointed out you should definitely split the logger creation from its configuration, here are my 2 cents:

import logging

_LOGGER_NAME = 'foo'

class MyFileHandler(logging.FileHandler):
FORMAT = '%(name)s %(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s'

   def __init__(self, fileName):
        logging.FileHandler.__init__(self, fileName, 'a')
       self.setFormatter(logging.Formatter(self.FORMAT))

if __name__ == '__main__':
        # split creation from configuration
        # creation
        logger = logging.getLogger(_LOGGER_NAME)
        # configuration
        logger.addHandler(MyFileHandler('anyfile.tmp'))
        logger.setLevel(logging.DEBUG)
        logger.info('bar')

I personally use the following pattern:

In any submodule moduleA.py of an application:

import MyApp
_logger = logging.getLogger(MyApp.logger.name + '.moduleA') # attach my logger to MyApp logger
# Configuration : nothing to be done, relies on MyApp configuration logger

# You can add code in case you are executing your module in standalone mode (for unit testing for instance)

if __name__ == '__main__':
        _logger = logging.getLogger('moduleA')
        _logger.addHandler(logging.FileHandler('moduleA.test','a'))
        # here is some unit tests



Jean-Michel
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to