-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[log] log contextId and userId (#18688)
- Loading branch information
1 parent
49d1d4f
commit 225040d
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/** | ||
* Copyright (c) 2023 Gitpod GmbH. All rights reserved. | ||
* Licensed under the GNU Affero General Public License (AGPL). | ||
* See License.AGPL.txt in the project root for license information. | ||
*/ | ||
|
||
import { LogContext } from "@gitpod/gitpod-protocol/lib/util/logging"; | ||
import { AsyncLocalStorage } from "node:async_hooks"; | ||
import { v4 } from "uuid"; | ||
|
||
// we are installing a special augmenter that enhances the log context if executed within `runWithContext` | ||
// with a contextId and a contextTimeMs, which denotes the amount of milliseconds since the context was created. | ||
type EnhancedLogContext = LogContext & { | ||
contextId?: string; | ||
contextTimeMs: number; | ||
}; | ||
const asyncLocalStorage = new AsyncLocalStorage<EnhancedLogContext>(); | ||
const augmenter: LogContext.Augmenter = (ctx) => { | ||
const globalContext = asyncLocalStorage.getStore(); | ||
const contextTime = globalContext?.contextTimeMs ? Date.now() - globalContext.contextTimeMs : undefined; | ||
return { | ||
...globalContext, | ||
contextTime, | ||
...ctx, | ||
}; | ||
}; | ||
LogContext.setAugmenter(augmenter); | ||
|
||
export async function runWithContext<T>(context: LogContext, fun: () => T): Promise<T> { | ||
return asyncLocalStorage.run( | ||
{ | ||
...context, | ||
contextId: v4(), | ||
contextTimeMs: Date.now(), | ||
}, | ||
fun, | ||
); | ||
} |
This file contains 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