@google-cloud/logging
- Version 12.0.1
- Published
- 330 kB
- 17 dependencies
- Apache-2.0 license
Install
npm i @google-cloud/loggingyarn add @google-cloud/loggingpnpm add @google-cloud/loggingOverview
Cloud Logging Client Library for Node.js
Index
Variables
variable v2
const v2: any;Functions
function assignSeverityToEntries
assignSeverityToEntries: (entries: Entry | Entry[], severity: string) => Entry[];Return an array of log entries with the desired severity assigned.
Parameter entries
Log entries.
Parameter severity
The desired severity level.
function detectServiceContext
detectServiceContext: (auth: GoogleAuth) => Promise<ServiceContext | null>;For logged errors, users can provide a service context. This enables errors to be picked up Cloud Error Reporting. For more information see [this guide]https://cloud.google.com/error-reporting/docs/formatting-error-messages and the [official documentation]https://cloud.google.com/error-reporting/reference/rest/v1beta1/ServiceContext.
function formatLogName
formatLogName: (projectId: string, name: string) => string;Format the name of a log. A log's full name is in the format of 'projects/{projectId}/logs/{logName}'.
Parameter projectId
Parameter name
Classes
class Entry
class Entry {}Create an entry object to define new data to insert into a meta.
Note, Cloud Logging Quotas and limits dictates that the maximum log entry size, including all LogEntry Resource properties, cannot exceed approximately 256 KB.
Parameter metadata
See a [LogEntry Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry).
Parameter data
The data to use as the value for this log entry.
If providing an object, these value types are supported: -
String-Number-Boolean-Buffer-Object-ArrayAny other types are stringified with
String(value).Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const syslog = logging.log('syslog');const metadata = {resource: {type: 'gce_instance',labels: {zone: 'global',instance_id: '3'}}};const entry = syslog.entry(metadata, {delegate: 'my_username'});syslog.alert(entry, (err, apiResponse) => {if (!err) {// Log entry inserted successfully.}});//-// You will also receive `Entry` objects when using// Logging#getEntries() and Log#getEntries().//-logging.getEntries((err, entries) => {if (!err) {// entries[0].data = The data value from the log entry.}});
constructor
constructor(metadata?: LogEntry, data?: any);property data
data: any;property metadata
metadata: LogEntry;method fromApiResponse_
static fromApiResponse_: (entry: google.logging.v2.LogEntry) => Entry;Create an Entry object from an API response, such as
entries:list.Parameter entry
An API representation of an entry. See a LogEntry.
Returns
{Entry}
method toJSON
toJSON: (options?: ToJsonOptions, projectId?: string) => EntryJson;Serialize an entry to the format the API expects. Read more: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
Parameter options
Configuration object.
Parameter
{boolean} [options.removeCircular] Replace circular references in an object with a string value,
[Circular].Parameter projectId
GCP Project ID.
method toStructuredJSON
toStructuredJSON: ( projectId?: string, useMessageField?: boolean) => StructuredJson;Serialize an entry to a standard format for any transports, e.g. agents. Read more: https://cloud.google.com/logging/docs/structured-logging
class Log
class Log implements LogSeverityFunctions {}A log is a named collection of entries, each entry representing a timestamped event. Logs can be produced by Google Cloud Platform services, by third-party services, or by your applications. For example, the log
apache-accessis produced by the Apache Web Server, but the logcompute.googleapis.com/activity_logis produced by Google Compute Engine.Parameter logging
Logging instance.
Parameter name
Name of the log.
Parameter options
Configuration object.
Parameter
{boolean} [options.removeCircular] Replace circular references in logged objects with a string value,
[Circular]. (Default: false)Parameter
{number} [options.maxEntrySize] A max entry size
Parameter
{string[]} [options.jsonFieldsToTruncate] A list of JSON properties at the given full path to be truncated. Received values will be prepended to predefined list in the order received and duplicates discarded.
Parameter
{ApiResponseCallback} [options.defaultWriteDeleteCallback] A default global callback to be used for Log#write and Log#delete APIs when ApiResponseCallback callback was not supplied by caller in function parameters. Note that LogOptions#defaultWriteDeleteCallback is useful when Log#write and Log#delete APIs are called without
awaitand without callback added explicitly to every call - this way LogOptions#defaultWriteDeleteCallback can serve as global callback handler, which for example could be used to catch all errors and eliminate crashes.Parameter
{boolean} [options.partialSuccess] Global flag indicating Whether a batch's valid entries should be written even if some other entry failed due to errors. Default is true. See partialSuccess for more info.
Example 1
import {Logging} from '@google-cloud/logging';import {LogOptions} from '@google-cloud/logging/build/src/log';const options: LogOptions = {maxEntrySize: 256,jsonFieldsToTruncate: ['jsonPayload.fields.metadata.structValue.fields.custom.stringValue',],defaultWriteDeleteCallback: (err: any) => {if (err) {console.log('Error: ' + err);}},};const logging = new Logging();const log = logging.log('syslog', options);
constructor
constructor(logging: Logging, name: string, options?: LogOptions);property defaultWriteDeleteCallback
defaultWriteDeleteCallback?: ApiResponseCallback;property formattedName_
formattedName_: string;property jsonFieldsToTruncate
jsonFieldsToTruncate: string[];property logging
logging: Logging;property maxEntrySize
maxEntrySize?: number;property name
name: string;property partialSuccess
partialSuccess: boolean;property removeCircular_
removeCircular_: boolean;method alert
alert: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "ALERT".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.alert(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.alert(entry).then(data => {const apiResponse = data[0];});
method assignSeverityToEntries_
static assignSeverityToEntries_: ( entries: Entry | Entry[], severity: string) => Entry[];Return an array of log entries with the desired severity assigned.
Parameter entries
Log entries.
Parameter severity
The desired severity level.
method critical
critical: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "CRITICAL".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.critical(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.critical(entry).then(data => {const apiResponse = data[0];});
method debug
debug: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "DEBUG".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.debug(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.debug(entry).then(data => {const apiResponse = data[0];});
method delete
delete: { (gaxOptions?: CallOptions): Promise<ApiResponse>; (gaxOptions: CallOptions, callback: ApiResponseCallback): void; (callback: ApiResponseCallback): void;};Delete the log.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');log.delete((err, apiResponse) => {if (!err) {// The log was deleted.}});//-// If the callback is omitted, we'll return a Promise.//-log.delete().then(data => {const apiResponse = data[0];});Example 2
include:samples/logs.js region_tag:logging_delete_log Another example:
method emergency
emergency: { ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "EMERGENCY".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.emergency(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.emergency(entry).then(data => {const apiResponse = data[0];});
method entry
entry: { (metadata?: LogEntry): Entry; (data?: string | {}): Entry; (metadata?: LogEntry, data?: string | {}): Entry;};Create an entry object for this log.
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]https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry, cannot exceed _approximately_ 256 KB.
Parameter metadata
See a [LogEntry Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry).
Parameter data
The data to use as the value for this log entry.
Returns
{Entry}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const metadata = {resource: {type: 'gce_instance',labels: {zone: 'global',instance_id: '3'}}};const entry = log.entry(metadata, {delegate: 'my_username'});entry.toJSON();// {// logName: 'projects/grape-spaceship-123/logs/syslog',// resource: {// type: 'gce_instance',// labels: {// zone: 'global',// instance_id: '3'// }// },// jsonPayload: {// delegate: 'my_username'// }// }
method error
error: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "ERROR".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.error(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.error(entry).then(data => {const apiResponse = data[0];});
method formatName_
static formatName_: (projectId: string, name: string) => string;Format the name of a log. A log's full name is in the format of 'projects/{projectId}/logs/{logName}'.
Returns
{string}
method getEntries
getEntries: { (options?: GetEntriesRequest): Promise<GetEntriesResponse>; (callback: GetEntriesCallback): void; (options: GetEntriesRequest, callback: GetEntriesCallback): void;};This method is a wrapper around {module:logging#getEntries}, but with a filter specified to only return entries from this log.
Parameter query
Query object for listing entries.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');log.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.log.getEntries(nextQuery, callback);}}log.getEntries({autoPaginate: false}, callback);//-// If the callback is omitted, we'll return a Promise.//-log.getEntries().then(data => {const entries = data[0];});
method getEntriesStream
getEntriesStream: (options: GetEntriesRequest) => any;This method is a wrapper around {module:logging#getEntriesStream}, but with a filter specified to only return {module:logging/entry} objects from this log.
Log#getEntriesStream
Parameter query
Query object for listing entries.
Returns
{ReadableStream} A readable stream that emits Entry instances.
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');log.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.//-log.getEntriesStream().on('data', function(entry) {this.end();});
method info
info: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "INFO".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.info(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.info(entry).then(data => {const apiResponse = data[0];});
method notice
notice: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "NOTICE".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.notice(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.notice(entry).then(data => {const apiResponse = data[0];});
method tailEntries
tailEntries: (options?: TailEntriesRequest) => any;This method is a wrapper around {module:logging#tailEntries}, but with a filter specified to only return {module:logging/entry} objects from this log.
Log#tailEntries
Parameter query
Query object for tailing entries.
Returns
{DuplexStream} A duplex stream that emits TailEntriesResponses containing an array of Entry instances.
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');log.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.//-log.tailEntries().on('data', function(entry) {this.end();});
method warning
warning: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write a log entry with a severity of "WARNING".
This is a simple wrapper around Log.write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.warning(entry, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.warning(entry).then(data => {const apiResponse = data[0];});
method write
write: { (entry: Entry | Entry[], options?: WriteOptions): Promise<ApiResponse>; ( entry: Entry | Entry[], options: WriteOptions, callback: ApiResponseCallback ): void; (entry: Entry | Entry[], callback: ApiResponseCallback): void;};Write log entries to Cloud Logging.
Note, Cloud Logging Quotas and limits dictates that the maximum cumulative size of all entries per write, including all [LogEntry Resource properties]https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry, cannot exceed _approximately_ 10 MB.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const entry = log.entry('gce_instance', {instance: 'my_instance'});log.write(entry, (err, apiResponse) => {if (!err) {// The log entry was written.}});//-// You may also pass multiple log entries to write.//-const secondEntry = log.entry('compute.googleapis.com', {user: 'my_username'});log.write([entry,secondEntry], (err, apiResponse) => {if (!err) {// The log entries were written.}});//-// To save some steps, you can also pass in plain values as your entries.// Note, however, that you must provide a configuration object to specify// the resource.//-const entries = [{user: 'my_username'},{home: process.env.HOME}];const options = {resource: 'compute.googleapis.com'};log.write(entries, options, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-log.write(entries).then(data => {const apiResponse = data[0];});Example 2
include:samples/logs.js region_tag:logging_write_log_entry Another example:
Example 3
include:samples/logs.js region_tag:logging_write_log_entry_advanced Another example:
class Logging
class Logging {}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
Parameter options
Configuration options.
Example 1
Import the client library
const {Logging} = require('@google-cloud/logging');Example 2
Create a client that uses Application Default Credentials (ADC):
const logging = new Logging();Example 3
Create a client with explicitcredentials:
const logging = new Logging({ projectId:'your-project-id', keyFilename: '/path/to/keyfile.json'});Example 4
include:samples/quickstart.js region_tag:logging_quickstart Full quickstart example:
constructor
constructor(options?: LoggingOptions, gaxInstance?: any);property api
api: { [key: string]: gax.ClientStub };property auth
auth: gax.GoogleAuth;property configService
configService?: any;property detectedResource
detectedResource?: {};property loggingService
loggingService?: any;property options
options: LoggingOptions;property projectId
projectId: string;method createSink
createSink: { (name: string, config: CreateSinkRequest): Promise<[Sink, LogSink]>; ( name: string, config: CreateSinkRequest, callback: CreateSinkCallback ): void;};CreateSinkCallback
Parameter err
Request error, if any.
Parameter sink
The new Sink.
Parameter apiResponse
The full API response.
method entry
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 Log#write.
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.
Parameter resource
See a [Monitored Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource).
Parameter data
The data to use as the value for this log entry.
Returns
{Entry}
Example 1
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'// }// }
method getEntries
getEntries: { (options?: GetEntriesRequest): Promise<GetEntriesResponse>; (callback: GetEntriesCallback): void; (options: GetEntriesRequest, callback: GetEntriesCallback): void;};List the entries in your logs.
Parameter query
Query object for listing entries.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
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];});Example 2
include:samples/logs.js region_tag:logging_list_log_entries Another example:
Example 3
include:samples/logs.js region_tag:logging_list_log_entries_advanced Another example:
method getEntriesStream
getEntriesStream: (options?: GetEntriesRequest) => Duplex;List the Entry objects in your logs as a readable object stream.
Logging#getEntriesStream
Parameter query
Query object for listing entries.
Returns
{ReadableStream} A readable stream that emits Entry instances.
Example 1
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();});
method getLogs
getLogs: { (options?: GetLogsRequest): Promise<GetLogsResponse>; (callback: GetLogsCallback): void; (options: GetLogsRequest, callback: GetLogsCallback): void;};List the entries in your logs.
Parameter query
Query object for listing entries.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
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];});Example 2
include:samples/logs.js region_tag:logging_list_logs Another example:
method getLogsStream
getLogsStream: (options?: GetLogsRequest) => Duplex;List the Log objects in your project as a readable object stream.
Logging#getLogsStream
Parameter query
Query object for listing entries.
Returns
{ReadableStream} A readable stream that emits Log instances.
Example 1
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();});
method getSinks
getSinks: { (options?: GetSinksRequest): Promise<GetSinksResponse>; (callback: GetSinksCallback): void; (options: GetSinksRequest, callback: GetSinksCallback): void;};Get the sinks associated with this project.
Parameter query
Query object for listing sinks.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
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];});Example 2
include:samples/sinks.js region_tag:logging_list_sinks Another example:
method getSinksStream
getSinksStream: (options: GetSinksRequest) => Duplex;Get the Sink objects associated with this project as a readable object stream.
Logging#getSinksStream
Parameter query
Query object for listing sinks.
Returns
{ReadableStream} A readable stream that emits Sink instances.
Example 1
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();});
method log
log: (name: string, options?: LogOptions) => Log;Get a reference to a Cloud Logging log.
See Log Overview
Parameter name
Name of the existing log.
Parameter options
Configuration object.
Parameter
{boolean} [options.removeCircular] Replace circular references in logged objects with a string value,
[Circular]. (Default: false)Returns
{Log}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.log('my-log');
method logSync
logSync: ( name: string, transport?: Writable, options?: LogSyncOptions) => LogSync;Get a reference to a Cloud Logging logSync.
Parameter name
Name of the existing log.
Parameter transport
An optional write stream.
Parameter options
An optional configuration object.
Returns
{LogSync}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();// Optional: enrich logs with additional contextawait logging.setProjectId();await logging.setDetectedResource();// Default transport writes to process.stdoutconst log = logging.logSync('my-log');
method request
request: <TResponse = any>( config: RequestConfig, callback?: RequestCallback<TResponse>) => Duplex;Funnel all API requests through this method, to be sure we have a project ID.
Parameter config
Configuration object.
Parameter
{object} config.gaxOpts GAX options.
Parameter
{function} config.method The gax method to call.
Parameter
{object} config.reqOpts Request options.
Parameter callback
Callback function.
method setAclForBucket_
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 Logging#createSink accepts.
method setAclForDataset_
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 Logging#createSink accepts.
method setAclForTopic_
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 Logging#createSink accepts.
method 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.
method setProjectId
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 reqOpts
method sink
sink: (name: string) => Sink;Get a reference to a Cloud Logging sink.
See Sink Overview
Parameter name
Name of the existing sink.
Returns
{Sink}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const sink = logging.sink('my-sink');
method tailEntries
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 query
Query object for tailing entries.
Returns
{DuplexStream} A duplex stream that emits TailEntriesResponses containing an array of Entry instances.
Example 1
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();});
class LogSync
class LogSync implements LogSeverityFunctions {}A logSync is a named collection of entries in structured log format. In Cloud Logging, structured logs refer to log entries that use the jsonPayload field to add structure to their payloads. In most GCP environments, like GKE and Cloud Functions, structured logs written to process.stdout are automatically picked up and formatted by logging agents.
Recommended for Serverless environment logging, especially where async log calls made by the
Logclass can be dropped by the CPU.Parameter logging
Logging instance.
Parameter name
Name of the logSync.
Parameter transport
transport A custom writable transport stream. Default: process.stdout.
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('mylog');
constructor
constructor( logging: Logging, name: string, transport?: Writable, options?: LogSyncOptions);property formattedName_
formattedName_: string;property logging
logging: Logging;property name
name: string;property transport
transport: Writable;property useMessageField_
useMessageField_: boolean;method alert
alert: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "ALERT".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.alert(entry);
method critical
critical: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "CRITICAL".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.critical(entry);
method debug
debug: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "DEBUG".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.debug(entry);
method emergency
emergency: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "EMERGENCY".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.emergency(entry);
method entry
entry: { (metadata?: LogEntry): Entry; (data?: string | {}): Entry; (metadata?: LogEntry, data?: string | {}): Entry;};Create an entry object for this log.
Using this method will not itself do any logging.
Parameter metadata
See a [LogEntry Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry).
Parameter data
The data to use as the value for this log entry.
Returns
{Entry}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const metadata = {resource: {type: 'gce_instance',labels: {zone: 'global',instance_id: '3'}}};const entry = log.entry(metadata, {delegate: 'my_username'});
method error
error: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "ERROR".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.error(entry);
method info
info: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "INFO".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.info(entry);
method notice
notice: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "NOTICE".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.notice(entry);
method warning
warning: (entry: Entry | Entry[], options?: WriteOptions) => void;Write a log entry with a severity of "WARNING".
This is a simple wrapper around LogSync#write. All arguments are the same as documented there.
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const log = logging.logSync('my-log');const entry = log.entry('gce_instance', {instance: 'my_instance'});log.warning(entry);
method write
write: (entry: Entry | Entry[], opts?: WriteOptions) => void;Write log entries to a custom transport (default: process.stdout).
Parameter entry
A log entry, or array of entries, to write.
Parameter options
Write options
Example 1
const entry = log.entry('gce_instance', {instance: 'my_instance'});log.write(entry);//-// You may also pass multiple log entries to write.//-const secondEntry = log.entry('compute.googleapis.com', {user: 'my_username'});log.write([entry, secondEntry]);//-// To save some steps, you can also pass in plain values as your entries.// Note, however, that you must provide a configuration object to specify// the resource.//-const entries = [{user: 'my_username'},{home: process.env.HOME}];const options = {resource: 'compute.googleapis.com'};log.write(entries, options);log.write(entries);});
class Sink
class Sink {}A sink is an object that lets you to specify a set of log entries to export to a particular destination. Cloud Logging lets you export log entries to destinations including Cloud Storage buckets (for long term log storage), Google BigQuery datasets (for log analysis), Google Pub/Sub (for streaming to other applications).
Parameter logging
Logging instance.
Parameter name
Name of the sink.
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const sink = logging.sink('my-sink');
constructor
constructor(logging: Logging, name: string);property formattedName_
formattedName_: string;property logging
logging: Logging;property metadata
metadata?: google.logging.v2.ILogSink;property name
name: string;method create
create: { (config: CreateSinkRequest): Promise<[Sink, LogSink]>; (config: CreateSinkRequest, callback: CreateSinkCallback): void;};Create a sink.
Parameter config
Config to set for the sink.
Parameter callback
Callback function.
Returns
{Promise}
Throws
{Error} if a config object is not provided.
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const sink = logging.sink('my-sink');const config = {destination: {// ...}};sink.create(config, (err, sink, apiResponse) => {if (!err) {// The sink was created successfully.}});//-// If the callback is omitted, we'll return a Promise.//-sink.create(config).then(data => {const sink = data[0];const apiResponse = data[1];});Example 2
include:samples/sinks.js region_tag:logging_create_sink Another example:
See Also
Logging#createSink
method delete
delete: { (gaxOptions?: CallOptions): Promise<DeleteResponse>; (callback: DeleteCallback): void; (gaxOptions: CallOptions, callback: DeleteCallback): void;};Delete the sink.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const sink = logging.sink('my-sink');sink.delete((err, apiResponse) => {if (!err) {// The log was deleted.}});//-// If the callback is omitted, we'll return a Promise.//-sink.delete().then(data => {const apiResponse = data[0];});Example 2
include:samples/sinks.js region_tag:logging_delete_sink Another example:
method getMetadata
getMetadata: { (gaxOptions?: CallOptions): Promise<SinkMetadataResponse>; (callback: SinkMetadataCallback): void; (gaxOptions: CallOptions, callback: SinkMetadataCallback): void;};Get the sink's metadata.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const sink = logging.sink('my-sink');sink.getMetadata((err, metadata, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-sink.getMetadata().then(data => {const metadata = data[0];});Example 2
include:samples/sinks.js region_tag:logging_get_sink Another example:
method setFilter
setFilter: { (filter: string): Promise<SinkMetadataResponse>; (filter: string, callback: SinkMetadataCallback): void;};Set the sink's filter.
This will override any filter that was previously set.
Parameter filter
The new filter.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const sink = logging.sink('my-sink');const filter = 'metadata.severity = ALERT';sink.setFilter(filter, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-sink.setFilter(filter).then(data => {const apiResponse = data[0];});
method setMetadata
setMetadata: { (metadata: SetSinkMetadata): Promise<SinkMetadataResponse>; (metadata: SetSinkMetadata, callback: SinkMetadataCallback): void;};Set the sink's metadata.
Note: If the sink was previously created or updated with uniqueWriterIdentity = true, then you must update the sink by setting uniqueWriterIdentity = true. Read more about using a unique writer identity here: https://cloud.google.com/logging/docs/api/tasks/exporting-logs#using_a_unique_writer_identity
See Sink Resource See projects.sink.update API Documentation
Parameter metadata
See a [Sink resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks#LogSink).
Parameter
{object} [metadata.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
Callback function.
Returns
{Promise}
Example 1
const {Logging} = require('@google-cloud/logging');const logging = new Logging();const sink = logging.sink('my-sink');const metadata = {filter: 'metadata.severity = ALERT'};sink.setMetadata(metadata, (err, apiResponse) => {});//-// If the callback is omitted, we'll return a Promise.//-sink.setMetadata(metadata).then(data => {const apiResponse = data[0];});Example 2
include:samples/sinks.js region_tag:logging_update_sink Another example:
Interfaces
interface AbortableDuplex
interface AbortableDuplex extends Duplex {}method abort
abort: () => void;interface CreateSinkCallback
interface CreateSinkCallback {}call signature
(err: Error | null, sink?: Sink | null, resp?: LogSink): void;interface CreateSinkRequest
interface CreateSinkRequest {}property destination
destination: any;property filter
filter?: string;property gaxOptions
gaxOptions?: gax.CallOptions;property includeChildren
includeChildren?: boolean;property name
name?: string;property outputVersionFormat
outputVersionFormat?: google.logging.v2.LogSink.VersionFormat;property uniqueWriterIdentity
uniqueWriterIdentity?: string | boolean;interface DeleteCallback
interface DeleteCallback {}call signature
(error?: Error | null, response?: google.protobuf.Empty): void;interface GetEntriesCallback
interface GetEntriesCallback {}call signature
( err: Error | null, entries?: Entry[], request?: google.logging.v2.IListLogEntriesRequest, apiResponse?: google.logging.v2.IListLogEntriesResponse): void;interface GetLogsCallback
interface GetLogsCallback {}call signature
( err: Error | null, entries?: Sink[], request?: google.logging.v2.IListLogsRequest, apiResponse?: google.logging.v2.IListLogsResponse): void;interface GetLogsRequest
interface GetLogsRequest {}property autoPaginate
autoPaginate?: boolean;property gaxOptions
gaxOptions?: gax.CallOptions;property maxApiCalls
maxApiCalls?: number;property maxResults
maxResults?: number;property pageSize
pageSize?: number;property pageToken
pageToken?: string;interface GetSinksCallback
interface GetSinksCallback {}call signature
( err: Error | null, entries?: Sink[], request?: google.logging.v2.IListSinksRequest, apiResponse?: google.logging.v2.IListSinksResponse): void;interface GetSinksRequest
interface GetSinksRequest {}property autoPaginate
autoPaginate?: boolean;property gaxOptions
gaxOptions?: gax.CallOptions;property maxApiCalls
maxApiCalls?: number;property maxResults
maxResults?: number;property pageSize
pageSize?: number;property pageToken
pageToken?: string;interface HttpRequest
interface CloudLoggingHttpRequest {}property cacheFillBytes
cacheFillBytes?: number;property cacheHit
cacheHit?: boolean;property cacheLookup
cacheLookup?: boolean;property cacheValidatedWithOriginServer
cacheValidatedWithOriginServer?: boolean;property latency
latency?: { seconds: number; nanos: number;};property protocol
protocol?: string;property referer
referer?: string;property remoteIp
remoteIp?: string;property requestMethod
requestMethod?: string;property requestSize
requestSize?: number;property requestUrl
requestUrl?: string;property responseSize
responseSize?: number;property serverIp
serverIp?: string;property status
status?: number;property userAgent
userAgent?: string;interface LoggingOptions
interface LoggingOptions extends gax.GrpcClientOptions {}property apiEndpoint
apiEndpoint?: string;property autoRetry
autoRetry?: boolean;property maxRetries
maxRetries?: number;interface RequestCallback
interface RequestCallback<TResponse> {}call signature
(err: Error | null, res?: TResponse): void;interface RequestConfig
interface RequestConfig {}interface ServiceContext
interface ServiceContext {}For logged errors, one can provide a the service context. For more information see [this guide]https://cloud.google.com/error-reporting/docs/formatting-error-messages and the [official documentation]https://cloud.google.com/error-reporting/reference/rest/v1beta1/ServiceContext.
interface TailEntriesResponse
interface TailEntriesResponse {}property entries
entries: Entry[];property suppressionInfo
suppressionInfo: google.logging.v2.TailLogEntriesResponse.SuppressionInfo;Enums
enum Severity
enum Severity { emergency = 0, alert = 1, critical = 2, error = 3, warning = 4, notice = 5, info = 6, debug = 7,}Type Aliases
type Client
type Client = string;type DeleteResponse
type DeleteResponse = google.protobuf.Empty;type GetEntriesResponse
type GetEntriesResponse = [ Entry[], google.logging.v2.IListLogEntriesRequest, google.logging.v2.IListLogEntriesResponse];type GetLogsResponse
type GetLogsResponse = [ Sink[], google.logging.v2.IListLogsRequest, google.logging.v2.IListLogsResponse];type GetSinksResponse
type GetSinksResponse = [ Sink[], google.logging.v2.IListSinksRequest, google.logging.v2.IListSinksResponse];type LogSink
type LogSink = google.logging.v2.ILogSink;type MonitoredResource
type MonitoredResource = google.api.IMonitoredResource;type SeverityNames
type SeverityNames = keyof typeof Severity;Namespaces
namespace middleware
module 'build/src/middleware/index.d.ts' {}namespace express
module 'build/src/middleware/express/index.d.ts' {}function makeMiddleware
makeMiddleware: <LoggerType>( projectId: string, makeChildLogger: ( trace: string, span?: string, traceSampled?: boolean ) => LoggerType, emitRequestLog?: ( httpRequest: CloudLoggingHttpRequest, trace: string, span?: string, traceSampled?: boolean ) => void) => (req: ServerRequest, res: http.ServerResponse, next: Function) => void;Generates an express middleware that installs a request-specific logger on the
requestobject. It optionally can do HttpRequest timing that can be used for generating request logs. This can be used to integrate with logging libraries such as winston and bunyan.Parameter projectId
Generated traceIds will be associated with this project.
Parameter makeChildLogger
A function that generates logger instances that will be installed onto
reqasreq.log. The logger should include the trace in each log entry's metadata (associated with the LOGGING_TRACE_KEY property.Parameter emitRequestLog
Optional. A function that will emit a parent request log. While some environments like GAE and GCF emit parent request logs automatically, other environments do not. When provided this function will be called with a populated
CloudLoggingHttpRequestwhich can be emitted as request log.
Package Files (11)
- build/src/entry.d.ts
- build/src/index.d.ts
- build/src/log-sync.d.ts
- build/src/log.d.ts
- build/src/middleware/express/index.d.ts
- build/src/middleware/express/make-middleware.d.ts
- build/src/middleware/index.d.ts
- build/src/sink.d.ts
- build/src/utils/http-request.d.ts
- build/src/utils/log-common.d.ts
- build/src/utils/metadata.d.ts
Dependencies (17)
Dev Dependencies (38)
- @google-cloud/bigquery
- @google-cloud/opentelemetry-cloud-trace-exporter
- @google-cloud/pubsub
- @google-cloud/storage
- @opentelemetry/api
- @opentelemetry/resources
- @opentelemetry/sdk-node
- @opentelemetry/sdk-trace-base
- @opentelemetry/sdk-trace-node
- @opentelemetry/semantic-conventions
- @types/extend
- @types/mocha
- @types/node
- @types/on-finished
- @types/proxyquire
- @types/pumpify
- @types/sinon
- bignumber.js
- c8
- codecov
- cross-env
- gapic-tools
- gts
- http2spy
- jsdoc
- jsdoc-fresh
- jsdoc-region-tag
- mocha
- nock
- null-loader
- pack-n-play
- proxyquire
- sinon
- ts-loader
- typescript
- uglify-js
- webpack
- webpack-cli
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@google-cloud/logging.
- Markdown[](https://www.jsdocs.io/package/@google-cloud/logging)
- HTML<a href="https://www.jsdocs.io/package/@google-cloud/logging"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5556 ms. - Missing or incorrect documentation? Open an issue for this package.
