0

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?

Thomas Browne
  • 23,824
  • 32
  • 78
  • 121

1 Answers1

1

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--')
blues
  • 4,547
  • 3
  • 23
  • 39
  • Works great, and actually because console logging is already set by fastapi, I don't need the streamhandlers, only the filehandler. Now another question, how do I set the message format for logging_fh? Right now it's only printing out the log message but i want to add a timestamp. – Thomas Browne Oct 13 '20 at 13:44
  • figured it out. Use formatter = logging.Formatter("message format goes here") then logging_fh.setFormatter(formatter). – Thomas Browne Oct 13 '20 at 14:00