Last active
June 27, 2017 23:23
-
-
Save mrister/1587e39d23e1432c33447160abd51933 to your computer and use it in GitHub Desktop.
Logging to Loggly with async await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// run npm i loggly --save | |
import * as loggly from 'node-loggly-bulk'; | |
interface LoggingClient { | |
log(obj: any, cb:Function): any | |
} | |
const client: LoggingClient = loggly.createClient({ | |
token: 'YOUR_APPLICATION_TOKEN', | |
subdomain: 'YOUR_SUBDOMAIN', | |
json: true | |
}); | |
async function logToLoggly(obj): Promise<boolean> { | |
// promisify | |
return new Promise<boolean>((resolve: Function, reject: Function) => { | |
return client.log(obj, (err, result) => { | |
if (err) return reject(err); | |
if (result.response === 'ok') return resolve(true); | |
return reject(new Error('Data not sent to Loggly')); | |
}); | |
}); | |
} | |
interface User { | |
firstName: string, | |
lastName: string | |
id?: number | |
} | |
async function getUser(id: number): Promise<User> { | |
const testUser: User = { | |
id, | |
firstName: 'MATTHEW', | |
lastName: 'SETTER' | |
}; | |
// simulate a remote (asnyc) call to get a user | |
return new Promise<User>((resolve) => { | |
process.nextTick(() => resolve(testUser)) | |
}); | |
} | |
// Test out the code | |
async function run() { | |
try { | |
const user1: User = await getUser(1); | |
await logToLoggly(user1); | |
const user2: User = await getUser(2); | |
await logToLoggly(user2); | |
// log them both in same object | |
await logToLoggly({user1, user2}); | |
process.exit(0); | |
} catch (e) { | |
process.exit(1); | |
console.error(e); | |
} | |
} | |
// run it and observe the logs! | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment