Skip to main content

A python logger similar to Go's slogger

Project description

SLogger

SLogger is a structured logger inspired by Go's slog, designed to simplify logging with key-value pairs in Python. It supports both plain text and JSON formats, with context fields being logged as top-level keys such as username and request_id.

Installation

Install SLogger via pip:

pip install roadsync_slogger

Basic Usage

SLogger logs messages along with additional context in a flat structure. Here's an example using the JSON format:

JSON Logging Example

from roadsync_slogger import SLogger

# Create SLogger instance with JSON format
logger = SLogger(format="json")

# Add initial context with username
logger = logger.with_fields(username="johndoe")

# Log a message with initial context
logger.info("User initialized session", request_id="abc123")
# Log output:
# {
#   "message": "User initialized session",
#   "username": "johndoe",
#   "request_id": "abc123"
# }

Using .with_fields()

The .with_fields() method allows you to persist fields across multiple log calls. Each call to .with_fields() returns a new SLogger instance with the added fields, leaving the original context unchanged.

Example:

# Adding fields using .with_fields()
logger = logger.with_fields(username="johndoe", request_id="abc123")

# Logging with the updated context
logger.info("Performed a profile update", action="update_profile")
# Log output:
# {
#   "message": "Performed a profile update",
#   "username": "johndoe",
#   "request_id": "abc123",
#   "action": "update_profile"
# }

Adding Context

You can continue adding fields with subsequent calls to .with_fields(), merging new context with existing fields. This allows for flexibility when extending the log context.

Example with Added Context:

# Initial logger with username field
logger = logger.with_fields(username="johndoe")

# Adding more context with action and request_id
logger = logger.with_fields(action="login", request_id="def456")
logger.info("Login successful")
# Log output:
# {
#   "message": "Login successful",
#   "username": "johndoe",
#   "request_id": "def456",
#   "action": "login"
# }

Full Config

@dataclass
class LogConfig:
    """
    Configuration for SLogger.

    Attributes:
        log_std: A callable for logging to stdout.
        log_err: A callable for logging to stderr.
        colors: A dictionary mapping log levels to their color codes.
        format: The log format, either "plain" or "json".
        json_formatter: A callable for formatting log entries in JSON.
        show_caller_info: A flag to include the caller's function name and line number.
    """
    log_std: Callable[[str], None]  # Function for logging to stdout (e.g., print)
    log_err: Callable[[str], None]  # Function for logging to stderr (e.g., print)
    colors: Dict[str, str]  # Colors for each log level
    format: str  # Log format: "plain" or "json"
    json_formatter: Callable[[Dict[str, Any]], bytes]  # Custom JSON formatter
    show_caller_info: bool  # Flag to include caller's function name and line number

full_config = LogConfig(...)

# Create SLogger instance with the full configuration
logger = SLogger(config=full_config)

Override Defaults

# Is the same as a new default config with just format and show_caller_info overriden
logger = SLogger(format='json', show_caller_info=True)

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

roadsync_slogger-1.1.2.tar.gz (4.9 kB view details)

Uploaded Source

Built Distribution

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

roadsync_slogger-1.1.2-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file roadsync_slogger-1.1.2.tar.gz.

File metadata

  • Download URL: roadsync_slogger-1.1.2.tar.gz
  • Upload date:
  • Size: 4.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.11.7 Linux/5.15.154+

File hashes

Hashes for roadsync_slogger-1.1.2.tar.gz
Algorithm Hash digest
SHA256 c7ceff0d0599f9aa7c8bc24cbf9b5670ae053c919c94c91c0f6ab4498e27062e
MD5 32c4d62ea50fc58e4a11d63c853818a3
BLAKE2b-256 1662ca384de50d0ae286f4fc8cbbf7f4b57ed90752132ba6c81f00a9f9e8497c

See more details on using hashes here.

File details

Details for the file roadsync_slogger-1.1.2-py3-none-any.whl.

File metadata

  • Download URL: roadsync_slogger-1.1.2-py3-none-any.whl
  • Upload date:
  • Size: 5.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.11.7 Linux/5.15.154+

File hashes

Hashes for roadsync_slogger-1.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 4343dd7b2999fcf6fd6bb9e1c00f934cf7bb794ac82e6577a0b864aa8adffbfd
MD5 5c84433a94d068138a438aaa5c401374
BLAKE2b-256 5e4c4a94a5c874c60699a1a37c226ee22f42e9db789a548953dc7fb683a524fd

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