Skip to content

Commit

Permalink
docs(samples): updated samples code to use async await (#329)
Browse files Browse the repository at this point in the history
  • Loading branch information
praveenqlogic authored and JustinBeckwith committed Nov 22, 2018
1 parent cfd74da commit 8e231b4
Show file tree
Hide file tree
Showing 3 changed files with 233 additions and 286 deletions.
257 changes: 116 additions & 141 deletions samples/logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

'use strict';

function writeLogEntry(logName) {
async function writeLogEntry(logName) {
// [START logging_write_log_entry]
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');
Expand Down Expand Up @@ -53,18 +53,13 @@ function writeLogEntry(logName) {

// 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);
});
await log.write([entry, secondEntry]);
console.log(`Wrote to ${logName}`);

// [END logging_write_log_entry]
}

function writeLogEntryAdvanced(logName, options) {
async function writeLogEntryAdvanced(logName, options) {
// [START logging_write_log_entry_advanced]
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');
Expand All @@ -88,18 +83,13 @@ function writeLogEntryAdvanced(logName, options) {

// 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);
});
await log.write(entry);
console.log(`Wrote to ${logName}`);

// [END logging_write_log_entry_advanced]
}

function listLogEntries(logName) {
async function listLogEntries(logName) {
// [START logging_list_log_entries]
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');
Expand All @@ -117,24 +107,17 @@ function listLogEntries(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);
});
const [entries] = await log.getEntries();
console.log('Logs:');
entries.forEach(entry => {
const metadata = entry.metadata;
console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
});

// [END logging_list_log_entries]
}

function listLogEntriesAdvanced(filter, pageSize, orderBy) {
async function listLogEntriesAdvanced(filter, pageSize, orderBy) {
// [START logging_list_log_entries_advanced]
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');
Expand All @@ -161,24 +144,17 @@ function listLogEntriesAdvanced(filter, pageSize, 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);
});
const [entries] = await logging.getEntries(options);
console.log('Logs:');
entries.forEach(entry => {
const metadata = entry.metadata;
console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
});

// [START logging_list_log_entries_advanced]
}

function deleteLog(logName) {
async function deleteLog(logName) {
// [START logging_delete_log]
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');
Expand All @@ -197,102 +173,101 @@ function deleteLog(logName) {
// 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);
});
await log.delete();
console.log(`Deleted log: ${logName}`);

// [END logging_delete_log]
}

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.',
async function main() {
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;
opts => {
listLogEntriesAdvanced(opts.filter, opts.limit, opts.sort);
}

try {
opts.entry = JSON.parse(opts.entry);
} catch (err) {
console.error('"entry" must be a valid JSON string!');
return;
)
.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) {
console.error('"entry" must be a valid JSON string!');
return;
}

writeLogEntryAdvanced(opts.logName, opts);
}
)
.command(
'write-simple <logName>',
'Writes a basic log entry to the specified log.',
{},
opts => {
writeLogEntry(opts.logName);
}
)
.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().argv;
}

writeLogEntryAdvanced(opts.logName, opts);
}
)
.command(
'write-simple <logName>',
'Writes a basic log entry to the specified log.',
{},
opts => {
writeLogEntry(opts.logName);
}
)
.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().argv;
main().catch(console.error);
68 changes: 33 additions & 35 deletions samples/quickstart.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,40 +14,38 @@
*/

'use strict';
async function main() {
// [START logging_quickstart]
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// [START logging_quickstart]
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Creates a client
const logging = new Logging({
projectId: projectId,
});

// The name of the log to write to
const logName = 'my-log';
// Selects the log to write to
const log = logging.log(logName);

// The data to write to the log
const text = 'Hello, world!';
// The metadata associated with the entry
const metadata = {
resource: {type: 'global'},
};
// Prepares a log entry
const entry = log.entry(metadata, text);

// Writes the log entry
log
.write(entry)
.then(() => {
console.log(`Logged: ${text}`);
})
.catch(err => {
console.error('ERROR:', err);
// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Creates a client
const logging = new Logging({
projectId: projectId,
});
// [END logging_quickstart]

// The name of the log to write to
const logName = 'my-log';
// Selects the log to write to
const log = logging.log(logName);

// The data to write to the log
const text = 'Hello, world!';
// The metadata associated with the entry
const metadata = {
resource: {type: 'global'},
};
// Prepares a log entry
const entry = log.entry(metadata, text);

// Writes the log entry
await log.write(entry);
console.log(`Logged: ${text}`);

// [END logging_quickstart]
}

main().catch(console.error);
Loading

0 comments on commit 8e231b4

Please sign in to comment.