Create a Log File in Python
Last Updated :
24 Apr, 2025
Logging is an essential aspect of software development, allowing developers to track and analyze the behavior of their programs. In Python, creating log files is a common practice to capture valuable information during runtime. Log files provide a detailed record of events, errors, and other relevant information, aiding in debugging and performance analysis. In this article, we will see how we can create a log file in Python.
What is a Log File in Python?
A log file in Python is a record of events generated by a program during its execution. It includes messages, warnings, and errors that can be crucial for understanding the program's behavior. Python provides a built-in module called logging
to facilitate easy logging.
Syntax
In the below syntax, the basicConfig
method is used to configure the logging module. The filename
parameter specifies the name of the log file and the level
parameter sets the logging level.
import logging
# Configure logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
# Log messages
logging.debug('This is a debug message')
Advantages of Log File in Python
- Debugging: Log files are invaluable during the debugging phase. They provide a detailed history of events, making it easier to identify and rectify issues.
- Performance Analysis: By analyzing log files, developers can gain insights into the performance of their applications. This includes execution times, resource usage, and potential bottlenecks.
- Error Tracking: Log files help in tracking errors and exceptions, providing detailed information about the context in which they occurred. This aids in fixing issues promptly.
How to Create a Log File in Python
Below, are the examples of how to Create a Log File in Python:
Example 1: Creating and Writing Log File
In this example, below Python script configures a basic logger to write warnings and higher severity to a file named 'gfg-log.log.' It also creates a custom logger with a file handler ('logs.log'). A warning message is logged both in the default logger and the custom logger with the associated file handlers.
Python3
import logging
logging.basicConfig(filename="gfg-log.log", filemode="w",
format="%(name)s → %(levelname)s: %(message)s")
logging.warning("warning")
logger = logging.getLogger(__name__)
FileOutputHandler = logging.FileHandler('logs.log')
logger.addHandler(FileOutputHandler)
logger.warning("test.")
Output:
root \u2192 WARNING: warning
__main__ \u2192 WARNING: test.
Example 2: Creating Log File and Logging Value
In this examples, below Python script configures logging to write messages with a custom format to a file named 'gfgnewlog.log.' A warning message is initially logged to the root logger, and then a custom logger is created with a file handler ('logs.log'). Another warning message is logged using the custom logger, and both messages are stored in their respective log files.
Python3
import logging
# Configure logging with a custom format
logging.basicConfig(filename="gfgnewlog.log", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s")
# Log a warning message
logging.warning("This is a warning")
# Create a logger instance
logger = logging.getLogger(__name__)
# Create a FileHandler to log to 'logs.log' file
file_handler = logging.FileHandler('logs.log')
# Add the FileHandler to the logger
logger.addHandler(file_handler)
# Log a warning message using the logger
logger.warning("This is a test.")
Output:
2024-02-15 11:25:59,067 - WARNING - This is a warning
2024-02-15 11:25:59,067 - WARNING - This is a test.
Similar Reads
Create A File If Not Exists In Python
In Python, creating a file if it does not exist is a common task that can be achieved with simplicity and efficiency. By employing the open() function with the 'x' mode, one can ensure that the file is created only if it does not already exist. This brief guide will explore the concise yet powerful
2 min read
Close a File in Python
In Python, a file object (often denoted as fp) is a representation of an open file. When working with files, it is essential to close the file properly to release system resources and ensure data integrity. Closing a file is crucial to avoid potential issues like data corruption and resource leaks.
2 min read
Parse and Clean Log Files in Python
Log files are essential for comprehending how software systems behave and function. However, because log files are unstructured, parsing and cleaning them can be difficult. We will examine how to use Python to efficiently parse and clean log files in this lesson. In this article, we will see how to
3 min read
Check end of file in Python
In Python, checking the end of a file is easy and can be done using different methods. One of the simplest ways to check the end of a file is by reading the file's content in chunks. When read() method reaches the end, it returns an empty string.Pythonf = open("file.txt", "r") # Read the entire cont
2 min read
Create a File Path with Variables in Python
The task is to create a file path using variables in Python. Different methods we can use are string concatenation and os.path.join(), both of which allow us to build file paths dynamically and ensure compatibility across different platforms. For example, if you have a folder named Documents and a f
3 min read
Check if a File Exists in Python
When working with files in Python, we often need to check if a file exists before performing any operations like reading or writing. by using some simple methods we can check if a file exists in Python without tackling any error. Using pathlib.Path.exists (Recommended Method)Starting with Python 3.4
3 min read
Python Delete File
When any large program is created, usually there are small files that we need to create to store some data that is needed for the large programs. when our program is completed, so we need to delete them. In this article, we will see how to delete a file in Python. Methods to Delete a File in Python
4 min read
Append Text or Lines to a File in Python
Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutori
3 min read
Print the Content of a Txt File in Python
Python provides a straightforward way to read and print the contents of a .txt file. Whether you are a beginner or an experienced developer, understanding how to work with file operations in Python is essential. In this article, we will explore some simple code examples to help you print the content
3 min read
Command Line File Downloader in Python
Python is one of the most popular general-purpose programming languages with a wide range of use cases from general coding to complex fields like AI. One of the reasons for such popularity of python as a programming language is the availability of many built-in as well as third-party libraries and p
4 min read