Skip to content

Instantly share code, notes, and snippets.

@jnahelou
Last active August 25, 2022 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnahelou/f3b6631db6760e962c10b88b887b96da to your computer and use it in GitHub Desktop.
Save jnahelou/f3b6631db6760e962c10b88b887b96da to your computer and use it in GitHub Desktop.
medium logging
import logging
import requests
import json
from opentelemetry.instrumentation.logging import LoggingInstrumentor
metadata_server = "http://metadata/computeMetadata/v1/"
metadata_flavor = {'Metadata-Flavor': 'Google'}
project_id = requests.get(
metadata_server + 'project/project-id', headers=metadata_flavor).text
structured_format = {
"message": "%(message)s",
"severity": "%(levelname)s",
"labels": {
"service_name": "%(otelServiceName)s",
"module": "%(module)s",
},
"logging.googleapis.com/sourceLocation": {
"file": "%(filename)s",
"line": "%(lineno)d",
"function": "%(name)s"
},
"logging.googleapis.com/spanId": "%(otelSpanID)s",
"logging.googleapis.com/trace": f'projects/{project_id}/traces/%(otelTraceID)s',
# Set trace_sampled to true to enable link from cloud logging to cloud trace
"logging.googleapis.com/trace_sampled": True,
}
LoggingInstrumentor().instrument(
logging_format=json.dumps(structured_format),
set_logging_format=True,
log_level=logging.DEBUG,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment