Skip to content

Instantly share code, notes, and snippets.

@tripodsan
Last active November 21, 2019 01:34
Show Gist options
  • Save tripodsan/fea64eda8bd3b0d3935abd96331b9400 to your computer and use it in GitHub Desktop.
Save tripodsan/fea64eda8bd3b0d3935abd96331b9400 to your computer and use it in GitHub Desktop.
Simple test to verify the usage of cls-hooked
/*
* Copyright 2019 Adobe. All rights reserved.
* This file is licensed to you 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 REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
// -------------------------- < helix-log >------------------------------------
// this is the global logger from helix-log
const rootLogger = {
filter: (msg) => msg,
log: (msg) => console.log('root:', rootLogger.filter(msg)),
};
// -------------------------- < openwhisk-logger >------------------------------------
const { createNamespace } = require('cls-hooked');
// test the root logger. since it was never modified, it should print the straight log message.
rootLogger.log('Hello from global');
const CLS_NAMESPACE = createNamespace('my-namespace');
// this is a message filter that appends the id from the session
function myFilter(msg) {
const id = CLS_NAMESPACE.get('id');
return `[${id}] ${msg}`;
}
// initialized our special log filter.
function init() {
rootLogger.filter = myFilter;
}
// initializes logging and runs the action
async function wrap(fn, params) {
return CLS_NAMESPACE.runAndReturn(() => {
init();
CLS_NAMESPACE.set('id', params.id);
return fn(params);
});
}
// -------------------------- < my action >------------------------------------
// this is my action code
async function run(params) {
rootLogger.log(`Hello from the action. sleeping for ${params.timeout}`);
await new Promise((resolve) => setTimeout(resolve, params.timeout));
rootLogger.log('done.');
}
// this is main action that would be exported to openwhisk
async function main(params) {
return wrap(run, params);
}
// -------------------------- < test >------------------------------------
Promise.all([
main({ id: 42, timeout: 1000 }),
main({ id: 31, timeout: 500 }),
]).then();
// invoke the logger from outside of the continuation context
rootLogger.log('Hello from global again');
/*
Prints:
root: Hello from global
root: [42] Hello from the action. sleeping for 1000
root: [31] Hello from the action. sleeping for 500
root: [undefined] Hello from global again
root: [31] done.
root: [42] done.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment