Skip to content

Instantly share code, notes, and snippets.

@edvasqueza
Last active June 14, 2021 16:54
Show Gist options
  • Save edvasqueza/fd87f9f0a13ce02feca7c8eaf439ad2a to your computer and use it in GitHub Desktop.
Save edvasqueza/fd87f9f0a13ce02feca7c8eaf439ad2a to your computer and use it in GitHub Desktop.
Python Custom log handler for Cloud Run GCP
class GCPHandler(logging.StreamHandler):
def emit(self, record):
try:
msg = self.format(record)
stream = self.stream
trace = None
global_log_fields = {}
if request and 'X-Cloud-Trace-Context' in request.headers.keys() and GCP_PROJECT:
trace_header = request.headers.get("X-Cloud-Trace-Context")
trace = trace_header.split("/")[0]
global_log_fields[
"logging.googleapis.com/trace"
] = f"projects/{GCP_PROJECT}/traces/{trace}"
global_log_fields[
"logging.googleapis.com/sourceLocation"
] = dict(file=record.filename, line=record.lineno, function=record.funcName)
stream.write(json.dumps(dict(
message=msg,
timestamp=datetime.utcnow().isoformat(),
severity=record.levelname,
**global_log_fields,
)) + self.terminator)
self.flush()
except Exception:
self.handleError(record)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment