[AstroPy] Astropy logging configuration

Adrian Price-Whelan adrianmpw at gmail.com
Mon Mar 27 09:44:06 EDT 2017


Interested to hear if there is a better solution (I run in to this
too). The hack I've used to suppress the duplicates is to remove all
handlers from the logger after importing astropy but before adding my
own. For your example:

import logging
import astropy
logger = logging.getLogger('astropy')
for handler in logger.handlers:
    logger.removeHandler(handler)

formatter = logging.Formatter(fmt="%(asctime)s [%(levelname)s] %(message)s")
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

logger.info('Hello')
astropy.log.info('Bye')

output is then:
2017-03-27 09:43:34,319 [INFO] Hello
2017-03-27 09:43:34,321 [INFO] Bye

On Mon, Mar 27, 2017 at 3:05 AM, Evert Rol <evert.rol at gmail.com> wrote:
> Is there a way to configure the astropy logger using the standard Python logging configuration?
> If I try the code below, I actually get double output, with only one of the two lines using the format I specified.
> More specifically, I'd like to be able to use a config dict, or a yaml file that may contain the configuration for several loggers: some may require a a debug level (for specific packages I'm debugging), while I'd like to silence others (to a warning or error level); so a global (root) logging configuration doesn't really work.
> (I realise that the amount of logging in astropy is low to non-existent, even at the debug level.)
>
> Practically, this issue came up when using a Django application, where I tried to set the various loggers in the Django settings file. That doesn't work (and caused some headaches, because astropy needs to be imported before Django sets up its loggers, which means it needs to be imported outside the whole Django project).
>
>
>   Evert
>
>
> import logging
> import astropy
> logger = logging.getLogger('astropy')
> formatter = logging.Formatter(fmt="%(asctime)s [%(levelname)s] %(message)s")
> handler = logging.StreamHandler()
> handler.setLevel(logging.DEBUG)
> handler.setFormatter(formatter)
> logger.addHandler(handler)
> logger.setLevel(logging.INFO)
>
> logger.info('Hello')
> astropy.log.info('Bye')
>
>
> output:
> INFO: Hello [__main__]
> 2017-03-27 14:05:28,330 [INFO] Hello
> INFO: Bye [__main__]
> 2017-03-27 14:05:29,341 [INFO] Bye
>
> _______________________________________________
> AstroPy mailing list
> AstroPy at python.org
> https://mail.python.org/mailman/listinfo/astropy



-- 
Adrian M. Price-Whelan
Lyman Spitzer, Jr. Postdoctoral Fellow
Princeton University
http://adrian.pw


More information about the AstroPy mailing list