Last active
June 14, 2021 16:54
-
-
Save edvasqueza/fd87f9f0a13ce02feca7c8eaf439ad2a to your computer and use it in GitHub Desktop.
Python Custom log handler for Cloud Run GCP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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