Actionhero tracing with Async Local Storage #2384
Answered
by
evantahler
IgorHulyaschy
asked this question in
Q&A
-
Hello, I need help, I want to use AsyncLocalStorage with actionhero Here is my wrapper for AsyncLocalStorage: const { AsyncLocalStorage } = require('async_hooks');
const { randomUUID } = require('crypto');
module.exports = class ALSWrapper {
asyncLocalStorage = new AsyncLocalStorage();
getTrace() {
const dataFromStore = this.asyncLocalStorage.getStore();
return {
traceId: dataFromStore ? dataFromStore.traceId : '',
traceMark: dataFromStore ? dataFromStore.traceMark : undefined,
};
}
startTraceWithoutPromise(fn, data = {}) {
const traceId = data.traceId || randomUUID();
const traceMark = data.traceMark || 'traceId';
this.asyncLocalStorage.run({ traceMark, traceId }, fn);
}
}; Here is my middleware that use als: class SomeCLass {
initialize: function () {
action.addMiddleware({
name: 'CorrelateTask',
global: true,
priority: 700,
preProcessor: () => {
return als.startTraceWithoutPromise(() => {},
{
traceMark: 'taskId',
});
}
});
}
} but the |
Beta Was this translation helpful? Give feedback.
Answered by
evantahler
Jan 11, 2023
Replies: 1 comment 1 reply
-
Would it work to store the local storage instance on the instance of the action's data object? import { Initializer, ActionProcessor, action } from "actionhero";
import { AsyncLocalStorage } from "node:async_hooks";
const asyncLocalStorage = new AsyncLocalStorage();
let idSeq = 0;
function logWithId(msg: string) {
const id = asyncLocalStorage.getStore();
console.log(`${id !== undefined ? id : "-"}:`, msg);
}
const asyncHookActionMiddleware: action.ActionMiddleware = {
name: "authenticated-action",
global: true,
preProcessor: async (data: ActionProcessor<any>) => {
asyncLocalStorage.run(idSeq++, () => {
const id = asyncLocalStorage.getStore();
logWithId("start");
data.session.asyncId = id;
});
},
postProcessor: async (data: ActionProcessor<any>) => {
asyncLocalStorage.run(data.session.asyncId, () => {
const id = asyncLocalStorage.getStore();
logWithId("finish");
});
},
};
export class asyncHookInitializer extends Initializer {
constructor() {
super();
this.name = "asyncHook";
}
async initialize() {
action.addMiddleware(asyncHookActionMiddleware);
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
evantahler
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would it work to store the local storage instance on the instance of the action's data object?