Skip to content

Python logging to file

  • by

You can use the logging module to accomplish logging into the file in Python. In order, the five parts do the following:

  1. set the output file (filename=logname)
  2. set it to append rather than overwrite (filemode='a')
  3. determine the format of the output message (format=...)
  4. determine the format of the output time (datefmt='%H:%M:%S')
  5. 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:'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

                    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                    level=logging.DEBUG)"Running Urban Planning")

logger = logging.getLogger('urbanGUI')


Python logging to file

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.

Leave a Reply

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