How to Log Locally in Python
Logs play a pivotal role in debugging, error tracking, and monitoring code execution. Python offers a built-in logging library that simplifies log output. In this article, we'll delve into the process of logging locally in Python.
1. Importing the Logging Library
To kick things off, begin by importing the logging
library, a part of Python's standard library designed to support logging functionality.
import logging
2. Configuring Logging
The configuration of logging encompasses specifying where logs should be directed, setting the log level, and defining the log message format. Here's a fundamental logging configuration:
logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
-
filename
: This denotes the file where logs will be recorded. Feel free to alter this to match your preferences. -
level
: The log level, with options such as DEBUG (the most detailed), INFO, WARNING, ERROR, and CRITICAL (the most critical). Select the appropriate level based on your application's needs. -
format
: This dictates the log message format. In this example, it includes a timestamp, log level, and message, but it's customizable according to your requirements.
3. Logging Messages
To log messages, leverage the logging
library for generating log messages.
logging.debug('This is a debug message.')
logging.info('This is an info message.')
logging.warning('This is a warning message.')
logging.error('This is an error message.')
logging.critical('This is a critical error message.')
4. Logging in Action
Here's a practical illustration. Each time this program runs, it appends logs to the 'app.log' file.
import logging
logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
def main():
logging.debug('The program has started.')
# Insert your program code here
if __name__ == '__main__':
main()
logging.info('The program has terminated successfully.')
This allows you to track your program's progress using logs and identify errors when necessary.
Top comments (0)