Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions samples/instrumentation-quickstart/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def multi():
def single():
"""Handle an http request by sleeping for 100-200 ms, and write the number of seconds slept as the response."""
duration = uniform(0.1, 0.2)
logger.info("handle /single request", extra={"duration": duration})
time.sleep(duration)
return f"slept {duration} seconds"

Expand Down
16 changes: 14 additions & 2 deletions samples/instrumentation-quickstart/gcp_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,30 @@
# limitations under the License.

import logging
from datetime import datetime
from typing import Optional

from opentelemetry.instrumentation.logging import LoggingInstrumentor
from pythonjsonlogger import jsonlogger


# We override JsonFormatter.formatTime() instead of using the datefmt strftime parameter
# because it does not support microsecond precision.


# [START opentelemetry_instrumentation_setup_logging]
class JsonFormatter(jsonlogger.JsonFormatter):
def formatTime(self, record: logging.LogRecord, datefmt: Optional[str] = None):
# Format the timestamp as RFC 3339 with microsecond precision
isoformat = datetime.fromtimestamp(record.created).isoformat()
return f"{isoformat}Z"


def setup_structured_logging() -> None:
LoggingInstrumentor().instrument()

log_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter(
formatter = JsonFormatter(
"%(asctime)s %(levelname)s %(message)s %(otelTraceID)s %(otelSpanID)s %(otelTraceSampled)s",
rename_fields={
"levelname": "severity",
Expand All @@ -32,7 +45,6 @@ def setup_structured_logging() -> None:
"otelSpanID": "logging.googleapis.com/spanId",
"otelTraceSampled": "logging.googleapis.com/trace_sampled",
},
datefmt="%Y-%m-%dT%H:%M:%SZ",
)
log_handler.setFormatter(formatter)
logging.basicConfig(
Expand Down