Logging

Logging

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

Constructor

new Logging(optionsopt)

Parameters:
Name Type Attributes Description
options ClientConfig <optional>

Configuration options.

See:
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();
}

Methods

(async) createSink(name, config, callbackopt) → {Promise.<CreateSinkResponse>}

Create a sink.

Parameters:
Name Type Attributes Description
name string

Name of the sink.

config CreateSinkRequest

Config to set for the sink.

callback CreateSinkCallback <optional>

Callback function.

Returns:
Type Description
Promise.<CreateSinkResponse>
See:
Throws:
  • If a name is not provided.

    Type
    Error
  • if a config object is not provided.

    Type
    Error
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({
  projectId: 'grape-spaceship-123'
});
const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

const config = {
  destination: storage.bucket('logging-bucket'),
  filter: 'severity = ALERT'
};

function callback(err, sink, apiResponse) {
  // `sink` is a Sink object.
}

logging.createSink('new-sink-name', config, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
logging.createSink('new-sink-name', config).then(data => {
  const sink = data[0];
  const apiResponse = data[1];
});

Another example:

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

  // Creates clients
  const logging = new Logging();
  const storage = new Storage();

  /**
   * TODO(developer): Uncomment the following lines to run the code.
   */
  // const sinkName = 'Name of your sink, e.g. my-sink';
  // const bucketName = 'Desination bucket, e.g. my-bucket';
  // const filter = 'Optional log filer, e.g. severity=ERROR';

  // The destination can be a Cloud Storage bucket, a Cloud Pub/Sub topic,
  // or a BigQuery dataset. In this case, it is a Cloud Storage Bucket.
  // See https://cloud.google.com/logging/docs/api/tasks/exporting-logs for
  // information on the destination format.
  const destination = storage.bucket(bucketName);
  const sink = logging.sink(sinkName);

  /**
   * The filter determines which logs this sink matches and will be exported
   * to the destination. For example a filter of 'severity>=INFO' will send
   * all logs that have a severity of INFO or greater to the destination.
   * See https://cloud.google.com/logging/docs/view/advanced_filters for more
   * filter information.
   */
  const config = {
    destination: destination,
    filter: filter,
  };

  async function createSink() {
    // See https://googleapis.dev/nodejs/logging/latest/Sink.html#create
    await sink.create(config);
    console.log(`Created sink ${sinkName} to ${bucketName}`);
  }
  createSink();

entry(resourceopt, data) → {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 Log#write.

Note, Cloud Logging Quotas and limits dictates that the maximum log entry size, including all LogEntry Resource properties, cannot exceed approximately 256 KB.

Parameters:
Name Type Attributes Description
resource object | string <optional>

See a Monitored Resource.

data object | string

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

Returns:
Type Description
Entry
See:
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'
//   }
// }

(async) getEntries(queryopt, callbackopt) → {Promise.<GetEntriesResponse>}

List the entries in your logs.

Parameters:
Name Type Attributes Description
query GetEntriesRequest <optional>

Query object for listing entries.

callback GetEntriesCallback <optional>

Callback function.

Returns:
Type Description
Promise.<GetEntriesResponse>
See:
Examples
const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getEntries((err, entries) => {
  // `entries` is an array of Stackdriver 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();

getEntriesStream(queryopt) → {ReadableStream}

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

Parameters:
Name Type Attributes Description
query GetEntriesRequest <optional>

Query object for listing entries.

Returns:
Type Description
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 Stackdriver 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();
  });

(async) getLogs(queryopt, callbackopt) → {Promise.<GetLogsResponse>}

List the entries in your logs.

Parameters:
Name Type Attributes Description
query GetLogsRequest <optional>

Query object for listing entries.

callback GetLogsCallback <optional>

Callback function.

Returns:
Type Description
Promise.<GetLogsResponse>
See:
Examples
const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

logging.getLogs((err, logs) => {
  // `logs` is an array of Stackdriver 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();

getLogsStream(queryopt) → {ReadableStream}

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

Parameters:
Name Type Attributes Description
query GetLogsRequest <optional>

Query object for listing entries.

Returns:
Type Description
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 Stackdriver 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();
  });

(async) getSinks(queryopt, callbackopt) → {Promise.<GetSinksResponse>}

Get the sinks associated with this project.

Parameters:
Name Type Attributes Description
query GetSinksRequest <optional>

Query object for listing sinks.

callback GetSinksCallback <optional>

Callback function.

Returns:
Type Description
Promise.<GetSinksResponse>
See:
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();

getSinksStream(queryopt) → {ReadableStream}

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

Parameters:
Name Type Attributes Description
query GetSinksRequest <optional>

Query object for listing sinks.

Returns:
Type Description
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, optionsopt) → {Log}

Get a reference to a Stackdriver Logging log.

Parameters:
Name Type Attributes Description
name string

Name of the existing log.

options object <optional>

Configuration object.

Properties
Name Type Attributes Description
removeCircular boolean <optional>

Replace circular references in logged objects with a string value, [Circular]. (Default: false)

Returns:
Type Description
Log
See:
Example
const {Logging} = require('@google-cloud/logging');
const logging = new Logging();
const log = logging.log('my-log');

request(config, callbackopt)

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

Parameters:
Name Type Attributes Description
config object

Configuration object.

Properties
Name Type Description
gaxOpts object

GAX options.

method function

The gax method to call.

reqOpts object

Request options.

callback function <optional>

Callback function.

sink(name) → {Sink}

Get a reference to a Stackdriver Logging sink.

Parameters:
Name Type Description
name string

Name of the existing sink.

Returns:
Type Description
Sink
See:
Example
const {Logging} = require('@google-cloud/logging');
const logging = new Logging();
const sink = logging.sink('my-sink');