2

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?

Rasputnik
  • 196
  • 4
  • 1
    https://stackoverflow.com/questions/49185824/log-jsonpayload-in-firebase-cloud-functions – Andrew Haines Mar 13 '19 at 14:57
  • Got this also solved in Python at [jsonPayload (structured logging) output from Python Google Cloud Function's logging needed to create Label-Based Metrics (LBM) in GCP](https://serverfault.com/questions/1093143/jsonpayload-structured-logging-output-from-python-google-cloud-functions-logg). – questionto42standswithUkraine Feb 09 '22 at 14:40

1 Answers1

2

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.
Sergiusz
  • 310
  • 2
  • 13