You can use the logging
module to accomplish logging into the file in Python. In order, the five parts do the following:
- set the output file (
filename=logname
) - set it to append rather than overwrite (
filemode='a'
) - determine the format of the output message (
format=...
) - determine the format of the output time (
datefmt='%H:%M:%S'
) - and determine the minimum message level it will accept (
level=logging.DEBUG
).
logging.basicConfig(filename="logfilename.log", level=logging.INFO)
There are a number of different levels that you can use to write to the file, such as:
logging.info('your text goes here')
logging.error('your text goes here')
logging.debug('your text goes here')
Python logging to file
Simple example code Create a log file in Python.
import logging
logging.basicConfig(filename="logfilename.log",
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
logger = logging.getLogger('urbanGUI')
Output:
Do comment if you have any doubts or suggestions on this Python logging topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.