-
Notifications
You must be signed in to change notification settings - Fork 598
Expand file tree
/
Copy pathgcloud-logger-config.ts
More file actions
72 lines (63 loc) · 2.43 KB
/
gcloud-logger-config.ts
File metadata and controls
72 lines (63 loc) · 2.43 KB
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
import type { pino } from 'pino';
import { convertBigintsToStrings } from './bigint-utils.js';
/* eslint-disable camelcase */
const GOOGLE_CLOUD_TRACE_ID = 'logging.googleapis.com/trace';
const GOOGLE_CLOUD_SPAN_ID = 'logging.googleapis.com/spanId';
const GOOGLE_CLOUD_TRACE_SAMPLED = 'logging.googleapis.com/trace_sampled';
/**
* Pino configuration for google cloud observability. Tweaks message and timestamp,
* adds trace context attributes, and injects severity level.
* Adapted from https://cloud.google.com/trace/docs/setup/nodejs-ot#config-structured-logging.
*/
export const GoogleCloudLoggerConfig = {
messageKey: 'message',
formatters: {
log(object: Record<string, unknown>): Record<string, unknown> {
// Convert bigints to strings recursively to avoid serialization issues
object = convertBigintsToStrings(object) as Record<string, unknown>;
// Add trace context attributes following Cloud Logging structured log format described
// in https://cloud.google.com/logging/docs/structured-logging#special-payload-fields
const { trace_id, span_id, trace_flags, ...rest } = object;
if (trace_id && span_id) {
return {
[GOOGLE_CLOUD_TRACE_ID]: trace_id,
[GOOGLE_CLOUD_SPAN_ID]: span_id,
[GOOGLE_CLOUD_TRACE_SAMPLED]: trace_flags ? trace_flags === '01' : undefined,
trace_flags, // Keep the original trace_flags for otel-pino-stream
...rest,
};
}
return object;
},
level(label: string, level: number): object {
// Inspired by https://github.com/pinojs/pino/issues/726#issuecomment-605814879
// Severity labels https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
let severity: string;
switch (label as pino.Level | keyof CustomLevels) {
case 'trace':
case 'debug':
case 'verbose':
severity = 'DEBUG';
break;
case 'info':
severity = 'INFO';
break;
case 'warn':
severity = 'WARNING';
break;
case 'error':
severity = 'ERROR';
break;
case 'fatal':
severity = 'CRITICAL';
break;
default:
severity = 'DEFAULT';
break;
}
return { severity, level };
},
},
} satisfies pino.LoggerOptions;
// Define custom logging levels for pino. Duplicate from pino-logger.ts.
type CustomLevels = { verbose: 25 };