Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save phillipharding/08ef1d71a83c8c934cbefc84c2abbf51 to your computer and use it in GitHub Desktop.

Select an option

Save phillipharding/08ef1d71a83c8c934cbefc84c2abbf51 to your computer and use it in GitHub Desktop.
Shows how to use Nodejs AsyncLocalStorage to manage the azure functions runtime Invocation Context (for logging and other things) across a single invocation without having to prop-drill the InvocationContext everywhere. This is safe for concurrent/parallel invocation use and safe for scaling scenarios.
// context.ts
import { AsyncLocalStorage } from 'node:async_hooks';
import { InvocationContext } from '@azure/functions';
const asyncLocalStorage = new AsyncLocalStorage<InvocationContext>();
export function setInvocationContext(context: InvocationContext): void {
asyncLocalStorage.enterWith(context);
}
export function getInvocationContext(): InvocationContext {
const context = asyncLocalStorage.getStore();
if (!context) {
throw new Error('No invocation context available');
}
return context;
}
export function getLogger() {
return getInvocationContext();
}
// ---------------------------------------------------------------------------------------------------------
// function handler
import { app, InvocationContext } from '@azure/functions';
import { setInvocationContext } from './utils/context';
app.http('myFunction', {
methods: ['GET'],
handler: async (request, context: InvocationContext) => {
// Set context at the start of each invocation
setInvocationContext(context);
// Now call your business logic
return await myBusinessLogic(request);
}
});
// ---------------------------------------------------------------------------------------------------------
// business logic
import { getLogger } from './utils/context';
export async function myBusinessLogic(request) {
const logger = getLogger();
logger.info('Processing request');
// Call other modules that also need logging
await someOtherModule.process();
return { status: 200, body: 'Done' };
}
// ---------------------------------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment