Class Logging (11.0.0)

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

See What is Cloud Logging?

See Introduction to the Cloud Logging API

See Logging to Google Cloud from Bunyan

See Logging to Google Cloud from Winston

Package

@google-cloud/logging

Examples

Import the client library


const {Logging} = require('@google-cloud/logging');

Create a client that uses Application Default Credentials (ADC):


const logging = new Logging();

Create a client with explicitcredentials:


const logging = new Logging({ projectId:
 'your-project-id', keyFilename: '/path/to/keyfile.json'
});

Full quickstart example:


// Imports the Google Cloud client library
const {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 = new Logging({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();
}

Constructors

(constructor)(options, gaxInstance)

constructor(options?: LoggingOptions, gaxInstance?: typeof gax);

Constructs a new instance of the Logging class

Parameters
NameDescription
options LoggingOptions
gaxInstance typeof gax

Properties

api

api: {
        [key: string]: gax.ClientStub;
    };

auth

auth: gax.GoogleAuth;

configService

configService?: typeof v2.ConfigServiceV2Client;

detectedResource

detectedResource?: object;

loggingService

loggingService?: typeof v2.LoggingServiceV2Client;

options

options: LoggingOptions;

projectId

projectId: string;

Methods

createSink(name, config)

createSink(name: string, config: CreateSinkRequest): Promise<[Sink, LogSink]>;

CreateSinkCallback

Parameters
NameDescription
name string
config CreateSinkRequest
Returns
TypeDescription
Promise<[Sink, LogSink]>

createSink(name, config, callback)

createSink(name: string, config: CreateSinkRequest, callback: CreateSinkCallback): void;
Parameters
NameDescription
name string
config CreateSinkRequest
callback CreateSinkCallback
Returns
TypeDescription
void

entry(resource, data)

entry(resource?: LogEntry, data?: {} | string): Entry;

Create an entry object.

Using this method will not itself make any API requests. You will use the object returned in other API calls, such as .

Note, Cloud Logging Quotas and limits dictates that the maximum log entry size, including all [LogEntry Resource properties]https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry, cannot exceed _approximately_ 256 KB.

See LogEntry JSON representation

Parameters
NameDescription
resource LogEntry

See a [Monitored Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource).

data {} | string

The data to use as the value for this log entry.

Returns
TypeDescription
Entry

{Entry}

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

const resource = {
  type: 'gce_instance',
  labels: {
    zone: 'global',
    instance_id: '3'
  }
};

const entry = logging.entry(resource, {
  delegate: 'my_username'
});

entry.toJSON();
// {
//   resource: {
//     type: 'gce_instance',
//     labels: {
//       zone: 'global',
//       instance_id: '3'
//     }
//   },
//   jsonPayload: {
//     delegate: 'my_username'
//   }
// }

getEntries(options)

getEntries(options?: GetEntriesRequest): Promise<GetEntriesResponse>;

List the entries in your logs.

See entries.list API Documentation

Parameter
NameDescription
options GetEntriesRequest
Returns
TypeDescription
Promise<GetEntriesResponse>

{Promise

Examples

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getEntries((err, entries) => {
  // `entries` is an array of Cloud Logging entry objects.
  // See the `data` property to read the data from the entry.
});

//-
// To control how many API requests are made and page through the results
// manually, set `autoPaginate` to `false`.
//-
function callback(err, entries, nextQuery, apiResponse) {
  if (nextQuery) {
    // More results exist.
    logging.getEntries(nextQuery, callback);
  }
}

logging.getEntries({
  autoPaginate: false
}, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
logging.getEntries().then(data => {
  const entries = data[0];
});

Another example:


  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following line to run the code.
   */
  // const logName = 'Name of the log from which to list entries, e.g. my-log';

  const log = logging.log(logName);

  async function printEntryMetadata() {
    // List the most recent entries for a given log
    // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getEntries
    const [entries] = await log.getEntries();
    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  }
  printEntryMetadata();

Another example:


  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following lines to run the code.
   *
   * Filter results, e.g. "severity=ERROR"
   * See https://cloud.google.com/logging/docs/view/advanced_filters for more
   * filter information.
   */
  // const filter = 'severity=ERROR';
  // const pageSize = 5;
  // const orderBy = 'timestamp desc';

  const options = {
    filter: filter,
    pageSize: pageSize,
    orderBy: orderBy,
  };

  async function printEntryMetadata() {
    // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getEntries
    const [entries] = await logging.getEntries(options);
    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  }
  printEntryMetadata();

getEntries(callback)

getEntries(callback: GetEntriesCallback): void;
Parameter
NameDescription
callback GetEntriesCallback
Returns
TypeDescription
void

getEntries(options, callback)

getEntries(options: GetEntriesRequest, callback: GetEntriesCallback): void;
Parameters
NameDescription
options GetEntriesRequest
callback GetEntriesCallback
Returns
TypeDescription
void

getEntriesStream(options)

getEntriesStream(options?: GetEntriesRequest): Duplex;

List the Entry objects in your logs as a readable object stream.

Logging#getEntriesStream

Parameter
NameDescription
options GetEntriesRequest
Returns
TypeDescription
Duplex

{ReadableStream} A readable stream that emits Entry instances.

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getEntriesStream()
  .on('error', console.error)
  .on('data', entry => {
    // `entry` is a Cloud Logging entry object.
    // See the `data` property to read the data from the entry.
  })
  .on('end', function() {
    // All entries retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
logging.getEntriesStream()
  .on('data', function(entry) {
    this.end();
  });

getLogs(options)

getLogs(options?: GetLogsRequest): Promise<GetLogsResponse>;

List the entries in your logs.

See logs.list API Documentation

Parameter
NameDescription
options GetLogsRequest
Returns
TypeDescription
Promise<GetLogsResponse>

{Promise

Examples

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getLogs((err, logs) => {
  // `logs` is an array of Cloud Logging log objects.
});

//-
// To control how many API requests are made and page through the results
// manually, set `autoPaginate` to `false`.
//-
function callback(err, entries, nextQuery, apiResponse) {
  if (nextQuery) {
    // More results exist.
    logging.getLogs(nextQuery, callback);
  }
}

logging.getLogs({
  autoPaginate: false
}, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
logging.getLogs().then(data => {
  const entries = data[0];
});

Another example:


  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  async function printLogNames() {
    const [logs] = await logging.getLogs();
    console.log('Logs:');
    logs.forEach(log => {
      console.log(log.name);
    });
  }
  printLogNames();

getLogs(callback)

getLogs(callback: GetLogsCallback): void;
Parameter
NameDescription
callback GetLogsCallback
Returns
TypeDescription
void

getLogs(options, callback)

getLogs(options: GetLogsRequest, callback: GetLogsCallback): void;
Parameters
NameDescription
options GetLogsRequest
callback GetLogsCallback
Returns
TypeDescription
void

getLogsStream(options)

getLogsStream(options?: GetLogsRequest): Duplex;

List the Log objects in your project as a readable object stream.

Logging#getLogsStream

Parameter
NameDescription
options GetLogsRequest
Returns
TypeDescription
Duplex

{ReadableStream} A readable stream that emits Log instances.

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getLogsStream()
  .on('error', console.error)
  .on('data', log => {
    // `log` is a Cloud Logging log object.
  })
  .on('end', function() {
    // All logs retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
logging.getLogsStream()
  .on('data', log => {
    this.end();
  });

getSinks(options)

getSinks(options?: GetSinksRequest): Promise<GetSinksResponse>;

Get the sinks associated with this project.

See projects.sinks.list API Documentation

Parameter
NameDescription
options GetSinksRequest
Returns
TypeDescription
Promise<GetSinksResponse>

{Promise

Examples

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getSinks((err, sinks) => {
  // sinks is an array of Sink objects.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
logging.getSinks().then(data => {
  const sinks = data[0];
});

Another example:


  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  async function printSinkMetadata() {
    // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getSinks
    const [sinks] = await logging.getSinks();
    console.log('Sinks:');
    sinks.forEach(sink => {
      console.log(sink.name);
      console.log(`  Destination: ${sink.metadata.destination}`);
      console.log(`  Filter: ${sink.metadata.filter}`);
    });
  }
  printSinkMetadata();

getSinks(callback)

getSinks(callback: GetSinksCallback): void;
Parameter
NameDescription
callback GetSinksCallback
Returns
TypeDescription
void

getSinks(options, callback)

getSinks(options: GetSinksRequest, callback: GetSinksCallback): void;
Parameters
NameDescription
options GetSinksRequest
callback GetSinksCallback
Returns
TypeDescription
void

getSinksStream(options)

getSinksStream(options: GetSinksRequest): Duplex;

Get the Sink objects associated with this project as a readable object stream.

Logging#getSinksStream

Parameter
NameDescription
options GetSinksRequest
Returns
TypeDescription
Duplex

{ReadableStream} A readable stream that emits Sink instances.

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getSinksStream()
  .on('error', console.error)
  .on('data', sink => {
    // `sink` is a Sink object.
  })
  .on('end', function() {
    // All sinks retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
logging.getSinksStream()
  .on('data', function(sink) {
    this.end();
  });

log(name, options)

log(name: string, options?: LogOptions): Log;

Get a reference to a Cloud Logging log.

See Log Overview

Parameters
NameDescription
name string

Name of the existing log.

options LogOptions

Configuration object.

Returns
TypeDescription
Log

{Log}

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();
const log = logging.log('my-log');

logSync(name, transport, options)

logSync(name: string, transport?: Writable, options?: LogSyncOptions): LogSync;

Get a reference to a Cloud Logging logSync.

Parameters
NameDescription
name string

Name of the existing log.

transport Writable

An optional write stream.

options LogSyncOptions

An optional configuration object.

Returns
TypeDescription
LogSync

{LogSync}

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

// Optional: enrich logs with additional context
await logging.setProjectId();
await logging.setDetectedResource();

// Default transport writes to process.stdout
const log = logging.logSync('my-log');

request(config, callback)

request<TResponse = any>(config: RequestConfig, callback?: RequestCallback<TResponse>): Duplex;

Funnel all API requests through this method, to be sure we have a project ID.

Parameters
NameDescription
config RequestConfig

Configuration object.

callback RequestCallback<TResponse>

Callback function.

Returns
TypeDescription
Duplex
Type Parameter
NameDescription
TResponse

setAclForBucket_(config)

setAclForBucket_(config: CreateSinkRequest): Promise<void>;

This method is called when creating a sink with a Bucket destination. The bucket must first grant proper ACL access to the Cloud Logging account.

The parameters are the same as what accepts.

Parameter
NameDescription
config CreateSinkRequest
Returns
TypeDescription
Promise<void>

setAclForDataset_(config)

setAclForDataset_(config: CreateSinkRequest): Promise<void>;

This method is called when creating a sink with a Dataset destination. The dataset must first grant proper ACL access to the Cloud Logging account.

The parameters are the same as what accepts.

Parameter
NameDescription
config CreateSinkRequest
Returns
TypeDescription
Promise<void>

setAclForTopic_(config)

setAclForTopic_(config: CreateSinkRequest): Promise<void>;

This method is called when creating a sink with a Topic destination. The topic must first grant proper ACL access to the Cloud Logging account.

The parameters are the same as what accepts.

Parameter
NameDescription
config CreateSinkRequest
Returns
TypeDescription
Promise<void>

setDetectedResource()

setDetectedResource(): Promise<void>;

setResource detects and sets a detectedresource object on the Logging instance. It can be invoked once to ensure ensuing LogSync entries contain resource context.

Returns
TypeDescription
Promise<void>

setProjectId(reqOpts)

setProjectId(reqOpts?: {}): Promise<void>;

setProjectId detects and sets a projectId string on the Logging instance. It can be invoked once to ensure ensuing LogSync entries have a projectID.

Parameter
NameDescription
reqOpts {}
Returns
TypeDescription
Promise<void>

sink(name)

sink(name: string): Sink;

Get a reference to a Cloud Logging sink.

See Sink Overview

Parameter
NameDescription
name string

Name of the existing sink.

Returns
TypeDescription
Sink

{Sink}

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();
const sink = logging.sink('my-sink');

tailEntries(options)

tailEntries(options?: TailEntriesRequest): Duplex;

Streaming read of live logs as log entries are ingested. Until the stream is terminated, it will continue reading logs.

Logging#tailEntries

Parameter
NameDescription
options TailEntriesRequest
Returns
TypeDescription
Duplex

{DuplexStream} A duplex stream that emits TailEntriesResponses containing an array of Entry instances.

Example

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.tailEntries()
  .on('error', console.error)
  .on('data', resp => {
    console.log(resp.entries);
    console.log(resp.suppressionInfo);
  })
  .on('end', function() {
    // All entries retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
logging.getEntriesStream()
  .on('data', function(entry) {
    this.end();
  });