1

The following code prints both to the console and to the specified log-file - why? How can I tell logger to only use the filehandler? I tried to disable printing to console by commenting out line 8 (logger.setLevel(logging.INFO)), but the result of that was that the log file was created but empty. (I'm using logger in main() and in the class defined in the file)

if __name__ == "__main__":
    HOME_DIR = '/mydir'
    LOG_FILENAME = HOME_DIR + '/my.log'

    logging.info('Starting...')

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    fh = logging.FileHandler(LOG_FILENAME)
    fh = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                   maxBytes=10000,
                   backupCount=1,)
    fh.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    main()
Alexander
  • 541
  • 5
  • 13
  • 2
    Please, take a look at this answer: [How to I disable and re-enable console logging in Python?](http://stackoverflow.com/a/2267567/1532460) – awesoon Nov 03 '15 at 11:31
  • @soon, thank's, it solved the problem. But I'm still confused. I thought I only had one instance of logging - the logger. But now it seems that I also have logging as an instance...and with logging.propagate I control whether information is propagated to logging? – Alexander Nov 03 '15 at 11:48
  • Yes, you are right. You may read about logger hierarchy here: [15.7.1. Logger Objects](https://docs.python.org/2/library/logging.html#logger-objects) – awesoon Nov 03 '15 at 12:41

0 Answers0