Python logging.info() Display on Console and Save Message into File – Python Tutorial

By | September 25, 2019

In python, we can use logging library to save python message into a file, you can read this tutorial to know how to do.

Save Python Message into a Log File with logging – Deep Learning Tutorial

However, there is an problem, we can save the python message into a file, but we can not see them on our console.

For example:

logging.info("Loading data finished...")

We can save the “Loading data finished…” into a log file, however, this message can not be displayed on console, we can not see it.

How to set python message to display on console and save it into a file?

You should set a handler to the logging.

Import library

import logging

Set logging format

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='/domain-result.log',
                    filemode='w')

Set logging handler for console

console = logging.StreamHandler()
console.setLevel(logging.INFO)
# add the handler to the root logger
logging.getLogger().addHandler(console)

Show python message on console and save it into a file

logging.info("{}: step {}, loss {:g}".format(time_str, step, loss))

Here is result:

Python logging.info() Display on Console and Save Message into File

Leave a Reply