-
Notifications
You must be signed in to change notification settings - Fork 99
/
entry.ts
343 lines (329 loc) · 10.9 KB
/
entry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*!
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const EventId = require('eventid');
import * as extend from 'extend';
import {google} from '../protos/protos';
import {objToStruct, structToObj, zuluToDateObj} from './utils/common';
import {
makeHttpRequestData,
CloudLoggingHttpRequest,
RawHttpRequest,
isRawHttpRequest,
} from './utils/http-request';
import {CloudTraceContext, getOrInjectContext} from './utils/context';
const eventId = new EventId();
export const INSERT_ID_KEY = 'logging.googleapis.com/insertId';
export const LABELS_KEY = 'logging.googleapis.com/labels';
export const OPERATION_KEY = 'logging.googleapis.com/operation';
export const SOURCE_LOCATION_KEY = 'logging.googleapis.com/sourceLocation';
export const SPAN_ID_KEY = 'logging.googleapis.com/spanId';
export const TRACE_KEY = 'logging.googleapis.com/trace';
export const TRACE_SAMPLED_KEY = 'logging.googleapis.com/trace_sampled';
// Accepted field types from user supported by this client library.
export type Timestamp = google.protobuf.ITimestamp | Date | string;
export type LogSeverity = google.logging.type.LogSeverity | string;
export type HttpRequest =
| google.logging.type.IHttpRequest
| CloudLoggingHttpRequest
| RawHttpRequest;
export type LogEntry = Omit<
google.logging.v2.ILogEntry,
'timestamp' | 'severity' | 'httpRequest'
> & {
timestamp?: Timestamp | null;
severity?: LogSeverity | null;
httpRequest?: HttpRequest | null;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Data = any;
// The expected format of a subset of Entry properties before submission to the
// LoggingService API.
export interface EntryJson {
timestamp: Timestamp;
insertId: number;
jsonPayload?: google.protobuf.IStruct;
textPayload?: string;
httpRequest?: google.logging.type.IHttpRequest;
trace?: string;
spanId?: string;
traceSampled?: boolean;
}
// The expected format of a subset of Entry properties before submission to a
// custom transport, most likely to process.stdout.
export interface StructuredJson {
// Universally supported properties
message?: string | object;
httpRequest?: object;
timestamp?: string;
[INSERT_ID_KEY]?: string;
[OPERATION_KEY]?: object;
[SOURCE_LOCATION_KEY]?: object;
[LABELS_KEY]?: object;
[SPAN_ID_KEY]?: string;
[TRACE_KEY]?: string;
[TRACE_SAMPLED_KEY]?: boolean;
// Properties not supported by all agents (e.g. Cloud Run, Functions)
logName?: string;
resource?: object;
}
export interface ToJsonOptions {
removeCircular?: boolean;
}
/**
* Create an entry object to define new data to insert into a meta.
*
* Note, [Cloud Logging Quotas and limits]{@link https://cloud.google.com/logging/quotas}
* dictates that the maximum log entry size, including all
* [LogEntry Resource properties]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry},
* cannot exceed _approximately_ 256 KB.
*
* @see [LogEntry JSON representation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry}
*
* @class
*
* @param {?object} [metadata] See a
* [LogEntry
* Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry).
* @param {object|string} 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`
* - `Array`
*
* Any other types are stringified with `String(value)`.
*
* @example
* ```
* 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.
* }
* });
* ```
*/
class Entry {
metadata: LogEntry;
data: Data;
constructor(metadata?: LogEntry, data?: Data) {
/**
* @name Entry#metadata
* @type {object}
* @property {Date} timestamp
* @property {number} insertId
*/
this.metadata = extend(
{
timestamp: new Date(),
},
metadata
);
// JavaScript date has a very coarse granularity (millisecond), which makes
// it quite likely that multiple log entries would have the same timestamp.
// The Logging API doesn't guarantee to preserve insertion order for entries
// with the same timestamp. The service does use `insertId` as a secondary
// ordering for entries with the same timestamp. `insertId` needs to be
// globally unique (within the project) however.
//
// We use a globally unique monotonically increasing EventId as the
// insertId.
this.metadata.insertId = this.metadata.insertId || eventId.new();
/**
* @name Entry#data
* @type {object}
*/
this.data = data;
}
/**
* Serialize an entry to the format the API expects. Read more:
* https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
*
* @param {object} [options] Configuration object.
* @param {boolean} [options.removeCircular] Replace circular references in an
* object with a string value, `[Circular]`.
* @param {string} [projectId] GCP Project ID.
*/
toJSON(options: ToJsonOptions = {}, projectId = '') {
const entry: EntryJson = extend(true, {}, this.metadata) as {} as EntryJson;
// Format log message
if (Object.prototype.toString.call(this.data) === '[object Object]') {
entry.jsonPayload = objToStruct(this.data, {
removeCircular: !!options.removeCircular,
stringify: true,
});
} else if (typeof this.data === 'string') {
entry.textPayload = this.data;
}
// Format log timestamp
if (entry.timestamp instanceof Date) {
const seconds = entry.timestamp.getTime() / 1000;
const secondsRounded = Math.floor(seconds);
entry.timestamp = {
seconds: secondsRounded,
nanos: Math.floor((seconds - secondsRounded) * 1e9),
};
} else if (typeof entry.timestamp === 'string') {
entry.timestamp = zuluToDateObj(entry.timestamp);
}
// Format httpRequest
const req = this.metadata.httpRequest;
if (isRawHttpRequest(req)) {
entry.httpRequest = makeHttpRequestData(req);
// Format trace and span
const traceContext = this.extractTraceFromHeaders(projectId);
if (traceContext) {
if (!this.metadata.trace && traceContext.trace)
entry.trace = traceContext.trace;
if (!this.metadata.spanId && traceContext.spanId)
entry.spanId = traceContext.spanId;
if (this.metadata.traceSampled === undefined)
entry.traceSampled = traceContext.traceSampled;
}
}
return entry;
}
/**
* Serialize an entry to a standard format for any transports, e.g. agents.
* Read more: https://cloud.google.com/logging/docs/structured-logging
*/
toStructuredJSON(projectId = '') {
const meta = this.metadata;
// Mask out the keys that need to be renamed.
/* eslint-disable @typescript-eslint/no-unused-vars */
const {
textPayload,
jsonPayload,
insertId,
trace,
spanId,
traceSampled,
operation,
sourceLocation,
labels,
...validKeys
} = meta;
/* eslint-enable @typescript-eslint/no-unused-vars */
const entry: StructuredJson = extend(true, {}, validKeys) as {};
// Re-map keys names.
entry[LABELS_KEY] = meta.labels
? Object.assign({}, meta.labels)
: undefined;
entry[INSERT_ID_KEY] = meta.insertId || undefined;
entry[TRACE_KEY] = meta.trace || undefined;
entry[SPAN_ID_KEY] = meta.spanId || undefined;
entry[TRACE_SAMPLED_KEY] =
'traceSampled' in meta && meta.traceSampled !== null
? meta.traceSampled
: undefined;
// Format log payload.
entry.message =
meta.textPayload || meta.jsonPayload || meta.protoPayload || undefined;
entry.message = this.data || entry.message;
// Format timestamp
if (meta.timestamp instanceof Date) {
entry.timestamp = meta.timestamp.toISOString();
}
// Format httprequest
const req = meta.httpRequest;
if (isRawHttpRequest(req)) {
entry.httpRequest = makeHttpRequestData(req);
// Detected trace context from headers if applicable.
const traceContext = this.extractTraceFromHeaders(projectId);
if (traceContext) {
if (!entry[TRACE_KEY] && traceContext.trace)
entry[TRACE_KEY] = traceContext.trace;
if (!entry[SPAN_ID_KEY] && traceContext.spanId)
entry[SPAN_ID_KEY] = traceContext.spanId;
if (entry[TRACE_SAMPLED_KEY] === undefined)
entry[TRACE_SAMPLED_KEY] = traceContext.traceSampled;
}
}
return entry;
}
/**
* extractTraceFromHeaders extracts trace and span information from raw HTTP
* request headers only.
* @private
*/
private extractTraceFromHeaders(projectId: string): CloudTraceContext | null {
const rawReq = this.metadata.httpRequest;
if (rawReq && 'headers' in rawReq) {
return getOrInjectContext(rawReq, projectId, false);
}
return null;
}
/**
* Create an Entry object from an API response, such as `entries:list`.
*
* @private
*
* @param {object} entry An API representation of an entry. See a
* {@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry| LogEntry}.
* @returns {Entry}
*/
static fromApiResponse_(entry: google.logging.v2.LogEntry) {
let data = entry[entry.payload!];
if (entry.payload === 'jsonPayload') {
data = structToObj(data);
}
const serializedEntry = new Entry(entry, data);
if (entry.timestamp) {
let ms = Number(entry.timestamp.seconds) * 1000;
ms += Number(entry.timestamp.nanos) / 1e6;
serializedEntry.metadata.timestamp = new Date(ms);
}
return serializedEntry;
}
}
/**
* Reference to the {@link Entry} class.
* @name module:@google-cloud/logging.Entry
* @see Entry
*/
export {Entry};