From dfc2d2c115930fd8c487f271a9e3d83b3e0e7951 Mon Sep 17 00:00:00 2001 From: Ashwin Kumar Date: Wed, 7 Feb 2024 09:38:24 -0800 Subject: [PATCH] feat(logging): add isLoggable util --- .../providers/cloudwatch/utils/isLoggable.ts | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 packages/logging/src/providers/cloudwatch/utils/isLoggable.ts diff --git a/packages/logging/src/providers/cloudwatch/utils/isLoggable.ts b/packages/logging/src/providers/cloudwatch/utils/isLoggable.ts new file mode 100644 index 00000000000..822039864b5 --- /dev/null +++ b/packages/logging/src/providers/cloudwatch/utils/isLoggable.ts @@ -0,0 +1,55 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { fetchAuthSession } from '@aws-amplify/core'; + +export const isLoggable = async ( + cloudWatchConfig: CloudWatchConfig, +): Promise => { + const { loggingConstraints } = cloudWatchConfig; + const { defaultLogLevel, categoryLogLevel } = + await getLoggingConstraint(loggingConstraints); + + let resolvedCategoryLogLevel; + if (!!categoryLogLevel) { + resolvedCategoryLogLevel = getCategoryLogLevel(log, categoryLogLevel); + } + + return resolvedCategoryLogLevel ?? defaultLogLevel; +}; + +const getLoggingConstraint = async ( + loggingConstraints: LoggingConstraints, +): Promise => { + const { defaultLogLevel, categoryLogLevel, userLogLevel } = + loggingConstraints; + + // const { userSub } = await fetchAuthSession(); + const userSub = 'userSub1'; + + if (!!userLogLevel?.[userSub]) { + return { + defaultLogLevel: userLogLevel[userSub].defaultLogLevel, + categoryLogLevel: userLogLevel[userSub]?.categoryLogLevel, + }; + } + + return { + defaultLogLevel, + categoryLogLevel, + }; +}; + +const getCategoryLogLevel = ( + log: LogParams, + categoryLogLevel: CategoryLogLevel, +): LogLevel | undefined => { + if (!log.category) { + return undefined; + } + + const matchedKey = Object.keys(categoryLogLevel).find( + key => key.toLowerCase() === log.category.toLowerCase(), + ); + return matchedKey ? categoryLogLevel[matchedKey] : undefined; +};