Skip to content

Handler fails to send logs when created with initial labels until recreated #57

@reggaeshark888

Description

@reggaeshark888

Description

When creating a LokiLoggerHandler with initial labels, logs are not sent to Loki until the handler is recreated (e.g., by updating labels). The handler appears to log locally but messages never reach the Loki server.

Steps to Reproduce

  1. Create a LokiLoggerHandler with initial labels
  2. Add it to a Python logger
  3. Send a log message
  4. Check Loki - the message is not there

Code to Reproduce

import logging
from loki_logger_handler.loki_logger_handler import LokiLoggerHandler

# Create handler with initial labels
handler = LokiLoggerHandler(
    url="http://localhost:3100/loki/api/v1/push",
    labels={"app": "test_app", "env": "dev"},
    timeout=10,
    compressed=True
)

# Set up logger
logger = logging.getLogger("test")
logger.setLevel(logging.INFO)
logger.addHandler(handler)

# This log doesn't reach Loki
logger.info("This message won't appear in Loki")

# Workaround: Remove and re-add handler
logger.removeHandler(handler)
logger.addHandler(handler)

# Now logs work
logger.info("This message WILL appear in Loki")

Expected Behavior
Logs should be sent to Loki immediately after handler creation.
Actual Behavior
Logs are only sent after the handler is removed and re-added to the logger, or after labels are updated.
Environment

Python version: 3.11.9
loki-logger-handler version: [check with pip show loki-logger-handler]
OS: Windows 11

Analysis
The issue appears to be related to the handler's flush thread initialization. The thread starts in __init__ but doesn't properly connect to the logging pipeline until the handler is reconfigured.
Workaround
Remove and re-add the handler after creation:
pythonlogger.addHandler(handler)
logger.removeHandler(handler)
logger.addHandler(handler)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions