Last active
April 10, 2023 11:05
-
-
Save glucazeau/84c52b910a42f870e011746ebe29a61e to your computer and use it in GitHub Desktop.
Using Loguru with Google Cloud Logging in a Cloud Function
This file contains 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
import json | |
from loguru import logger | |
# From: https://cloud.google.com/run/docs/logging#writing_structured_logs | |
class CloudLoggingHandler: | |
def __init__(self, request): | |
project = "" # Add your project name here | |
self.global_log_fields = {} | |
trace_header = request.headers.get("X-Cloud-Trace-Context") | |
if trace_header and project: | |
trace = trace_header.split("/") | |
self.global_log_fields[ | |
"logging.googleapis.com/trace" | |
] = f"projects/{project}/traces/{trace[0]}" | |
def write(self, message): | |
entry = dict( | |
severity=message.record["level"].name, | |
message=message, | |
**self.global_log_fields, | |
) | |
print(json.dumps(entry)) | |
def handle_http_request(request): | |
logger.remove() | |
logger.add(CloudLoggingHandler(request), format="{function}:{line} - {message}") | |
logger.debug("This is a DEBUG message") | |
logger.info("This is an INFO message") | |
logger.warning("This is a WARNING message") | |
logger.error("This is an ERROR message") | |
return "Completed", 200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment