Create a Log File in Python
Last Updated :
28 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
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
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
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
Check If a Text File Empty in Python Before performing any operations on your required file, you may need to check whether a file is empty or has any data inside it. An empty file is one that contains no data and has a size of zero bytes. In this article, we will look at how to check whether a text file is empty using Python.Check if a
4 min read
Create a watchdog in Python to look for filesystem changes Many times a file is needed to be processed at the time of its creation or its modification. This can be done by following changes in a particular directory. There are many ways in python to follow changes made in a directory. One such way is to use the watchdog module. As the name suggests this mod
4 min read
How to Write a Configuration File in Python? Configuring your Python applications using configuration files is a common practice that allows you to separate configuration details from your code, making it more modular and easier to manage. In this article, we'll explore how to create a configuration file in Python, focusing on a simple and wid
3 min read
How To Detect File Changes Using Python In the digital age, monitoring file changes is essential for various applications, ranging from data synchronization to security. Python offers robust libraries and methods to detect file modifications efficiently. In this article, we will see some generally used method which is used to detect chang
3 min read