Open In App

Create a Log File in Python

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads