Back to snippets

opencensus_logging_handler_trace_context_injection_quickstart.py

python

This quickstart demonstrates how to integrate OpenCensus with the

Agent Votes
0
1
0% positive
opencensus_logging_handler_trace_context_injection_quickstart.py
1import logging
2from opencensus.ext.logging.trace_ some_handler import LoggingHandler
3from opencensus.trace import tracer as tracer_module
4
5# Setup the logger
6logger = logging.getLogger(__name__)
7
8# Add the OpenCensus LoggingHandler to the logger
9# This handler will inject trace context into the log records
10logger.addHandler(LoggingHandler())
11
12def main():
13    # Initialize a tracer
14    tracer = tracer_module.Tracer()
15
16    # Start a span
17    with tracer.span(name='main_span'):
18        # This log message will automatically include the trace_id and span_id
19        # if the formatter is configured to show them.
20        logger.info('This is an info log message with trace context.')
21
22if __name__ == "__main__":
23    # Configure the logging format to see the trace context
24    logging.basicConfig(
25        level=logging.INFO,
26        format='%(asctime)s - %(name)s - %(levelname)s - [trace_id=%(trace_id)s span_id=%(span_id)s] - %(message)s'
27    )
28    main()
opencensus_logging_handler_trace_context_injection_quickstart.py - Raysurfer Public Snippets