forked from GoogleCloudPlatform/nodejs-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogs.js
More file actions
345 lines (291 loc) · 10.6 KB
/
Copy pathlogs.js
File metadata and controls
345 lines (291 loc) · 10.6 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
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
344
345
/**
* Copyright 2017, Google, Inc.
* 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.
*/
'use strict';
function writeLogEntry (logName) {
// [START logging_write_log_entry]
// Imports the Google Cloud client library
const Logging = require('@google-cloud/logging');
// Instantiates a client
const logging = Logging();
// The log to write to, e.g. "my-log"
// const logName = "my-log";
const log = logging.log(logName);
// Modify this resource to match a resource in your project
// See https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource
const resource = {
// This example targets the "global" resource for simplicity
type: 'global'
};
// A text log entry
const entry = log.entry({ resource: resource }, 'Hello, world!');
// A structured log entry
const secondEntry = log.entry({ resource: resource }, {
name: 'King Arthur',
quest: 'Find the Holy Grail',
favorite_color: 'Blue'
});
// Save the two log entries. You can write entries one at a time, but it is
// best to write multiple entires together in a batch.
log.write([entry, secondEntry])
.then(() => {
console.log(`Wrote to ${logName}`);
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END logging_write_log_entry]
}
function loggingBunyan () {
// [START logging_bunyan]
const bunyan = require('bunyan');
// Imports the Google Cloud client library for Bunyan
const LoggingBunyan = require('@google-cloud/logging-bunyan');
// Instantiates a Bunyan Stackdriver Logging client
const loggingBunyan = LoggingBunyan();
// Create a Bunyan logger that streams to Stackdriver Logging
// Logs will be written to: "projects/YOUR_PROJECT_ID/logs/bunyan_log"
const logger = bunyan.createLogger({
// The JSON payload of the log as it appears in Stackdriver Logging
// will contain "name": "my-service"
name: 'my-service',
// log at 'info' and above
level: 'info',
streams: [
// Log to the console
{ stream: process.stdout },
// And log to Stackdriver Logging
loggingBunyan.stream()
]
});
// Writes some log entries
logger.error('warp nacelles offline');
logger.info('shields at 99%');
// [END logging_bunyan]
}
function loggingWinston () {
// [START logging_winston]
const winston = require('winston');
const Logger = winston.Logger;
const Console = winston.transports.Console;
// Imports the Google Cloud client library for Winston
const LoggingWinston = require('@google-cloud/logging-winston');
// Instantiates a Winston Stackdriver Logging client
const loggingWinston = LoggingWinston();
// Create a Winston logger that streams to Stackdriver Logging
// Logs will be written to: "projects/YOUR_PROJECT_ID/logs/winston_log"
const logger = new Logger({
level: 'info', // log at 'info' and above
transports: [
// Log to the console
new Console(),
// And log to Stackdriver Logging
loggingWinston
]
});
// Writes some log entries
logger.error('warp nacelles offline');
logger.info('shields at 99%');
// [END logging_winston]
}
function bunyanSetupExplicit () {
// [START logging_bunyan_setup_explicit]
// Imports the Google Cloud client library for Bunyan
const LoggingBunyan = require('@google-cloud/logging-bunyan');
// Instantiates a client
const loggingBunyan = LoggingBunyan({
projectId: 'your-project-id',
keyFilename: '/path/to/key.json'
});
// [END logging_bunyan_setup_explicit]
console.log(loggingBunyan);
}
function winstonSetupExplicit () {
// [START logging_winston_setup_explicit]
// Imports the Google Cloud client library for Winston
const LoggingWinston = require('@google-cloud/logging-winston');
// Instantiates a client
const loggingWinston = LoggingWinston({
projectId: 'your-project-id',
keyFilename: '/path/to/key.json'
});
// [END logging_winston_setup_explicit]
console.log(loggingWinston);
}
function writeLogEntryAdvanced (logName, options) {
// [START logging_write_log_entry_advanced]
// Imports the Google Cloud client library
const Logging = require('@google-cloud/logging');
// Instantiates a client
const logging = Logging();
// The log to write to, e.g. "my-log"
// const logName = "my-log";
// The request options
// const options = {
// resource: {...},
// entry: 'Hello, world!'
// };
const log = logging.log(logName);
// Prepare the entry
const entry = log.entry({ resource: options.resource }, options.entry);
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging/log?method=write
log.write(entry)
.then(() => {
console.log(`Wrote to ${logName}`);
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END logging_write_log_entry_advanced]
}
function listLogEntries (logName) {
// [START logging_list_log_entries]
// Imports the Google Cloud client library
const Logging = require('@google-cloud/logging');
// Instantiates a client
const logging = Logging();
// The log from which to list entries, e.g. "my-log"
// const logName = "my-log";
const log = logging.log(logName);
// List the most recent entries for a given log
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging?method=getEntries
log.getEntries()
.then((results) => {
const entries = results[0];
console.log('Logs:');
entries.forEach((entry) => {
const metadata = entry.metadata;
console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
});
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END logging_list_log_entries]
}
function listLogEntriesAdvanced (filter, pageSize, orderBy) {
// [START logging_list_log_entries_advanced]
// Imports the Google Cloud client library
const Logging = require('@google-cloud/logging');
// Instantiates a client
const logging = Logging();
// 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;
// Sort results
// const orderBy = 'timestamp';
const options = {
filter: filter,
pageSize: pageSize,
orderBy: orderBy
};
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging?method=getEntries
logging.getEntries(options)
.then((results) => {
const entries = results[0];
console.log('Logs:');
entries.forEach((entry) => {
const metadata = entry.metadata;
console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
});
})
.catch((err) => {
console.error('ERROR:', err);
});
// [START logging_list_log_entries_advanced]
}
function deleteLog (logName) {
// [START logging_delete_log]
// Imports the Google Cloud client library
const Logging = require('@google-cloud/logging');
// Instantiates a client
const logging = Logging();
// The log to delete, e.g. "my-log"
// const logName = "my-log";
const log = logging.log(logName);
// Deletes a logger and all its entries.
// Note that a deletion can take several minutes to take effect.
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging/log?method=delete
log.delete()
.then(() => {
console.log(`Deleted log: ${logName}`);
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END logging_delete_log]
}
// The command-line program
const cli = require(`yargs`)
.demand(1)
.command('list', 'Lists log entries, optionally filtering, limiting, and sorting results.', {
filter: {
alias: 'f',
type: 'string',
requiresArg: true,
description: 'Only log entries matching the filter are written.'
},
limit: {
alias: 'l',
type: 'number',
requiresArg: true,
description: 'Maximum number of results to return.'
},
sort: {
alias: 's',
type: 'string',
requiresArg: true,
description: 'Sort results.'
}
}, (opts) => {
listLogEntriesAdvanced(opts.filter, opts.limit, opts.sort);
})
.command('list-simple <logName>', 'Lists log entries.', {}, (opts) => listLogEntries(opts.logName))
.command('write <logName> <resource> <entry>', 'Writes a log entry to the specified log.', {}, (opts) => {
try {
opts.resource = JSON.parse(opts.resource);
} catch (err) {
console.error('"resource" must be a valid JSON string!');
return;
}
try {
opts.entry = JSON.parse(opts.entry);
} catch (err) {}
writeLogEntryAdvanced(opts.logName, opts);
})
.command('write-simple <logName>', 'Writes a basic log entry to the specified log.', {}, (opts) => {
writeLogEntry(opts.logName);
})
.command('bunyan', 'Writes some logs entries to Stackdriver Logging via Winston.', {}, loggingBunyan)
.command('bunyan-setup', 'Setup up the Bunyan logger with explicit credentianls.', {}, bunyanSetupExplicit)
.command('winston', 'Writes some logs entries to Stackdriver Logging via Winston.', {}, loggingWinston)
.command('winston-setup', 'Setup up the Winston logger with explicit credentianls.', {}, winstonSetupExplicit)
.command('delete <logName>', 'Deletes the specified Log.', {}, (opts) => {
deleteLog(opts.logName);
})
.example('node $0 list', 'List all log entries.')
.example('node $0 list -f "severity=ERROR" -s "timestamp" -l 2', 'List up to 2 error entries, sorted by timestamp ascending.')
.example(`node $0 list -f 'logName="my-log"' -l 2`, 'List up to 2 log entries from the "my-log" log.')
.example('node $0 write my-log \'{"type":"gae_app","labels":{"module_id":"default"}}\' \'"Hello World!"\'', 'Write a string log entry.')
.example('node $0 write my-log \'{"type":"global"}\' \'{"message":"Hello World!"}\'', 'Write a JSON log entry.')
.example('node $0 delete my-log', 'Delete "my-log".')
.wrap(120)
.recommendCommands()
.epilogue(`For more information, see https://cloud.google.com/logging/docs`)
.help()
.strict();
if (module === require.main) {
cli.parse(process.argv.slice(2));
}