Splunk Logging Handler

3.0.0 · active · verified Sun Apr 12

The `splunk-handler` library provides a Python logging handler for sending log events to a Splunk Enterprise instance. It leverages the Splunk HTTP Event Collector (HEC) for data ingestion. The current version is 3.0.0, and the project maintains an active release cadence, addressing bug fixes, new features, and Python compatibility updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure and use `splunk-handler` to send log messages to Splunk Enterprise via the HTTP Event Collector. It uses environment variables for sensitive connection details and includes an example of `force_flush` for critical environments like AWS Lambda. Ensure your Splunk HEC is properly configured and accessible from where this code runs.

import logging
import os
from splunk_handler import SplunkHandler, force_flush

# Configure Splunk HEC details via environment variables
SPLUNK_HOST = os.environ.get('SPLUNK_HOST', 'splunk.example.com')
SPLUNK_PORT = os.environ.get('SPLUNK_PORT', '8088')
SPLUNK_TOKEN = os.environ.get('SPLUNK_TOKEN', 'YOUR_SPLUNK_HEC_TOKEN')
SPLUNK_INDEX = os.environ.get('SPLUNK_INDEX', 'main')

# Initialize the SplunkHandler
try:
    splunk_handler = SplunkHandler(
        host=SPLUNK_HOST,
        port=SPLUNK_PORT,
        token=SPLUNK_TOKEN,
        index=SPLUNK_INDEX,
        protocol='https', # Use 'http' if SSL is not configured
        verify=True,      # Set to False if using self-signed certs and not providing CA
        flush_interval=1.0 # Send logs every 1 second for demonstration
    )
    # Add the handler to the root logger
    logging.getLogger('').addHandler(splunk_handler)
    logging.getLogger('').setLevel(logging.INFO)

    # Example log messages
    logging.info('Hello from splunk-handler!')
    logging.warning('This is a warning message.')
    logging.error('An error occurred: %s', 'something went wrong')

    # For environments like AWS Lambda, ensure logs are flushed before exiting.
    # In a typical application, the atexit hook handles this, but explicit call might be needed.
    force_flush()
    print('Logs sent to Splunk (check your Splunk instance).')

except Exception as e:
    print(f"Failed to configure Splunk handler or send logs: {e}")
    print("Please ensure SPLUNK_HOST, SPLUNK_PORT, SPLUNK_TOKEN, and SPLUNK_INDEX are correctly set.")
    print("Also, verify that Splunk HEC is enabled and accessible.")

view raw JSON →