Writing logs to a file with python logging | Python

Python provides Logging module to handle logging usage. Logging has functions like debug(), info(), warning(), error, critical() for logging purpose.

Writing logs to file in Python

Writing logs to a file is a basic requirement for any application, below is the code snippet for writing logs.

Writing logs in append mode


# Import logging module
import logging

# Set logging level
logging.basicConfig(filename='sample.log', level=logging.DEBUG)

# Pass message to logging functions
logging.debug('This is debug message this should be written in sample.log file')
logging.info('Info message would be written in sample.log as level is DEBUG')
logging.warning('Warning message would be written in sample.log as level is DEBUG')
    

Writing fresh logs, without appending to the previous logs


# Import logging module
import logging

# Set logging level with filemode 'w'
logging.basicConfig(filename='sample.log', filemode='w', level=logging.DEBUG)

# Pass message to logging functions
logging.debug('This is debug message this should be written in sample.log file')
logging.info('Info message would be written in sample.log as level is DEBUG')
logging.warning('Warning message would be written in sample.log as level is DEBUG')
    

Above two snippets generates a file "sample.log" in current directory nd records the messages passed to logging functions.