/
log.ts
72 lines (61 loc) · 1.31 KB
/
log.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
import { Logging } from "@google-cloud/logging";
const LOG_NAME = "custom-log";
// This makes the logs appear in the same place as console.log()
// invocations from Cloud Functions
const METADATA = {
resource: {
type: "cloud_function",
labels: {
function_name: "CustomMetrics",
region: "us-central1"
}
},
severity: "DEBUG"
};
// The Logging instance detects the project ID from the environment
// automatically.
const logging = new Logging();
const log = logging.log(LOG_NAME);
export enum Level {
ALL = 0,
DEBUG = 1,
WARN = 2,
ERROR = 3,
NONE = 4
}
let LOG_LEVEL = Level.ALL;
export function setLogLevel(level: Level) {
LOG_LEVEL = level;
}
export function debug(message: any, ...args: any[]) {
if (LOG_LEVEL > Level.DEBUG) {
return;
}
if (args) {
console.log(message, ...args);
} else {
console.log(message);
}
}
export function warn(message: any, ...args: any) {
if (LOG_LEVEL > Level.WARN) {
return;
}
if (args) {
console.warn(message, ...args);
} else {
console.warn(message);
}
}
/**
* Log JSON data.
*/
export function logData(data: any) {
// Add a message (if there isn't one)
if (!data.message) {
data.message = JSON.stringify(data);
}
const entry = log.entry(METADATA, data);
// Log (fire-and-forget)
log.write(entry);
}