structured logging from a cloud function
So I've been banging my head against this for a while now, thought I'd ask here.
Is it possible to use structured logging from within a Cloud Function?
The log and metrics agents aren't available in CF and I'd like some richer data in our StackDriver logs (mainly to leverage for some log-based metrics).
Does anybody have some pointers as to what is possible without the extra machinery available using a log agent?
Solution 1:
I posted this community wiki answer to make the recommendation provided by @Andrew Haines more visible. This question was answered here. Please find solution summary below:
// global
const { Logging } = require("@google-cloud/logging");
const logging = new Logging();
const Log = logging.log("cloudfunctions.googleapis.com%2Fcloud-functions");
const LogMetadata = {
severity: "INFO",
type: "cloud_function",
labels: {
function_name: process.env.FUNCTION_TARGET,
project: process.env.GCP_PROJECT,
region: JSON.parse(process.env.FIREBASE_CONFIG).locationId
}
};
// per request
const data = { FOO: "BAR" };
const traceId = req.get("x-cloud-trace-context").split("/")[0];
const metadata = {
...LogMetadata,
severity: 'INFO',
trace: `projects/${process.env.GCLOUD_PROJECT}/traces/${traceId}`,
labels: {
execution_id: req.get("function-execution-id")
}
};
Log.write(Log.entry(metadata, data));
Values for severity
can be found here.
DEFAULT (0) The log entry has no assigned severity level.
DEBUG (100) Debug or trace information.
INFO (200) Routine information, such as ongoing status or performance.
NOTICE (300) Normal but significant events, such as start up, shut down, or a configuration change.
WARNING (400) Warning events might cause problems.
ERROR (500) Error events are likely to cause problems.
CRITICAL (600) Critical events cause more severe problems or outages.
ALERT (700) A person must take an action immediately.
EMERGENCY (800) One or more systems are unusable.