Cloud Logging: Node.js Client

release levelnpm version

Google Cloud Logging allows you to store, search, analyze,monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services.

If you require lightweight dependencies, an experimental, minified version ofthis library is available at@google-cloud/logging-min.Note:logging-min is experimental, and its feature surface is subject to change. To install@google-cloud/logging-min library run the following command:

npm install @google-cloud/logging-min

For an interactive tutorial on using the client library in a Node.js application, click Guide Me:

Guide Me

A comprehensive list of changes in each version may be found inthe CHANGELOG.

Read more about the client libraries for Cloud APIs, including the olderGoogle APIs Client Libraries, inClient Libraries Explained.

Table of contents:

Quickstart

Before you begin

  1. Select or create a Cloud Platform project.
  2. Enable the Cloud Logging API.
  3. Set up authentication with a service account so you can access theAPI from your local workstation.

Installing the client library

npm install @google-cloud/logging

Using the client library

// Imports the Google Cloud client libraryconst {Logging} = require('@google-cloud/logging');async function quickstart(  projectId = 'YOUR_PROJECT_ID', // Your Google Cloud Platform project ID  logName = 'my-log' // The name of the log to write to) {  // Creates a client  const logging = newLogging({projectId});  // Selects the log to write to  const log = logging.log(logName);  // The data to write to the log  const text = 'Hello, world!';  // The metadata associated with the entry  const metadata = {    resource: {type: 'global'},    // See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity    severity: 'INFO',  };  // Prepares a log entry  const entry = log.entry(metadata, text);  async function writeLog() {    // Writes the log entry    await log.write(entry);    console.log(`Logged: ${text}`);  }  writeLog();}

Batching Writes

High throughput applications should avoid awaiting calls to the logger:

await log.write(logEntry1);await log.write(logEntry2);

Rather, applications should use afire and forget approach:

log.write(logEntry1);log.write(logEntry2);

The@google-cloud/logging library will handle batching and dispatchingthese log lines to the API.

Writing to Stdout

TheLogSync class helps users easily write context-rich structured logs tostdout or any custom transport. It extracts additional log properties liketrace context from HTTP headers and can be used as an on/off toggle betweenwriting to the API or tostdout during local development.

Logs written tostdout are then picked up, out-of-process, by a Loggingagent in the respective GCP environment. Logging agents can add moreproperties to each entry before streaming it to the Logging API.

Read more aboutLogging agents.

Serverless applications like Cloud Functions, Cloud Run, and App Engineare highly recommended to use theLogSync class as async logs may be droppeddue to lack of CPU.

Read more aboutstructured logging.

// Optional: Create and configure a clientconst logging = new Logging();await logging.setProjectId()await logging.setDetectedResource()// Create a LogSync transport, defaulting to `process.stdout`const log = logging.logSync(logname);const meta = { // optional field overrides here };const entry = log.entry(meta, 'Your log message');log.write(entry);// Syntax sugar for logging at a specific severitylog.alert(entry);log.warning(entry);

Populating Http request metadata

Metadata about Http request is a part of thestructured log infothat can be captured within each log entry. It can provide a context for the application logs andis used to group multiple log entries under the load balancer request logs. See thesamplehow to populate the Http request metadata for log entries.

If you already have a "raw" Httprequest object you can assign it toentry.metadata.httpRequest directly. More information abouthow therequest is interpreted as raw can be found in thecode.

Automatic Trace/Span ID Extraction

Cloud Logging libraries usetrace fields within LogEntry to capture trace contexts, which enables thecorrelation of logs and traces, and distributed tracing troubleshooting. These tracing fields, includingtrace,spanId, andtraceSampled, define the trace context for aLogEntry.

If not provided explicitly in a LogEntry, the Cloud Logging library automatically populatestrace,span_id, andtrace_sampled fields from detected OpenTelemetry span contexts, or from HTTP request headers.

Extracting Trace/Span ID from OpenTelemetry Context

If you are using OpenTelemetry and there is an active span in the OpenTelemetry Context, thetrace,span_id, andtrace_sampled fields in the log entry are automatically populated from the active span. More information about OpenTelemetry can be foundhere.

Extracting Trace/Span ID from HTTP Headers

If tracing fields are not provided explicitly and no OpenTelemetry context is detected, thetrace /span_id fields are extracted automatically from HTTP headers. Trace information can be automatically populated from either theW3C Traceparent orX-Cloud-Trace-Context headers.

Error handling with logs written or deleted asynchronously

TheLog class provide users the ability to write and delete logs asynchronously. However, there are cases when log entriescannot be written or deleted and error is thrown - if error is not handled properly, it could crash the application.One possible way to catch the error is toawait the log write/delete calls and wrap it withtry/catch like in example below:

    // Write log entry and and catch any errors    try {      await log.write(entry);    } catch (err) {      console.log('Error is: ' + err);    }

However, awaiting for everylog.write orlog.delete calls may introduce delays which could be avoided by simply adding a callback like in the example below. This way the log entry can be queued for processing and codeexecution will continue without further delays. The callback will be called once the operation is complete:

    // Asynchronously write the log entry and handle respone or any errors in provided callback    log.write(entry, err => {      if (err) {        // The log entry was not written.        console.log(err.message);      } else {        console.log('No error in write callback!');      }    });

Adding a callback to everylog.write orlog.delete calls could be a burden, especially if codehandling the error is always the same. For this purpose we introduced an ability to provide a default callbackforLog class which could be set throughLogOptions passed toLog constructor as in example below - thisway you can define a global callback once for alllog.write andlog.delete calls and be able to handle errors:

  const {Logging} = require('@google-cloud/logging');  const logging = newLogging();  // Create options with default callback to be called on every write/delete response or error  const options = {    defaultWriteDeleteCallback: function (err) {      if (err) {        console.log('Error is: ' + err);      } else {        console.log('No error, all is good!');      }    },  };  const log = logging.log('my-log', options);

See the full sample inwriteLogWithCallback functionhere.

Samples

Samples are in thesamples/ directory. Each sample'sREADME.md has instructions for running its sample.

SampleSource CodeTry it
Fluentsource codeOpen in Cloud Shell
Log HTTP Requestsource codeOpen in Cloud Shell
Logssource codeOpen in Cloud Shell
Quickstartsource codeOpen in Cloud Shell
Sinkssource codeOpen in Cloud Shell

TheCloud Logging Node.js Client API Reference documentationalso contains samples.

Supported Node.js Versions

Our client libraries follow theNode.js release schedule.Libraries are compatible with all currentactive andmaintenance versions ofNode.js.If you are using an end-of-life version of Node.js, we recommend that you updateas soon as possible to an actively supported LTS version.

Google's client libraries support legacy versions of Node.js runtimes on abest-efforts basis with the following warnings:

  • Legacy versions are not tested in continuous integration.
  • Some security patches and features cannot be backported.
  • Dependencies cannot be kept up-to-date.

Client libraries targeting some end-of-life versions of Node.js are available, andcan be installed through npmdist-tags.The dist-tags follow the naming conventionlegacy-(version).For example,npm install @google-cloud/logging@legacy-8 installs client librariesfor versions compatible with Node.js 8.

Versioning

This library followsSemantic Versioning.

This library is considered to bestable. The code surface will not change in backwards-incompatible waysunless absolutely necessary (e.g. because of critical security issues) or withan extensive deprecation period. Issues and requests againststable librariesare addressed with the highest priority.

More Information:Google Cloud Platform Launch Stages

Contributing

Contributions welcome! See theContributing Guide.

Please note that thisREADME.md, thesamples/README.md,and a variety of configuration files in this repository (including.nycrc andtsconfig.json)are generated from a central template. To edit one of these files, make an editto its templates indirectory.

License

Apache Version 2.0

SeeLICENSE

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-30 UTC.