python logging printing empty lines message for print

882 Views Asked by At

We are trying to introducing python logging in out existing python project.

As we already have lot more print statement in code, we decided to redirect all print logs to logging file using below statement.

import logging, sys
import os
from logging.handlers import TimedRotatingFileHandler
formatter = logging.Formatter("%(asctime)s - %(pathname)s - %(funcName)s - %(levelname)s - %(message)s")
log_path = '/logs/server.log'
handler = TimedRotatingFileHandler(filename=log_path, when='midnight')
handler.setFormatter(formatter)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(handler)
sys.stderr.write = log.error
sys.stdout.write = log.info

However, it printing two lines with second as empty logs.

2020-09-21 09:03:05,978 - utils.py - logger - INFO - <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>
2020-09-21 09:03:05,978 - utils.py - logger - INFO -

2020-09-21 09:03:05,978 - utils.py - logger - INFO - 1600693385   Mon Sep 21 09:03:05 2020        19882 Registering functions
2020-09-21 09:03:05,978 - utils.py - logger - INFO -

It is working for logging function like info, error. it only giving issue for print.

It would be great help if someone know cause of it.

In additional detail, we are using gunicorn as server and falcon as rest framework.

1

There are 1 best solutions below

0
On

You should not modify the write functions of stdout and stderr but add a stream handler for info and for error (one on stdout and the other one on stderr)

You can find an example on SO here: https://stackoverflow.com/a/31459386/14306518