how to enable logging in my agent code? i am using...
# ask-ai
k
how to enable logging in my agent code? i am using livekit agent boiler plate code and wants to see logs to understand how much each component ( stt, tts, llm ) taking.
t
Thanks for reaching out, Saurav. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
👀 1
To enable logging in your LiveKit agent boilerplate code and monitor components like STT, TTS, and LLM, follow these steps: 1. Import the Metrics Module:
from livekit.agents import metrics
2. Set Up Logging:
Copy code
import logging
logger = logging.getLogger("agent-metrics")
logger.setLevel(<http://logging.INFO|logging.INFO>)
3. Subscribe to Metrics Events: Use the
metrics_collected
event to capture metrics for each component:
Copy code
@agent.on("metrics_collected")
def _on_metrics_collected(ev: metrics.MetricsCollectedEvent):
    metrics.log_metrics(ev.metrics, logger=logger)
4. Log Specific Metrics: For detailed logging of each component:
Copy code
@agent.on("metrics_collected")
def _on_metrics_collected(ev: metrics.MetricsCollectedEvent):
    if isinstance(ev.metrics, metrics.STTMetrics):
        <http://logger.info|logger.info>(f"STT Metrics: Audio Duration: {ev.metrics.audio_duration}, Streamed: {ev.metrics.streamed}, Error: {ev.metrics.error}")
    elif isinstance(ev.metrics, metrics.TTSMetrics):
        <http://logger.info|logger.info>(f"TTS Metrics: Audio Duration: {ev.metrics.audio_duration}, TTFB: {ev.metrics.ttfb}")
    elif isinstance(ev.metrics, metrics.LLMMetrics):
        <http://logger.info|logger.info>(f"LLM Metrics: TTFT: {ev.metrics.ttft}, Tokens per Second: {ev.metrics.tokens_per_second}, Total Tokens: {ev.metrics.total_tokens}")
5. Aggregate Metrics: Use the
UsageCollector
class to aggregate metrics across a session:
Copy code
usage_collector = metrics.UsageCollector()
@agent.on("metrics_collected")
def _on_metrics_collected(ev: metrics.MetricsCollectedEvent):
    usage_collector.collect(ev.metrics)
async def log_usage():
    summary = usage_collector.get_summary()
    <http://logger.info|logger.info>(f"Usage Summary: {summary}")
For more advanced use cases, such as sending metrics to a server, you can modify the event handler to send data to an HTTP endpoint. Let me know if you need further assistance!
k
but how to integrate it with existing logger like log guru
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!