Thomas Browne
Thomas Browne

Reputation: 24888

How to redirect another library's console logging messages to a file, in Python

The fastAPI library that I import for an API I have written, writes many logging.INFO level messages to the console, which I would like either to redirect to a file-based log, or ideally, to both console and file. Here is an example of fastAPI module logging events in my console:

enter image description here

So I've tried to implement this Stack Overflow answer ("Easy-peasy with Python 3.3 and above"), but the log file it creates ("api_screen.log") is always empty....

# -------------------------- logging ----------------------------
logging_file = "api_screen.log"

logging_level = logging.INFO
logging_format = '  %(message)s'
logging_handlers = [logging.FileHandler(logging_file), logging.StreamHandler()]

logging.basicConfig(level = logging_level, format = logging_format, handlers = logging_handlers)
logging.info("------logging test------")

Even though my own "------logging test------" message does appear on console within the other fastAPI logs:

enter image description here

As you can see here it's created the file, but it has size zero.

enter image description here

So what do I need to do also to get the file logging working?

Upvotes: 0

Views: 1070

Answers (1)

blues
blues

Reputation: 5185

There are multiple issues here. First and most importantly: basicConfig does nothing if a logger is already configured, which fastAPI does. So the handlers you are creating are never used. When you call logging.info() you are sending a log to the root logger which is printed because the fastAPI has added a handler to it. You are also not setting the level on your handlers. Try this code instead of what you currently have:

logging_file = "api_screen.log"
logging_level = logging.INFO

logging_fh = logging.FileHandler(logging_file)
logging_sh = logging.StreamHandler()
logging_fh.setLevel(logging_level)
logging_sh.setLevel(logging_level)

root_logger = logging.getLogger()
root_logger.addHandler(logging_fh)
root_logger.addHandler(logging_sh)

logging.info('--test--')

Upvotes: 1

Related Questions