Below is an example of a custom logging.Formatter that outputs logs in JSON Lines (jsonl) format with the date, filename, line number, and message as keys:
import logging
import json
class JsonFormatter(logging.Formatter):
def format(self, record):
# Construct a dict with the desired log attributes.
log_record = {
"date": self.formatTime(record, self.datefmt),
"filename": record.filename,
"line": record.lineno,
"message": record.getMessage(),
}
# Return the JSON-formatted string
return json.dumps(log_record)
# Example usage:
if __name__ == "__main__":
logger = logging.getLogger("jsonLogger")
logger.setLevel(logging.DEBUG)
# Create a stream handler (writes to stdout)
stream_handler = logging.StreamHandler()
# Specify a date format if desired
datefmt = "%Y-%m-%d %H:%M:%S"
stream_handler.setFormatter(JsonFormatter(datefmt=datefmt))
logger.addHandler(stream_handler)
# Example log message
logger.info("This is a test log message")
Explanation
-
Custom Formatter Class: The JsonFormatter class inherits from logging.Formatter and overrides the format method. Inside this method, a dictionary (log_record) is populated with:
date: Formatted using the formatTime method.
filename: The name of the file that issued the log.
line: The line number in the file.
message: The log message.
-
JSON Output: The dictionary is then converted to a JSON string using json.dumps.
-
Usage: The custom formatter is attached to a stream handler, which is added to the logger. When you log messages, they are output as JSON objects on separate lines (jsonl format).
You can adapt this further by adding more fields if needed or write the output to a file instead of standard output.