Skip to content
Advertisement

Python logging: how to write logs into file and stdout

I have a main file where I use all the functions from the module. I want to log all the necessary things into file and into stdout.

It works when I use logger.info("Write it into file") inside main file, but it doesn’t work when I import here some functions from the other scripts.

I use it inside main file to make a logger

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create file handler
fh = logging.FileHandler('logging.log', mode='a')
fh.setLevel(logging.DEBUG)
# create console handler
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

And in other file I use only

logger = logging.getLogger(__name__)

How can I get all the logs?

Advertisement

Answer

__name__ has different values in your two modules, so you really have two different loggers. You are only adding the file handler to one of them.

You want to configure a common ancestor. That could be the root logger:

root_logger = logging.getLogger()
...
root_logger.addHandler(fh)
root_logger.addHandler(ch)

or a specific logger that only your two loggers inherit from.

base_logger = logging.getLogger('base')
# configure base_logger

logger_in_main = logging.getLogger('base.' + __name__)

and

logger_in_other = logging.getLogger('base.' + __name__)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement