In addition to plain text log files, you can also log information in JSON format. JSON-formatted logs offer several advantages, including:
- Structured Data: JSON provides a structured format that is easier to parse and analyze using tools like Elasticsearch or Kibana.
- Machine Readability: JSON is machine-readable, making it suitable for automated processing and analysis.
- Flexibility: JSON can represent a wide range of data types and structures.
Creating a JSON Formatter
Import the JSON Formatter:
Python
import logging.json
Create a JSON Formatter:
Python
json_formatter = logging.json.JSONFormatter(
‘%(asctime)s %(name)s %(levelname)s %(message)s’,
ensure_ascii=False
)
This creates a JSON formatter that includes the timestamp, logger name, log level, and message in the JSON output. The ensure_ascii
parameter ensures that non-ASCII characters are properly encoded.
Adding the JSON Formatter to a Handler
Create a File Handler:
Python
file_handler = logging.FileHandler(‘app.json’)
Set the Formatter:
Python
file_handler.setFormatter(json_formatter)
Add the Handler to the Logger:
Python
logger.addHandler(file_handler)
Logging JSON Objects
To log JSON objects directly, use the json.dumps
function:
Python
import json
data = {"message": "This is a JSON object"}
logger.info(json.dumps(data))
Additional Considerations
- Logging Level: Adjust the logging level for the file handler to control which messages are written to the log file.
- Log Rotation: Consider using rotating file handlers to manage log file size.
- Log Analysis Tools: Use tools like Elasticsearch or Kibana to analyze JSON-formatted logs.