Making Python loggers output all messages to stdout in addition to log file
All logging output is handled by the handlers; just add a logging.StreamHandler()
to the root logger.
Here's an example configuring a stream handler (using stdout
instead of the default stderr
) and adding it to the root logger:
import loggingimport sysroot = logging.getLogger()root.setLevel(logging.DEBUG)handler = logging.StreamHandler(sys.stdout)handler.setLevel(logging.DEBUG)formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')handler.setFormatter(formatter)root.addHandler(handler)
The simplest way to log to stdout:
import loggingimport syslogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
You could create two handlers for file and stdout and then create one logger with handlers
argument to basicConfig
. It could be useful if you have the same log_level and format output for both handlers:
import loggingimport sysfile_handler = logging.FileHandler(filename='tmp.log')stdout_handler = logging.StreamHandler(sys.stdout)handlers = [file_handler, stdout_handler]logging.basicConfig( level=logging.DEBUG, format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s', handlers=handlers)logger = logging.getLogger('LOGGER_NAME')