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 Introduction to the Cloud Logging API
Package
@google-cloud/loggingExamples
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 | |
---|---|
Name | Description |
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 | |
---|---|
Name | Description |
name |
string
|
config |
CreateSinkRequest
|
Returns | |
---|---|
Type | Description |
Promise<[Sink, LogSink]> |
createSink(name, config, callback)
createSink(name: string, config: CreateSinkRequest, callback: CreateSinkCallback): void;
Parameters | |
---|---|
Name | Description |
name |
string
|
config |
CreateSinkRequest
|
callback |
CreateSinkCallback
|
Returns | |
---|---|
Type | Description |
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.
Parameters | |
---|---|
Name | Description |
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 | |
---|---|
Type | Description |
Entry |
{Entry} |
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.
Parameter | |
---|---|
Name | Description |
options |
GetEntriesRequest
|
Returns | |
---|---|
Type | Description |
Promise<GetEntriesResponse> |
{Promise
|
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 | |
---|---|
Name | Description |
callback |
GetEntriesCallback
|
Returns | |
---|---|
Type | Description |
void |
getEntries(options, callback)
getEntries(options: GetEntriesRequest, callback: GetEntriesCallback): void;
Parameters | |
---|---|
Name | Description |
options |
GetEntriesRequest
|
callback |
GetEntriesCallback
|
Returns | |
---|---|
Type | Description |
void |
getEntriesStream(options)
getEntriesStream(options?: GetEntriesRequest): Duplex;
List the Entry objects in your logs as a readable object stream.
Logging#getEntriesStream
Parameter | |
---|---|
Name | Description |
options |
GetEntriesRequest
|
Returns | |
---|---|
Type | Description |
Duplex |
{ReadableStream} A readable stream that emits Entry instances. |
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.
Parameter | |
---|---|
Name | Description |
options |
GetLogsRequest
|
Returns | |
---|---|
Type | Description |
Promise<GetLogsResponse> |
{Promise
|
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 | |
---|---|
Name | Description |
callback |
GetLogsCallback
|
Returns | |
---|---|
Type | Description |
void |
getLogs(options, callback)
getLogs(options: GetLogsRequest, callback: GetLogsCallback): void;
Parameters | |
---|---|
Name | Description |
options |
GetLogsRequest
|
callback |
GetLogsCallback
|
Returns | |
---|---|
Type | Description |
void |
getLogsStream(options)
getLogsStream(options?: GetLogsRequest): Duplex;
List the Log objects in your project as a readable object stream.
Logging#getLogsStream
Parameter | |
---|---|
Name | Description |
options |
GetLogsRequest
|
Returns | |
---|---|
Type | Description |
Duplex |
{ReadableStream} A readable stream that emits Log instances. |
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.
Parameter | |
---|---|
Name | Description |
options |
GetSinksRequest
|
Returns | |
---|---|
Type | Description |
Promise<GetSinksResponse> |
{Promise
|
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 | |
---|---|
Name | Description |
callback |
GetSinksCallback
|
Returns | |
---|---|
Type | Description |
void |
getSinks(options, callback)
getSinks(options: GetSinksRequest, callback: GetSinksCallback): void;
Parameters | |
---|---|
Name | Description |
options |
GetSinksRequest
|
callback |
GetSinksCallback
|
Returns | |
---|---|
Type | Description |
void |
getSinksStream(options)
getSinksStream(options: GetSinksRequest): Duplex;
Get the Sink objects associated with this project as a readable object stream.
Logging#getSinksStream
Parameter | |
---|---|
Name | Description |
options |
GetSinksRequest
|
Returns | |
---|---|
Type | Description |
Duplex |
{ReadableStream} A readable stream that emits Sink instances. |
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 | |
---|---|
Name | Description |
name |
string
Name of the existing log. |
options |
LogOptions
Configuration object. |
Returns | |
---|---|
Type | Description |
Log |
{Log} |
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 | |
---|---|
Name | Description |
name |
string
Name of the existing log. |
transport |
Writable
An optional write stream. |
options |
LogSyncOptions
An optional configuration object. |
Returns | |
---|---|
Type | Description |
LogSync |
{LogSync} |
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 | |
---|---|
Name | Description |
config |
RequestConfig
Configuration object. |
callback |
RequestCallback<TResponse>
Callback function. |
Returns | |
---|---|
Type | Description |
Duplex |
Type Parameter | |
---|---|
Name | Description |
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 | |
---|---|
Name | Description |
config |
CreateSinkRequest
|
Returns | |
---|---|
Type | Description |
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 | |
---|---|
Name | Description |
config |
CreateSinkRequest
|
Returns | |
---|---|
Type | Description |
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 | |
---|---|
Name | Description |
config |
CreateSinkRequest
|
Returns | |
---|---|
Type | Description |
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 | |
---|---|
Type | Description |
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 | |
---|---|
Name | Description |
reqOpts |
{}
|
Returns | |
---|---|
Type | Description |
Promise<void> |
sink(name)
sink(name: string): Sink;
Get a reference to a Cloud Logging sink.
See Sink Overview
Parameter | |
---|---|
Name | Description |
name |
string
Name of the existing sink. |
Returns | |
---|---|
Type | Description |
Sink |
{Sink} |
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 | |
---|---|
Name | Description |
options |
TailEntriesRequest
|
Returns | |
---|---|
Type | Description |
Duplex |
{DuplexStream} A duplex stream that emits TailEntriesResponses containing an array of Entry instances. |
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();
});