Constructor

Logging

new Logging(options)

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).

Parameter

options

Optional

ClientConfig

Configuration options.

See also

What is Stackdriver Logging?

Introduction to the Stackdriver Logging API

Logging to Stackdriver from Bunyan

Logging to Stackdriver from Winston

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 explicit credentials:

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');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Creates a client
const logging = new Logging({
  projectId: projectId,
});

// The name of the log to write to
const logName = 'my-log';
// 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'}};
// Prepares a log entry
const entry = log.entry(metadata, text);

// Writes the log entry
log
  .write(entry)
  .then(() => {
    console.log(`Logged: ${text}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Properties

Entry

static

Constructor

Entry class.

See also
Entry

Log

static

Constructor

Log class.

See also
Log

Logging

static

Constructor

Logging class.

See also
Logging

Sink

static

Constructor

Sink class.

See also
Sink

Methods

createSink

createSink(name, config, callback) returns Promise containing CreateSinkResponse

Create a sink.

Parameter

name

string

Name of the sink.

config

CreateSinkRequest

Config to set for the sink.

callback

Optional

CreateSinkCallback

Callback function.

See also

Sink Overview

Advanced Logs Filters

projects.sinks.create API Documentation

Sink#create
Throws

Error 

If a name is not provided.

Error 

if a config object is not provided.

Returns

Promise containing CreateSinkResponse 

Example

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

var 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(function(data) {
  var sink = data[0];
  var 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,
};

// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging/sink?method=create
sink
  .create(config)
  .then(() => {
    console.log(`Created sink ${sinkName} to ${bucketName}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

entry

entry(resource, data) returns Entry

Create an entry object.

Note that using this method will not itself make any API requests. You will use the object returned in other API calls, such as Log#write.

Parameter

resource

Optional

(nullable object or nullable string)

See a Monitored Resource.

data

(object or string)

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

See also

LogEntry JSON representation

Returns

Entry 

Example

var Logging = require('@google-cloud/logging');
var logging = new Logging();

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

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

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

getEntries

getEntries(query, callback) returns Promise containing GetEntriesResponse

List the entries in your logs.

Parameter

query

Optional

GetEntriesRequest

Query object for listing entries.

callback

Optional

GetEntriesCallback

Callback function.

See also

entries.list API Documentation

Returns

Promise containing GetEntriesResponse 

Example

var Logging = require('@google-cloud/logging');
var logging = new Logging();

logging.getEntries(function(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(function(data) {
  var 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);

// List the most recent entries for a given log
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging?method=getEntries
log
  .getEntries()
  .then(results => {
    const entries = results[0];

    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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';

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

  // See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging?method=getEntries
  logging
    .getEntries(options)
    .then(results => {
      const entries = results[0];

      console.log('Logs:');
      entries.forEach(entry => {
        const metadata = entry.metadata;
        console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
      });
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
}

function deleteLog(logName) {
  // 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 to delete, e.g. my-log';

  const log = logging.log(logName);

  // Deletes a logger and all its entries.
  // Note that a deletion can take several minutes to take effect.
  // See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging/log?method=delete
  log
    .delete()
    .then(() => {
      console.log(`Deleted log: ${logName}`);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
}

require(`yargs`)
  .demand(1)
  .command(
    'list',
    'Lists log entries, optionally filtering, limiting, and sorting results.',
    {
      filter: {
        alias: 'f',
        type: 'string',
        requiresArg: true,
        description: 'Only log entries matching the filter are written.',
      },
      limit: {
        alias: 'l',
        type: 'number',
        requiresArg: true,
        description: 'Maximum number of results to return.',
      },
      sort: {
        alias: 's',
        type: 'string',
        requiresArg: true,
        description: 'Sort results.',
      },
    },
    opts => {
      listLogEntriesAdvanced(opts.filter, opts.limit, opts.sort);
    }
  )
  .command('list-simple <logName>', 'Lists log entries.', {}, opts =>
    listLogEntries(opts.logName)
  )
  .command(
    'write <logName> <resource> <entry>',
    'Writes a log entry to the specified log.',
    {},
    opts => {
      try {
        opts.resource = JSON.parse(opts.resource);
      } catch (err) {
        console.error('"resource" must be a valid JSON string!');
        return;
      }

      try {
        opts.entry = JSON.parse(opts.entry);
      } catch (err) {
        console.error('"entry" must be a valid JSON string!');
        return;
      }

      writeLogEntryAdvanced(opts.logName, opts);
    }
  )
  .command(
    'write-simple <logName>',
    'Writes a basic log entry to the specified log.',
    {},
    opts => {
      writeLogEntry(opts.logName);
    }
  )
  .command('delete <logName>', 'Deletes the specified Log.', {}, opts => {
    deleteLog(opts.logName);
  })
  .example('node $0 list', 'List all log entries.')
  .example(
    'node $0 list -f "severity=ERROR" -s "timestamp" -l 2',
    'List up to 2 error entries, sorted by timestamp ascending.'
  )
  .example(
    `node $0 list -f 'logName="my-log"' -l 2`,
    'List up to 2 log entries from the "my-log" log.'
  )
  .example(
    'node $0 write my-log \'{"type":"gae_app","labels":{"module_id":"default"}}\' \'"Hello World!"\'',
    'Write a string log entry.'
  )
  .example(
    'node $0 write my-log \'{"type":"global"}\' \'{"message":"Hello World!"}\'',
    'Write a JSON log entry.'
  )
  .example('node $0 delete my-log', 'Delete "my-log".')
  .wrap(120)
  .recommendCommands()
  .epilogue(`For more information, see https://cloud.google.com/logging/docs`)
  .help()
  .strict().argv;

getEntriesStream

getEntriesStream(query) returns ReadableStream

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

Parameter

query

Optional

GetEntriesRequest

Query object for listing entries.

Returns

ReadableStream 

A readable stream that emits Entry instances.

Example

var Logging = require('@google-cloud/logging');
var logging = new Logging();

logging.getEntriesStream()
  .on('error', console.error)
  .on('data', function(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();
  });

getSinks

getSinks(query, callback) returns Promise containing GetSinksResponse

Get the sinks associated with this project.

Parameter

query

Optional

GetSinksRequest

Query object for listing sinks.

callback

Optional

GetSinksCallback

Callback function.

See also

projects.sinks.list API Documentation

Returns

Promise containing GetSinksResponse 

Example

var Logging = require('@google-cloud/logging');
var logging = new Logging();

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

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

Another example:

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

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

// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging?method=getSinks
logging
  .getSinks()
  .then(results => {
    const sinks = results[0];

    console.log('Sinks:');
    sinks.forEach(sink => {
      console.log(sink.name);
      console.log(`  Destination: ${sink.metadata.destination}`);
      console.log(`  Filter: ${sink.metadata.filter}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

getSinksStream

getSinksStream(query) returns ReadableStream

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

Parameter

query

Optional

GetSinksRequest

Query object for listing sinks.

Returns

ReadableStream 

A readable stream that emits Sink instances.

Example

var Logging = require('@google-cloud/logging');
var logging = new Logging();

logging.getSinksStream()
  .on('error', console.error)
  .on('data', function(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

log(name, options) returns Log

Get a reference to a Stackdriver Logging log.

Parameter

name

string

Name of the existing log.

options

Optional

object

Configuration object.

See also

Log Overview

Returns

Log 

Example

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

request

request(config, callback)

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

Parameter

config

object

Configuration object.

callback

Optional

function()

Callback function.

sink

sink(name) returns Sink

Get a reference to a Stackdriver Logging sink.

Parameter

name

string

Name of the existing sink.

See also

Sink Overview

Returns

Sink 

Example

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