Python printing to screen and writing to a file at the same time

You create a Python script. If you need print to screen and writing to a log file at the same time, you could use the under source code.

We have to use the logging library. Let’s see it here: https://docs.python.org/3/library/logging.html

Here is the source code which is written in Python3

[sourcecode language=”python” wraplines=”false” collapse=”false”] import logging
## CONFIG LOG
#
globalLogLevel = logging.INFO
#globalLogLevel = logging.DEBUG
globalLogFormat = ‘%(asctime)s %(levelname)-4s %(filename)s:%(lineno)d %(message)s’
globalLogFile = ‘app.log’
globalDateFmt = ‘%Y%m%d %H:%M:%S’

# Config loggin global
# set up logging to file – see previous section for more details
logging.basicConfig(level=globalLogLevel,
format=globalLogFormat,
datefmt=globalDateFmt,
filename=globalLogFile)

# Config log to console
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(globalLogLevel)
# set a format which is simpler for console use
formatter = logging.Formatter(globalLogFormat, datefmt=globalDateFmt)
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger(”).addHandler(console)
[/sourcecode]

 

Hope it help !

Leave a Reply

Your email address will not be published. Required fields are marked *