Skip to main content

A custom formatter for Python's logging module that outputs logs in the Bunyan JSON format.

Project description

Bunyan Formatter

A custom formatter for Python's logging module that outputs logs in the Bunyan JSON format.

Description

This package provides a BunyanFormatter class that formats log records into the Bunyan JSON format. Bunyan is a lightweight JSON logger for Node.js, but this formatter allows you to use the same log format in Python projects.

Key features:

  • Outputs logs in JSON format
  • Includes project name, hostname, file path, line number, and other metadata
  • Supports various log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  • Handles both project and external file paths

Installation

To install the Bunyan Formatter package, run:

pip install bunyan-formatter

Usage

Here's a basic example of how to use the Bunyan Formatter in your Python project:

import logging
from bunyan_formatter import BunyanFormatter

# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Create a handler and set the formatter
handler = logging.StreamHandler()
formatter = BunyanFormatter(project_name="MyProject", project_root="/path/to/my/project")
handler.setFormatter(formatter)

# Add the handler to the logger
logger.addHandler(handler)

# Now you can use the logger
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

Django

In your Django project's settings.py file, add the following logging configuration:

BASE_DIR = Path(__file__).resolve().parent.parent

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "bunyan": {
            "()": BunyanFormatter,
            "project_name": "MyProject",
            "project_root": BASE_DIR,
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "bunyan",
            "stream": "ext://sys.stdout",
        },
        "file": {
            "level": "DEBUG",
            "class": "logging.FileHandler",
            "filename": BASE_DIR / "logs" / "django.log",
            "formatter": "bunyan",
        },
    },
    "root": {
        "level": "DEBUG",
        "handlers": ["console", "file"],
    },
}

Examples

Basic Logging

logger.info("User logged in", extra={"username": "john_doe"})

Output:

{
  "v": 0,
  "name": "MyProject",
  "msg": "User logged in",
  "level": 30,
  "levelname": "INFO",
  "hostname": "your-hostname",
  "target": "__main__",
  "line": 10,
  "file": "main.py",
  "extra": {
    "username": "john_doe"
  }
}

Error Logging with Exception

try:
    result = 1 / 0
except ZeroDivisionError as e:
    logger.exception("An error occurred", exc_info=True)

Output:

{
  "v": 0,
  "name": "MyProject",
  "msg": "An error occurred",
  "level": 50,
  "levelname": "ERROR",
  "hostname": "your-hostname",
  "target": "__main__",
  "line": 15,
  "file": "main.py",
  "err": {
    "message": "division by zero",
    "name": "ZeroDivisionError",
    "stack": [
      // Stack trace here
    ]
  }
}

Custom Fields

You can add custom fields to your log entries:

logger.info("Order processed", extra={
    "order_id": 12345,
    "customer_id": 67890,
    "total_amount": 100.00
})

Output:

{
  "v": 0,
  "name": "MyProject",
  "msg": "Order processed",
  "level": 30,
  "levelname": "INFO",
  "hostname": "your-hostname",
  "target": "__main__",
  "line": 20,
  "file": "main.py",
  "extra": {
    "order_id": 12345,
    "customer_id": 67890,
    "total_amount": 100.0
  }
}

Contributing

Contributions are welcome! Please submit pull requests or issues on our GitHub repository.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bunyan_formatter-1.0.2.tar.gz (35.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bunyan_formatter-1.0.2-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file bunyan_formatter-1.0.2.tar.gz.

File metadata

  • Download URL: bunyan_formatter-1.0.2.tar.gz
  • Upload date:
  • Size: 35.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for bunyan_formatter-1.0.2.tar.gz
Algorithm Hash digest
SHA256 75ee93d8094eb3b472e9fffc1babfa596cd90ff0e9aa900bfd6bf45838fff503
MD5 777bdee14c46f57643e8a24d01ccab10
BLAKE2b-256 1399e791237ccf0dff4384a73166d897a96a0837cb34cc8784203fc8626bb176

See more details on using hashes here.

File details

Details for the file bunyan_formatter-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for bunyan_formatter-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 bb1ab9d0c864aee89bee642e49061e000f310a0963066dce161e37e7d12369a6
MD5 eacca3f7e27dfc03e3a09570d5eed2bb
BLAKE2b-256 d13bee1445709823dc0bc36d1179fac98405cc427f2d9a42b4cf5201e274a5c6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page