To store your log messages in a JSON file instead of printing them to the console, you can create a file handler in addition to the console handler. Below is an updated version of the previous example that writes logs to a JSON file.
Step-by-Step Instructions:
-
Install json-logger: If you haven't done this already, ensure you have the json-logger package installed.
pip install python-json-logger
-
Update the Logger to Use a File Handler: Here’s how to set up a JSON logger that writes to a file:
import logging
import sys
from pythonjsonlogger import jsonlogger
# Create a custom logger
logger = logging.getLogger("my_json_logger")
# Set the default logging level
logger.setLevel(logging.DEBUG)
# Create a file handler to write log messages to a file
file_handler = logging.FileHandler("logs.json") # Specify the log file name
file_handler.setLevel(logging.DEBUG) # Choose your level (DEBUG, INFO, etc.)
# Create a console handler for output (optional)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
# Define the JSON formatter
formatter = jsonlogger.JsonFormatter()
# Set the formatter for both handlers
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)
# Example logging
logger.debug("This is a debug message")
logger.info("This is an info message", extra={"user": "john_doe"})
logger.warning("This is a warning message", extra={"module": "main"})
logger.error("This is an error message", extra={"error": "Not Found"})
logger.critical("This is a critical message")
Explanation of Changes:
-
File Handler: A FileHandler is created for logs.json. This handler will write logs directly to this file.
-
Set Levels: The logging level for the file handler is set to DEBUG, capturing all log messages.
-
Formatter: The same JsonFormatter is applied to both handlers (the file handler and, optionally, a console handler for real-time viewing).
-
Log to Both Destinations: Now, any messages logged will be output in JSON format both to logs.json and the console.
Running the Logger
When you run this script, it will create (or append to) a file named logs.json and the log messages will be formatted in JSON.
Example of logs.json Output
Here's what you might see in logs.json after running the script:
{"asctime": "2023-10-01 12:00:00,000", "message": "This is a debug message", "levelname": "DEBUG", "name": "my_json_logger"}
{"asctime": "2023-10-01 12:00:00,001", "message": "This is an info message", "levelname": "INFO", "name": "my_json_logger", "user": "john_doe"}
{"asctime": "2023-10-01 12:00:00,002", "message": "This is a warning message", "levelname": "WARNING", "name": "my_json_logger", "module": "main"}
{"asctime": "2023-10-01 12:00:00,003", "message": "This is an error message", "levelname": "ERROR", "name": "my_json_logger", "error": "Not Found"}
{"asctime": "2023-10-01 12:00:00,004", "message": "This is a critical message", "levelname": "CRITICAL", "name": "my_json_logger"}
Note on Appending
The default behavior of FileHandler is to append to the log file if it already exists. If you wish to overwrite the file each time you run your script, you can use:
file_handler = logging.FileHandler("logs.json", mode='w')
This will clear the contents of logs.json each time the script is executed.