How to log both to console and file using Python?
Question: I am working Python and I need to logger so I decided to start using
RotatingFileHandler. Below is my `logging.conf` file

    
    
    [loggers]
    keys=root
    
    [handlers]
    keys=logfile
    
    [formatters]
    keys=logfileformatter
    
    [logger_root]
    level=DEBUG
    handlers=logfile
    
    [formatter_logfileformatter]
    format=%(asctime)s %(name)-12s: %(levelname)s %(message)s
    
    [handler_logfile]
    class=handlers.RotatingFileHandler
    level=NOTSET
    args=('ookagent.log', 'a', 50000000000, 5)
    formatter=logfileformatter
    

And below is my Python script from which I am successfully able to log to the
files. But I am not sure how to log both to files and console as well.

    
    
    #!/usr/bin/python
    import logging
    import logging.config
    import logging.handlers
    
    # using RotatingFileHandler for logging purpose
    logging.config.fileConfig('logging.conf')
    ooklogger = logging.getLogger('')
    
    
    ooklogger.info("HelloWorld")
    

Can we make a change in my logging.conf file by which I can login both to
console and files as well? Is it possible to do that?


Answer: Sure, the logging configuration file format lets you specify multiple
handlers. You can use a `StreamHandler` to log to the console. That would
entail modifications like these to your config file:

    
    
    [handlers]
    keys=logfile,logconsole
    
    [handler_logconsole]
    class=StreamHandler
    # other configuration directives as you like
    
    [logger_root]
    handlers=logfile,logconsole
    

See the [config file
documentation](http://docs.python.org/2/library/logging.config.html#configuration-
file-format) for more information and examples.

