From 0cc7564841e801649e76d2ed3a2ca7673ce105d6 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Tue, 3 Oct 2023 16:37:12 -0700 Subject: [PATCH 01/15] feat: implement _isLoggable and corrected categoryLogLevel in UserLogLevel class --- .../logging/cloudwatch_logging_config.dart | 2 +- .../lib/src/cloudwatch_logger_plugin.dart | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.dart b/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.dart index 3012fc94a2..581da428de 100644 --- a/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.dart +++ b/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.dart @@ -161,7 +161,7 @@ class UserLogLevel _$UserLogLevelFromJson(json); final LogLevel defaultLogLevel; - final Map categoryLogLevel; + final Map categoryLogLevel; @override List get props => [defaultLogLevel, categoryLogLevel]; diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index 074f69e906..949a74ff47 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -304,7 +304,38 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin if (!_enabled) { return false; } + final loggingConstraint = _getLoggingConstraint(); + + String? userId; + + Amplify.Hub.listen(HubChannel.Auth, (AuthHubEvent event) async { + if (event.type == AuthHubEventType.signedOut || + event.type == AuthHubEventType.userDeleted || + event.type == AuthHubEventType.sessionExpired) { + userId = null; + } + if (event.type == AuthHubEventType.signedIn) { + userId = event.payload?.userId; + } + }); + + if (loggingConstraint.userLogLevel.containsKey(userId)) { + final userLevel = loggingConstraint.userLogLevel[userId]!; + + if (userLevel.categoryLogLevel.containsKey(logEntry.loggerName)) { + return logEntry.level >= + userLevel.categoryLogLevel[logEntry.loggerName]!; + } + + return logEntry.level >= userLevel.defaultLogLevel; + } + + if (loggingConstraint.categoryLogLevel.containsKey(logEntry.loggerName)) { + return logEntry.level >= + loggingConstraint.categoryLogLevel[logEntry.loggerName]!; + } + return logEntry.level >= loggingConstraint.defaultLogLevel; } From 4f29c7a3da1180cbc26cbab48109d5ea315080d0 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Wed, 4 Oct 2023 10:27:17 -0700 Subject: [PATCH 02/15] chore: added _userId private variable instead of using method variable --- .../lib/src/cloudwatch_logger_plugin.dart | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index 949a74ff47..29e6f447b4 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -126,6 +126,7 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin } }); } + String? _userId; final CloudWatchPluginConfig _pluginConfig; final CloudWatchLogsClient _client; @@ -313,14 +314,14 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin if (event.type == AuthHubEventType.signedOut || event.type == AuthHubEventType.userDeleted || event.type == AuthHubEventType.sessionExpired) { - userId = null; + _userId = null; } if (event.type == AuthHubEventType.signedIn) { - userId = event.payload?.userId; + _userId = event.payload?.userId; } }); - if (loggingConstraint.userLogLevel.containsKey(userId)) { + if (loggingConstraint.userLogLevel.containsKey(_userId)) { final userLevel = loggingConstraint.userLogLevel[userId]!; if (userLevel.categoryLogLevel.containsKey(logEntry.loggerName)) { From 72de02f2f62f58fda23ec3d189224d7877a361fa Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Wed, 4 Oct 2023 10:47:07 -0700 Subject: [PATCH 03/15] chore: add aft workflows --- .github/dependabot.yaml | 56 ++++++++---- .../amplify_logging_cloudwatch_example.yaml | 86 ++++++++++++++++++- .../logging/cloudwatch_logging_config.g.dart | 5 +- .../.flutter-plugins | 7 ++ .../.flutter-plugins-dependencies | 1 + 5 files changed, 134 insertions(+), 21 deletions(-) create mode 100644 packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins create mode 100644 packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml index 8c14eafba7..d7a178b3fc 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -1917,15 +1917,27 @@ updates: update-types: - "version-update:semver-patch" # Ignore all repo packages + - dependency-name: "amplify_auth_cognito" + - dependency-name: "amplify_analytics_pinpoint" + - dependency-name: "amplify_analytics_pinpoint_dart" + - dependency-name: "amplify_core" + - dependency-name: "aws_common" - dependency-name: "amplify_lints" - # Group dependencies which have a constraint set in the global "pubspec.yaml" - groups: - build_runner: - patterns: - - "build_runner" - build_web_compilers: - patterns: - - "build_web_compilers" + - dependency-name: "aws_logging_cloudwatch" + - dependency-name: "aws_signature_v4" + - dependency-name: "smithy" + - dependency-name: "smithy_aws" + - dependency-name: "amplify_db_common_dart" + - dependency-name: "amplify_secure_storage_dart" + - dependency-name: "worker_bee" + - dependency-name: "worker_bee_builder" + - dependency-name: "amplify_db_common" + - dependency-name: "amplify_secure_storage" + - dependency-name: "amplify_auth_cognito_dart" + - dependency-name: "smithy_codegen" + - dependency-name: "amplify_flutter" + - dependency-name: "amplify_logging_cloudwatch" + - dependency-name: "amplify_authenticator" - package-ecosystem: "pub" directory: "packages/logging_cloudwatch/amplify_logging_cloudwatch/example" schedule: @@ -1936,15 +1948,27 @@ updates: update-types: - "version-update:semver-patch" # Ignore all repo packages + - dependency-name: "amplify_auth_cognito" + - dependency-name: "amplify_analytics_pinpoint" + - dependency-name: "amplify_analytics_pinpoint_dart" + - dependency-name: "amplify_core" + - dependency-name: "aws_common" - dependency-name: "amplify_lints" - # Group dependencies which have a constraint set in the global "pubspec.yaml" - groups: - build_runner: - patterns: - - "build_runner" - build_web_compilers: - patterns: - - "build_web_compilers" + - dependency-name: "aws_logging_cloudwatch" + - dependency-name: "aws_signature_v4" + - dependency-name: "smithy" + - dependency-name: "smithy_aws" + - dependency-name: "amplify_db_common_dart" + - dependency-name: "amplify_secure_storage_dart" + - dependency-name: "worker_bee" + - dependency-name: "worker_bee_builder" + - dependency-name: "amplify_db_common" + - dependency-name: "amplify_secure_storage" + - dependency-name: "amplify_auth_cognito_dart" + - dependency-name: "smithy_codegen" + - dependency-name: "amplify_flutter" + - dependency-name: "amplify_logging_cloudwatch" + - dependency-name: "amplify_authenticator" - package-ecosystem: "pub" directory: "packages/logging_cloudwatch/aws_logging_cloudwatch" schedule: diff --git a/.github/workflows/amplify_logging_cloudwatch_example.yaml b/.github/workflows/amplify_logging_cloudwatch_example.yaml index f29ae7a98e..3ab6b1503d 100644 --- a/.github/workflows/amplify_logging_cloudwatch_example.yaml +++ b/.github/workflows/amplify_logging_cloudwatch_example.yaml @@ -7,23 +7,103 @@ on: - stable paths: - '.github/workflows/amplify_logging_cloudwatch_example.yaml' - - '.github/workflows/dart_vm.yaml' + - '.github/workflows/flutter_vm.yaml' + - 'packages/amplify/amplify_flutter/lib/**/*.dart' + - 'packages/amplify/amplify_flutter/pubspec.yaml' + - 'packages/amplify_core/lib/**/*.dart' + - 'packages/amplify_core/pubspec.yaml' - 'packages/amplify_lints/lib/**/*.yaml' - 'packages/amplify_lints/pubspec.yaml' + - 'packages/analytics/amplify_analytics_pinpoint/lib/**/*.dart' + - 'packages/analytics/amplify_analytics_pinpoint/pubspec.yaml' + - 'packages/analytics/amplify_analytics_pinpoint_dart/lib/**/*.dart' + - 'packages/analytics/amplify_analytics_pinpoint_dart/pubspec.yaml' + - 'packages/auth/amplify_auth_cognito/lib/**/*.dart' + - 'packages/auth/amplify_auth_cognito/pubspec.yaml' + - 'packages/auth/amplify_auth_cognito_dart/lib/**/*.dart' + - 'packages/auth/amplify_auth_cognito_dart/pubspec.yaml' + - 'packages/authenticator/amplify_authenticator/lib/**/*.dart' + - 'packages/authenticator/amplify_authenticator/pubspec.yaml' + - 'packages/aws_common/lib/**/*.dart' + - 'packages/aws_common/pubspec.yaml' + - 'packages/aws_signature_v4/lib/**/*.dart' + - 'packages/aws_signature_v4/pubspec.yaml' + - 'packages/common/amplify_db_common/lib/**/*.dart' + - 'packages/common/amplify_db_common/pubspec.yaml' + - 'packages/common/amplify_db_common_dart/lib/**/*.dart' + - 'packages/common/amplify_db_common_dart/pubspec.yaml' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/**/*.dart' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/**/*.yaml' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/lib/**/*' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/test/**/*' + - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/lib/**/*.dart' + - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/pubspec.yaml' + - 'packages/logging_cloudwatch/aws_logging_cloudwatch/lib/**/*.dart' + - 'packages/logging_cloudwatch/aws_logging_cloudwatch/pubspec.yaml' + - 'packages/secure_storage/amplify_secure_storage/lib/**/*.dart' + - 'packages/secure_storage/amplify_secure_storage/pubspec.yaml' + - 'packages/secure_storage/amplify_secure_storage_dart/lib/**/*.dart' + - 'packages/secure_storage/amplify_secure_storage_dart/pubspec.yaml' + - 'packages/smithy/smithy/lib/**/*.dart' + - 'packages/smithy/smithy/pubspec.yaml' + - 'packages/smithy/smithy_aws/lib/**/*.dart' + - 'packages/smithy/smithy_aws/pubspec.yaml' + - 'packages/smithy/smithy_codegen/lib/**/*.dart' + - 'packages/smithy/smithy_codegen/pubspec.yaml' + - 'packages/worker_bee/worker_bee/lib/**/*.dart' + - 'packages/worker_bee/worker_bee/pubspec.yaml' + - 'packages/worker_bee/worker_bee_builder/lib/**/*.dart' + - 'packages/worker_bee/worker_bee_builder/pubspec.yaml' pull_request: paths: - '.github/workflows/amplify_logging_cloudwatch_example.yaml' - - '.github/workflows/dart_vm.yaml' + - '.github/workflows/flutter_vm.yaml' + - 'packages/amplify/amplify_flutter/lib/**/*.dart' + - 'packages/amplify/amplify_flutter/pubspec.yaml' + - 'packages/amplify_core/lib/**/*.dart' + - 'packages/amplify_core/pubspec.yaml' - 'packages/amplify_lints/lib/**/*.yaml' - 'packages/amplify_lints/pubspec.yaml' + - 'packages/analytics/amplify_analytics_pinpoint/lib/**/*.dart' + - 'packages/analytics/amplify_analytics_pinpoint/pubspec.yaml' + - 'packages/analytics/amplify_analytics_pinpoint_dart/lib/**/*.dart' + - 'packages/analytics/amplify_analytics_pinpoint_dart/pubspec.yaml' + - 'packages/auth/amplify_auth_cognito/lib/**/*.dart' + - 'packages/auth/amplify_auth_cognito/pubspec.yaml' + - 'packages/auth/amplify_auth_cognito_dart/lib/**/*.dart' + - 'packages/auth/amplify_auth_cognito_dart/pubspec.yaml' + - 'packages/authenticator/amplify_authenticator/lib/**/*.dart' + - 'packages/authenticator/amplify_authenticator/pubspec.yaml' + - 'packages/aws_common/lib/**/*.dart' + - 'packages/aws_common/pubspec.yaml' + - 'packages/aws_signature_v4/lib/**/*.dart' + - 'packages/aws_signature_v4/pubspec.yaml' + - 'packages/common/amplify_db_common/lib/**/*.dart' + - 'packages/common/amplify_db_common/pubspec.yaml' + - 'packages/common/amplify_db_common_dart/lib/**/*.dart' + - 'packages/common/amplify_db_common_dart/pubspec.yaml' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/**/*.dart' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/**/*.yaml' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/lib/**/*' - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/example/test/**/*' + - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/lib/**/*.dart' + - 'packages/logging_cloudwatch/amplify_logging_cloudwatch/pubspec.yaml' + - 'packages/logging_cloudwatch/aws_logging_cloudwatch/lib/**/*.dart' + - 'packages/logging_cloudwatch/aws_logging_cloudwatch/pubspec.yaml' + - 'packages/secure_storage/amplify_secure_storage/lib/**/*.dart' + - 'packages/secure_storage/amplify_secure_storage/pubspec.yaml' + - 'packages/secure_storage/amplify_secure_storage_dart/lib/**/*.dart' + - 'packages/secure_storage/amplify_secure_storage_dart/pubspec.yaml' + - 'packages/smithy/smithy/lib/**/*.dart' + - 'packages/smithy/smithy/pubspec.yaml' + - 'packages/smithy/smithy_aws/lib/**/*.dart' + - 'packages/smithy/smithy_aws/pubspec.yaml' + - 'packages/smithy/smithy_codegen/lib/**/*.dart' + - 'packages/smithy/smithy_codegen/pubspec.yaml' + - 'packages/worker_bee/worker_bee/lib/**/*.dart' + - 'packages/worker_bee/worker_bee/pubspec.yaml' + - 'packages/worker_bee/worker_bee_builder/lib/**/*.dart' + - 'packages/worker_bee/worker_bee_builder/pubspec.yaml' schedule: - cron: "0 6,12 * * *" # Every day at 06:00 and 12:00 defaults: @@ -40,7 +120,7 @@ concurrency: jobs: test: - uses: ./.github/workflows/dart_vm.yaml + uses: ./.github/workflows/flutter_vm.yaml with: package-name: amplify_logging_cloudwatch_example working-directory: packages/logging_cloudwatch/amplify_logging_cloudwatch/example diff --git a/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.g.dart b/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.g.dart index 72ab29ce57..b7aa0da96a 100644 --- a/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.g.dart +++ b/packages/amplify_core/lib/src/config/logging/cloudwatch_logging_config.g.dart @@ -104,7 +104,7 @@ UserLogLevel _$UserLogLevelFromJson(Map json) => UserLogLevel( LogLevel.error, categoryLogLevel: (json['categoryLogLevel'] as Map?)?.map( - (k, e) => MapEntry(k, e as String), + (k, e) => MapEntry(k, $enumDecode(_$LogLevelEnumMap, e)), ) ?? const {}, ); @@ -112,5 +112,6 @@ UserLogLevel _$UserLogLevelFromJson(Map json) => UserLogLevel( Map _$UserLogLevelToJson(UserLogLevel instance) => { 'defaultLogLevel': _$LogLevelEnumMap[instance.defaultLogLevel]!, - 'categoryLogLevel': instance.categoryLogLevel, + 'categoryLogLevel': instance.categoryLogLevel + .map((k, e) => MapEntry(k, _$LogLevelEnumMap[e]!)), }; diff --git a/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins b/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins new file mode 100644 index 0000000000..f081e27981 --- /dev/null +++ b/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins @@ -0,0 +1,7 @@ +# This is a generated file; do not edit or check into version control. +device_info_plus=/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/ +path_provider=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider-2.1.1/ +path_provider_android=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_android-2.2.0/ +path_provider_foundation=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_foundation-2.3.1/ +path_provider_linux=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_linux-2.2.1/ +path_provider_windows=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_windows-2.2.1/ diff --git a/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies b/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies new file mode 100644 index 0000000000..ccf2b7ad23 --- /dev/null +++ b/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies @@ -0,0 +1 @@ +{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":true,"dependencies":[]},{"name":"path_provider_foundation","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_foundation-2.3.1/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"android":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":true,"dependencies":[]},{"name":"path_provider_android","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_android-2.2.0/","native_build":true,"dependencies":[]}],"macos":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":true,"dependencies":[]},{"name":"path_provider_foundation","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_foundation-2.3.1/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"linux":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":false,"dependencies":[]},{"name":"path_provider_linux","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_linux-2.2.1/","native_build":false,"dependencies":[]}],"windows":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":false,"dependencies":[]},{"name":"path_provider_windows","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_windows-2.2.1/","native_build":false,"dependencies":[]}],"web":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","dependencies":[]}]},"dependencyGraph":[{"name":"device_info_plus","dependencies":[]},{"name":"path_provider","dependencies":["path_provider_android","path_provider_foundation","path_provider_linux","path_provider_windows"]},{"name":"path_provider_android","dependencies":[]},{"name":"path_provider_foundation","dependencies":[]},{"name":"path_provider_linux","dependencies":[]},{"name":"path_provider_windows","dependencies":[]}],"date_created":"2023-10-04 10:41:43.565295","version":"3.10.6"} \ No newline at end of file From 8cc4dec6b3efb29a6dde148241f7730ce1b6b6a2 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Wed, 4 Oct 2023 11:49:01 -0700 Subject: [PATCH 04/15] chore: added helper method make sure category keys match --- .../lib/src/cloudwatch_logger_plugin.dart | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index 29e6f447b4..b3bb43875d 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -308,8 +308,6 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin final loggingConstraint = _getLoggingConstraint(); - String? userId; - Amplify.Hub.listen(HubChannel.Auth, (AuthHubEvent event) async { if (event.type == AuthHubEventType.signedOut || event.type == AuthHubEventType.userDeleted || @@ -322,24 +320,34 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin }); if (loggingConstraint.userLogLevel.containsKey(_userId)) { - final userLevel = loggingConstraint.userLogLevel[userId]!; + final userLevel = loggingConstraint.userLogLevel[_userId]!; - if (userLevel.categoryLogLevel.containsKey(logEntry.loggerName)) { - return logEntry.level >= - userLevel.categoryLogLevel[logEntry.loggerName]!; + if (_checkLogLevel(userLevel.categoryLogLevel, logEntry)) { + return true; } return logEntry.level >= userLevel.defaultLogLevel; } - if (loggingConstraint.categoryLogLevel.containsKey(logEntry.loggerName)) { - return logEntry.level >= - loggingConstraint.categoryLogLevel[logEntry.loggerName]!; + if (_checkLogLevel(loggingConstraint.categoryLogLevel, logEntry)) { + return true; } return logEntry.level >= loggingConstraint.defaultLogLevel; } + bool _checkLogLevel( + Map categoryLogLevel, + LogEntry logEntry, + ) { + for (final entry in categoryLogLevel.entries) { + if (logEntry.loggerName.contains(entry.key)) { + return logEntry.level >= entry.value; + } + } + return false; + } + @override Future handleLogEntry(LogEntry logEntry) async { if (!(_isLoggable(logEntry))) { From 58cddf4a89cd64b7d7f00aaa76c9c7551dc105ef Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Wed, 4 Oct 2023 12:02:45 -0700 Subject: [PATCH 05/15] chore: removed unnecessary new listener --- .../amplify_logging_cloudwatch/.flutter-plugins | 7 ------- .../.flutter-plugins-dependencies | 1 - .../lib/src/cloudwatch_logger_plugin.dart | 15 ++++----------- 3 files changed, 4 insertions(+), 19 deletions(-) delete mode 100644 packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins delete mode 100644 packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies diff --git a/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins b/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins deleted file mode 100644 index f081e27981..0000000000 --- a/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins +++ /dev/null @@ -1,7 +0,0 @@ -# This is a generated file; do not edit or check into version control. -device_info_plus=/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/ -path_provider=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider-2.1.1/ -path_provider_android=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_android-2.2.0/ -path_provider_foundation=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_foundation-2.3.1/ -path_provider_linux=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_linux-2.2.1/ -path_provider_windows=/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_windows-2.2.1/ diff --git a/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies b/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies deleted file mode 100644 index ccf2b7ad23..0000000000 --- a/packages/logging_cloudwatch/amplify_logging_cloudwatch/.flutter-plugins-dependencies +++ /dev/null @@ -1 +0,0 @@ -{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":true,"dependencies":[]},{"name":"path_provider_foundation","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_foundation-2.3.1/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"android":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":true,"dependencies":[]},{"name":"path_provider_android","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_android-2.2.0/","native_build":true,"dependencies":[]}],"macos":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":true,"dependencies":[]},{"name":"path_provider_foundation","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_foundation-2.3.1/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"linux":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":false,"dependencies":[]},{"name":"path_provider_linux","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_linux-2.2.1/","native_build":false,"dependencies":[]}],"windows":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","native_build":false,"dependencies":[]},{"name":"path_provider_windows","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/path_provider_windows-2.2.1/","native_build":false,"dependencies":[]}],"web":[{"name":"device_info_plus","path":"/Users/ktruon/.pub-cache/hosted/pub.dev/device_info_plus-9.0.3/","dependencies":[]}]},"dependencyGraph":[{"name":"device_info_plus","dependencies":[]},{"name":"path_provider","dependencies":["path_provider_android","path_provider_foundation","path_provider_linux","path_provider_windows"]},{"name":"path_provider_android","dependencies":[]},{"name":"path_provider_foundation","dependencies":[]},{"name":"path_provider_linux","dependencies":[]},{"name":"path_provider_windows","dependencies":[]}],"date_created":"2023-10-04 10:41:43.565295","version":"3.10.6"} \ No newline at end of file diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index b3bb43875d..d28c6e8cc0 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -98,8 +98,12 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin if (event.type == AuthHubEventType.signedOut || event.type == AuthHubEventType.userDeleted || event.type == AuthHubEventType.sessionExpired) { + _userId = null; await _clearLogs(); } + if (event.type == AuthHubEventType.signedIn) { + _userId = event.payload?.userId; + } }); } @@ -308,17 +312,6 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin final loggingConstraint = _getLoggingConstraint(); - Amplify.Hub.listen(HubChannel.Auth, (AuthHubEvent event) async { - if (event.type == AuthHubEventType.signedOut || - event.type == AuthHubEventType.userDeleted || - event.type == AuthHubEventType.sessionExpired) { - _userId = null; - } - if (event.type == AuthHubEventType.signedIn) { - _userId = event.payload?.userId; - } - }); - if (loggingConstraint.userLogLevel.containsKey(_userId)) { final userLevel = loggingConstraint.userLogLevel[_userId]!; From 84ed82ce88728c55526423fc91f932761d1d8bdd Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Wed, 4 Oct 2023 12:02:58 -0700 Subject: [PATCH 06/15] Update packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart Co-authored-by: NikaHsn --- .../lib/src/cloudwatch_logger_plugin.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index d28c6e8cc0..dd1aa13e7e 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -334,7 +334,7 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin LogEntry logEntry, ) { for (final entry in categoryLogLevel.entries) { - if (logEntry.loggerName.contains(entry.key)) { + if (logEntry.loggerName.toLowerCase().contains(entry.key.toLowerCase())) { return logEntry.level >= entry.value; } } From 9a0f64a34a0c5533c06b9f21ddfba801d097a25b Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Wed, 4 Oct 2023 12:12:47 -0700 Subject: [PATCH 07/15] chore: removed white spaces --- .../lib/src/cloudwatch_logger_plugin.dart | 5 ----- 1 file changed, 5 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index dd1aa13e7e..c26689191d 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -131,7 +131,6 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin }); } String? _userId; - final CloudWatchPluginConfig _pluginConfig; final CloudWatchLogsClient _client; final CloudWatchLogStreamProvider _logStreamProvider; @@ -314,18 +313,14 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin if (loggingConstraint.userLogLevel.containsKey(_userId)) { final userLevel = loggingConstraint.userLogLevel[_userId]!; - if (_checkLogLevel(userLevel.categoryLogLevel, logEntry)) { return true; } - return logEntry.level >= userLevel.defaultLogLevel; } - if (_checkLogLevel(loggingConstraint.categoryLogLevel, logEntry)) { return true; } - return logEntry.level >= loggingConstraint.defaultLogLevel; } From 33d524f32e5c39971276abb516611ddb956f7dc9 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Thu, 5 Oct 2023 11:04:00 -0700 Subject: [PATCH 08/15] chore: added tests, tests methods, and fixed a typ --- .../lib/src/cloudwatch_logger_plugin.dart | 30 ++- .../test/cloudwatch_logger_plugin_test.dart | 219 +++++++++++++++++- .../aws_logging_cloudwatch/test/mocks.dart | 5 +- 3 files changed, 251 insertions(+), 3 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index c26689191d..22293d1583 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -126,8 +126,12 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin if (event.type == AuthHubEventType.signedOut || event.type == AuthHubEventType.userDeleted || event.type == AuthHubEventType.sessionExpired) { + _userId = null; await _clearLogs(); } + if (event.type == AuthHubEventType.signedIn) { + _userId = event.payload?.userId; + } }); } String? _userId; @@ -318,8 +322,12 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin } return logEntry.level >= userLevel.defaultLogLevel; } - if (_checkLogLevel(loggingConstraint.categoryLogLevel, logEntry)) { + final isLoggableByCategory = + _checkLogLevel(loggingConstraint.categoryLogLevel, logEntry); + if (isLoggableByCategory) { return true; + } else if (loggingConstraint.categoryLogLevel.isNotEmpty) { + return false; } return logEntry.level >= loggingConstraint.defaultLogLevel; } @@ -336,6 +344,26 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin return false; } + /// Test the _isLoggable method. + @protected + @visibleForTesting + bool testIsLoggable(LogEntry logEntry) => _isLoggable(logEntry); + + /// Get user id for testing. + @protected + @visibleForTesting + String? get testUserId => _userId; + + /// Set user id for testing. + @protected + @visibleForTesting + set testUserId(String? userId) => _userId = userId; + + /// Get logging constraint for testing. + @protected + @visibleForTesting + LoggingConstraints get testLoggingConstraint => _getLoggingConstraint(); + @override Future handleLogEntry(LogEntry logEntry) async { if (!(_isLoggable(logEntry))) { diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart index 699053c57f..9592a97f0a 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart @@ -12,6 +12,22 @@ import 'package:test/test.dart'; import 'mocks.dart'; +class MockRemoteLoggingConstraintProvider + extends RemoteLoggingConstraintProvider { + @override + LoggingConstraints get loggingConstraint { + return const LoggingConstraints( + userLogLevel: { + 'user1': UserLogLevel( + defaultLogLevel: LogLevel.warn, + categoryLogLevel: {}, + ), + }, + // ... other properties ... + ); + } +} + void main() { late MockCloudWatchLogsClient mockCloudWatchLogsClient; late MockQueuedItemStore mockQueuedItemStore; @@ -798,7 +814,7 @@ void main() { plugin.handleLogEntry(errorLog), completes, ); - hubEventController.add(AuthHubEvent.signedIn(MockAuhtUser())); + hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); await Future.delayed(Duration.zero); verify( @@ -813,4 +829,205 @@ void main() { ); }); }); + + group('Test _isLoggable method', () { + final hubEventController = StreamController.broadcast(); + Amplify.Hub.addChannel(HubChannel.Auth, hubEventController.stream); + const pluginConfig = CloudWatchPluginConfig( + logGroupName: 'logGroupName', + region: 'region', + loggingConstraints: loggingConstraint, + enable: true, + ); + setUp(() { + mockCloudWatchLogsClient = MockCloudWatchLogsClient(); + mockQueuedItemStore = MockQueuedItemStore(); + mockCloudWatchLogStreamProvider = MockCloudWatchLogStreamProvider(); + plugin = CloudWatchLoggerPlugin.testPlugin( + client: mockCloudWatchLogsClient, + pluginConfig: pluginConfig, + logStore: mockQueuedItemStore, + logStreamProvider: mockCloudWatchLogStreamProvider, + ); + }); + tearDownAll(hubEventController.close); + + test('returns true for default level logs when no user level set', () { + final entry = LogEntry( + level: pluginConfig.loggingConstraints.defaultLogLevel, + loggerName: '', + message: '', + ); + expect(plugin.testIsLoggable(entry), isTrue); + }); + + test('returns true for user level logs when user level set', () { + final mockRemoteLoggingConstraintProvider = + MockRemoteLoggingConstraintProvider(); + + plugin = CloudWatchLoggerPlugin.testPlugin( + client: mockCloudWatchLogsClient, + pluginConfig: pluginConfig, + logStreamProvider: mockCloudWatchLogStreamProvider, + logStore: mockQueuedItemStore, + remoteLoggingConstraintProvider: mockRemoteLoggingConstraintProvider, + )..testUserId = 'user1'; + + final entry = + LogEntry(level: LogLevel.warn, loggerName: 'logger', message: ''); + + expect(plugin.testIsLoggable(entry), isTrue); + }); + + test('returns false when log level is below default level', () { + final entry = LogEntry( + level: LogLevel.debug, + loggerName: '', + message: '', + ); + + expect(plugin.testIsLoggable(entry), isFalse); + }); + + test('returns true when log level is above default level', () { + final entry = LogEntry( + level: LogLevel.error, + loggerName: '', + message: '', + ); + + expect(plugin.testIsLoggable(entry), isTrue); + }); + + test( + 'returns true when category log level is set and log level is above category level', + () { + const loggingConstraint = LoggingConstraints( + defaultLogLevel: LogLevel.info, + categoryLogLevel: {'logger': LogLevel.warn}, + ); + + const categoryLogLevelPluginConfig = CloudWatchPluginConfig( + logGroupName: 'logGroupName', + region: 'region', + loggingConstraints: loggingConstraint, + enable: true, + ); + + plugin = CloudWatchLoggerPlugin.testPlugin( + client: mockCloudWatchLogsClient, + pluginConfig: categoryLogLevelPluginConfig, + logStreamProvider: mockCloudWatchLogStreamProvider, + logStore: mockQueuedItemStore, + ); + + final entry = LogEntry( + level: LogLevel.error, + loggerName: 'logger', + message: '', + ); + + expect(plugin.testIsLoggable(entry), isTrue); + }); + + test( + 'returns false when category log level is set and log level is below category level', + () { + const loggingConstraint = LoggingConstraints( + defaultLogLevel: LogLevel.info, + categoryLogLevel: {'logger': LogLevel.error}, + ); + + const categoryLogLevelPluginConfig = CloudWatchPluginConfig( + logGroupName: 'logGroupName', + region: 'region', + loggingConstraints: loggingConstraint, + enable: true, + ); + + plugin = CloudWatchLoggerPlugin.testPlugin( + client: mockCloudWatchLogsClient, + pluginConfig: categoryLogLevelPluginConfig, + logStreamProvider: mockCloudWatchLogStreamProvider, + logStore: mockQueuedItemStore, + ); + + final entry = LogEntry( + level: LogLevel.info, + loggerName: 'logger', + message: '', + ); + + expect(plugin.testIsLoggable(entry), isFalse); + }); + }); + + group('Test _userId method', () { + final hubEventController = StreamController.broadcast(); + final events = [ + AuthHubEvent.sessionExpired(), + AuthHubEvent.signedOut(), + AuthHubEvent.userDeleted(), + AuthHubEvent.signedIn(MockAuthUser()), + ]; + Amplify.Hub.addChannel(HubChannel.Auth, hubEventController.stream); + const pluginConfig = CloudWatchPluginConfig( + logGroupName: 'logGroupName', + region: 'region', + loggingConstraints: loggingConstraint, + enable: true, + ); + setUp(() { + mockCloudWatchLogsClient = MockCloudWatchLogsClient(); + mockQueuedItemStore = MockQueuedItemStore(); + mockCloudWatchLogStreamProvider = MockCloudWatchLogStreamProvider(); + plugin = CloudWatchLoggerPlugin.testPlugin( + client: mockCloudWatchLogsClient, + pluginConfig: pluginConfig, + logStore: mockQueuedItemStore, + logStreamProvider: mockCloudWatchLogStreamProvider, + ); + }); + tearDownAll(hubEventController.close); + + test('sets _userId to null on sign out', () async { + final event = events[1]; + hubEventController.add(event); + + // Allow event to propagate + await Future.delayed(Duration.zero); + + expect(plugin.testUserId, isNull); + }); + + test('sets _userId to null on session expired', () async { + final event = events[0]; + hubEventController.add(event); + + // Allow event to propagate + await Future.delayed(Duration.zero); + + expect(plugin.testUserId, isNull); + }); + + test('sets _userId to null on user deleted', () async { + final event = events[2]; + hubEventController.add(event); + + // Allow event to propagate + await Future.delayed(Duration.zero); + + expect(plugin.testUserId, isNull); + }); + + test('sets _userId on signed in', () async { + final event = events[3]; + hubEventController.add(event); + + // Allow event to propagate + await Future.delayed(Duration.zero); + + expect(plugin.testUserId, equals(event.payload?.userId)); + }); + }); } diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart index bdf6fba1e7..dbdd69c5b0 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart @@ -18,4 +18,7 @@ class MockCloudWatchLogStreamProvider extends Mock class MockRemoteLoggingConstraintProvider extends Mock implements RemoteLoggingConstraintProvider {} -class MockAuhtUser extends Mock implements AuthUser {} +class MockAuthUser extends Mock implements AuthUser { + @override + String get userId => 'mockUserId'; +} From 0921f149c9fbb371ec4fc2f1607206bf5b31d572 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Thu, 5 Oct 2023 12:45:43 -0700 Subject: [PATCH 09/15] Update packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart Co-authored-by: NikaHsn --- .../lib/src/cloudwatch_logger_plugin.dart | 31 +++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index 22293d1583..c111677685 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -314,36 +314,35 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin } final loggingConstraint = _getLoggingConstraint(); - - if (loggingConstraint.userLogLevel.containsKey(_userId)) { - final userLevel = loggingConstraint.userLogLevel[_userId]!; - if (_checkLogLevel(userLevel.categoryLogLevel, logEntry)) { - return true; +if (loggingConstraint.userLogLevel.containsKey(_userId)) { + final userLogLevel = loggingConstraint.userLogLevel[_userId]!; + final userCategoryLogLevel = + _getCategoryLogLevel(userLogLevel.categoryLogLevel, logEntry); + if (userCategoryLogLevel != null) { + return logEntry.level >= userCategoryLogLevel; } - return logEntry.level >= userLevel.defaultLogLevel; + return logEntry.level >= userLogLevel.defaultLogLevel; } - final isLoggableByCategory = - _checkLogLevel(loggingConstraint.categoryLogLevel, logEntry); - if (isLoggableByCategory) { - return true; - } else if (loggingConstraint.categoryLogLevel.isNotEmpty) { - return false; + + final categoryLogLevel = + _getCategoryLogLevel(loggingConstraint.categoryLogLevel, logEntry); + if (categoryLogLevel != null) { + return logEntry.level >= categoryLogLevel; } return logEntry.level >= loggingConstraint.defaultLogLevel; } - bool _checkLogLevel( + LogLevel? _getCategoryLogLevel( Map categoryLogLevel, LogEntry logEntry, ) { for (final entry in categoryLogLevel.entries) { if (logEntry.loggerName.toLowerCase().contains(entry.key.toLowerCase())) { - return logEntry.level >= entry.value; + return entry.value; } } - return false; + return null; } - /// Test the _isLoggable method. @protected @visibleForTesting From 3954b4f7e150f2a18005fa2da0d497251f28f1fd Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Thu, 5 Oct 2023 17:03:59 -0700 Subject: [PATCH 10/15] chore: removed testing methods and adjusted tests --- .../lib/src/cloudwatch_logger_plugin.dart | 21 +- .../test/cloudwatch_logger_plugin_test.dart | 203 +++++++----------- 2 files changed, 80 insertions(+), 144 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index c111677685..1945ffebd8 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -314,7 +314,7 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin } final loggingConstraint = _getLoggingConstraint(); -if (loggingConstraint.userLogLevel.containsKey(_userId)) { + if (loggingConstraint.userLogLevel.containsKey(_userId)) { final userLogLevel = loggingConstraint.userLogLevel[_userId]!; final userCategoryLogLevel = _getCategoryLogLevel(userLogLevel.categoryLogLevel, logEntry); @@ -343,25 +343,6 @@ if (loggingConstraint.userLogLevel.containsKey(_userId)) { } return null; } - /// Test the _isLoggable method. - @protected - @visibleForTesting - bool testIsLoggable(LogEntry logEntry) => _isLoggable(logEntry); - - /// Get user id for testing. - @protected - @visibleForTesting - String? get testUserId => _userId; - - /// Set user id for testing. - @protected - @visibleForTesting - set testUserId(String? userId) => _userId = userId; - - /// Get logging constraint for testing. - @protected - @visibleForTesting - LoggingConstraints get testLoggingConstraint => _getLoggingConstraint(); @override Future handleLogEntry(LogEntry logEntry) async { diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart index 9592a97f0a..39d810e069 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart @@ -833,10 +833,17 @@ void main() { group('Test _isLoggable method', () { final hubEventController = StreamController.broadcast(); Amplify.Hub.addChannel(HubChannel.Auth, hubEventController.stream); + const loggingConstraints2 = LoggingConstraints( + categoryLogLevel: { + 'Amplify': LogLevel.debug, + 'Auth': LogLevel.warn, + }, + defaultLogLevel: LogLevel.warn, + ); const pluginConfig = CloudWatchPluginConfig( logGroupName: 'logGroupName', region: 'region', - loggingConstraints: loggingConstraint, + loggingConstraints: loggingConstraints2, enable: true, ); setUp(() { @@ -849,185 +856,133 @@ void main() { logStore: mockQueuedItemStore, logStreamProvider: mockCloudWatchLogStreamProvider, ); + + when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); }); tearDownAll(hubEventController.close); - test('returns true for default level logs when no user level set', () { + test('logs when log level meets default constraint', () async { final entry = LogEntry( - level: pluginConfig.loggingConstraints.defaultLogLevel, + level: LogLevel.error, loggerName: '', message: '', ); - expect(plugin.testIsLoggable(entry), isTrue); - }); - - test('returns true for user level logs when user level set', () { - final mockRemoteLoggingConstraintProvider = - MockRemoteLoggingConstraintProvider(); - - plugin = CloudWatchLoggerPlugin.testPlugin( - client: mockCloudWatchLogsClient, - pluginConfig: pluginConfig, - logStreamProvider: mockCloudWatchLogStreamProvider, - logStore: mockQueuedItemStore, - remoteLoggingConstraintProvider: mockRemoteLoggingConstraintProvider, - )..testUserId = 'user1'; - final entry = - LogEntry(level: LogLevel.warn, loggerName: 'logger', message: ''); - - expect(plugin.testIsLoggable(entry), isTrue); + await plugin.handleLogEntry(entry); + verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); }); - test('returns false when log level is below default level', () { + test('does not log when log level is below default constraint', () async { final entry = LogEntry( level: LogLevel.debug, loggerName: '', message: '', ); - expect(plugin.testIsLoggable(entry), isFalse); + await plugin.handleLogEntry(entry); + verifyNever(() => mockQueuedItemStore.addItem(any(), any())); }); - test('returns true when log level is above default level', () { + test('logs when log level meets category override', () async { final entry = LogEntry( - level: LogLevel.error, - loggerName: '', + level: LogLevel.debug, + loggerName: 'Amplify', message: '', ); - expect(plugin.testIsLoggable(entry), isTrue); + await plugin.handleLogEntry(entry); + verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); }); - test( - 'returns true when category log level is set and log level is above category level', - () { - const loggingConstraint = LoggingConstraints( - defaultLogLevel: LogLevel.info, - categoryLogLevel: {'logger': LogLevel.warn}, - ); - - const categoryLogLevelPluginConfig = CloudWatchPluginConfig( - logGroupName: 'logGroupName', - region: 'region', - loggingConstraints: loggingConstraint, - enable: true, - ); - - plugin = CloudWatchLoggerPlugin.testPlugin( - client: mockCloudWatchLogsClient, - pluginConfig: categoryLogLevelPluginConfig, - logStreamProvider: mockCloudWatchLogStreamProvider, - logStore: mockQueuedItemStore, - ); - + test('does not log when category override blocks log', () async { final entry = LogEntry( - level: LogLevel.error, - loggerName: 'logger', + level: LogLevel.info, + loggerName: 'Auth', message: '', ); - expect(plugin.testIsLoggable(entry), isTrue); + await plugin.handleLogEntry(entry); + verifyNever(() => mockQueuedItemStore.addItem(any(), any())); }); - test( - 'returns false when category log level is set and log level is below category level', - () { - const loggingConstraint = LoggingConstraints( - defaultLogLevel: LogLevel.info, - categoryLogLevel: {'logger': LogLevel.error}, + test('applies userLogLevel filter', () { + const loggingConstraints3 = LoggingConstraints( + userLogLevel: { + 'mockUserId': UserLogLevel( + defaultLogLevel: LogLevel.warn, + categoryLogLevel: {}, + ), + }, ); - - const categoryLogLevelPluginConfig = CloudWatchPluginConfig( + const config2 = CloudWatchPluginConfig( logGroupName: 'logGroupName', region: 'region', - loggingConstraints: loggingConstraint, + loggingConstraints: loggingConstraints3, enable: true, ); + hubEventController.add( + AuthHubEvent.signedIn( + MockAuthUser(), + ), + ); + plugin = CloudWatchLoggerPlugin.testPlugin( client: mockCloudWatchLogsClient, - pluginConfig: categoryLogLevelPluginConfig, - logStreamProvider: mockCloudWatchLogStreamProvider, + pluginConfig: config2, logStore: mockQueuedItemStore, + logStreamProvider: mockCloudWatchLogStreamProvider, ); + final entry = LogEntry(level: LogLevel.info, loggerName: '', message: ''); + plugin.handleLogEntry(entry); + verifyNever(() => mockQueuedItemStore.addItem(any(), any())); + }); + + test('logs at default level', () async { final entry = LogEntry( - level: LogLevel.info, - loggerName: 'logger', + level: LogLevel.warn, message: '', + loggerName: '', ); - expect(plugin.testIsLoggable(entry), isFalse); + await plugin.handleLogEntry(entry); + verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); }); - }); - group('Test _userId method', () { - final hubEventController = StreamController.broadcast(); - final events = [ - AuthHubEvent.sessionExpired(), - AuthHubEvent.signedOut(), - AuthHubEvent.userDeleted(), - AuthHubEvent.signedIn(MockAuthUser()), - ]; - Amplify.Hub.addChannel(HubChannel.Auth, hubEventController.stream); - const pluginConfig = CloudWatchPluginConfig( - logGroupName: 'logGroupName', - region: 'region', - loggingConstraints: loggingConstraint, - enable: true, - ); - setUp(() { - mockCloudWatchLogsClient = MockCloudWatchLogsClient(); - mockQueuedItemStore = MockQueuedItemStore(); - mockCloudWatchLogStreamProvider = MockCloudWatchLogStreamProvider(); + test('does not log below default level', () async { + final entry = + LogEntry(level: LogLevel.debug, message: '', loggerName: ''); + + await plugin.handleLogEntry(entry); + verifyNever(() => mockQueuedItemStore.addItem(any(), any())); + }); + + test('logs at category override level', () async { + const pluginConfig = CloudWatchPluginConfig( + loggingConstraints: LoggingConstraints( + categoryLogLevel: {'Amplify': LogLevel.debug}, + ), + region: 'region', + logGroupName: 'logGroupName', + ); + plugin = CloudWatchLoggerPlugin.testPlugin( client: mockCloudWatchLogsClient, pluginConfig: pluginConfig, logStore: mockQueuedItemStore, logStreamProvider: mockCloudWatchLogStreamProvider, ); - }); - tearDownAll(hubEventController.close); - - test('sets _userId to null on sign out', () async { - final event = events[1]; - hubEventController.add(event); - - // Allow event to propagate - await Future.delayed(Duration.zero); - expect(plugin.testUserId, isNull); - }); - - test('sets _userId to null on session expired', () async { - final event = events[0]; - hubEventController.add(event); - - // Allow event to propagate - await Future.delayed(Duration.zero); - - expect(plugin.testUserId, isNull); - }); - - test('sets _userId to null on user deleted', () async { - final event = events[2]; - hubEventController.add(event); - - // Allow event to propagate - await Future.delayed(Duration.zero); - - expect(plugin.testUserId, isNull); - }); - - test('sets _userId on signed in', () async { - final event = events[3]; - hubEventController.add(event); + final entry = LogEntry( + level: LogLevel.debug, + loggerName: 'Amplify', + message: '', + ); - // Allow event to propagate - await Future.delayed(Duration.zero); + await plugin.handleLogEntry(entry); - expect(plugin.testUserId, equals(event.payload?.userId)); + verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); }); }); } From 572fd3bbcfa7620b561752550eb60d3bc37736f2 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Mon, 9 Oct 2023 09:39:07 -0700 Subject: [PATCH 11/15] chore: WIP - changed tests for handleLogEntry --- .../test/cloudwatch_logger_plugin_test.dart | 360 +++++++++++------- .../aws_logging_cloudwatch/test/mocks.dart | 8 +- 2 files changed, 233 insertions(+), 135 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart index 39d810e069..e52320cd9c 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart @@ -35,7 +35,29 @@ void main() { late CloudWatchLoggerPlugin plugin; late MockSmithyOperation mockPutLogEventsOperation; - const loggingConstraint = LoggingConstraints(); + const loggingConstraint = LoggingConstraints( + defaultLogLevel: LogLevel.error, + categoryLogLevel: { + 'Auth': LogLevel.warn, + 'DataStore': LogLevel.debug, + }, + userLogLevel: { + 'mockUserId': UserLogLevel( + defaultLogLevel: LogLevel.warn, + categoryLogLevel: { + 'Auth': LogLevel.debug, + 'DataStore': LogLevel.info, + }, + ), + 'userId': UserLogLevel( + defaultLogLevel: LogLevel.error, + categoryLogLevel: { + 'Auth': LogLevel.info, + 'DataStore': LogLevel.warn, + }, + ) + }, + ); const pluginConfig = CloudWatchPluginConfig( logGroupName: 'logGroupName', region: 'region', @@ -54,6 +76,48 @@ void main() { loggerName: 'loggerName', ); + final infoLog = LogEntry( + level: LogLevel.info, + message: 'info message', + loggerName: 'loggerName', + ); + + final datastoreDebugLog = LogEntry( + level: LogLevel.debug, + message: 'debug message', + loggerName: 'DataStore', + ); + + final datastoreInfoLog = LogEntry( + level: LogLevel.verbose, + message: 'info message', + loggerName: 'DataStore', + ); + + final authWarnLog = LogEntry( + level: LogLevel.warn, + message: 'debug message', + loggerName: 'Auth', + ); + + final authDebugLog = LogEntry( + level: LogLevel.debug, + message: 'debug message', + loggerName: 'Auth', + ); + + final authInfoLog = LogEntry( + level: LogLevel.info, + message: 'info message', + loggerName: 'Auth', + ); + + final authVerboseLog = LogEntry( + level: LogLevel.verbose, + message: 'verbose message', + loggerName: 'Auth', + ); + final queuedItems = [ QueuedItem( id: 1, @@ -122,7 +186,73 @@ void main() { ).called(1); }); - test('when enabled,logs are not added to the log store if not loggable', + test('Category logs are added to the item store when loggable', () async { + when( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, + ), + ).thenAnswer((_) async => {}); + + when(() => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB)) + .thenReturn(false); + + plugin.enable(); + + await expectLater( + plugin.handleLogEntry(authWarnLog), + completes, + ); + + verify( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, + ), + ).called(1); + + verify( + () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), + ).called(1); + }); + + test( + 'Category logs are added to the item store when loggable even when below default log level', + () async { + when( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, + ), + ).thenAnswer((_) async => {}); + + when(() => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB)) + .thenReturn(false); + + plugin.enable(); + + await expectLater( + plugin.handleLogEntry(datastoreDebugLog), + completes, + ); + + verify( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, + ), + ).called(1); + + verify( + () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), + ).called(1); + }); + + test('when enabled, logs are not added to the log store if not loggable', () async { plugin.enable(); await expectLater( @@ -132,6 +262,29 @@ void main() { verifyZeroInteractions(mockQueuedItemStore); }); + test( + 'when enabled, category logs are not added to the log store if not loggable', + () async { + plugin.enable(); + await expectLater( + plugin.handleLogEntry(authDebugLog), + completes, + ); + verifyZeroInteractions(mockQueuedItemStore); + }); + + test( + 'when enabled, category logs are not added to the log store if not loggable below category log level', + () async { + plugin.enable(); + when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); + await expectLater( + plugin.handleLogEntry(datastoreInfoLog), + completes, + ); + verifyZeroInteractions(mockQueuedItemStore); + }); + test( 'when disabled, logs are cleared from item store and new logs will not' ' be added to the local store', () async { @@ -828,161 +981,100 @@ void main() { () => mockQueuedItemStore.clear(), ); }); - }); - group('Test _isLoggable method', () { - final hubEventController = StreamController.broadcast(); - Amplify.Hub.addChannel(HubChannel.Auth, hubEventController.stream); - const loggingConstraints2 = LoggingConstraints( - categoryLogLevel: { - 'Amplify': LogLevel.debug, - 'Auth': LogLevel.warn, - }, - defaultLogLevel: LogLevel.warn, - ); - const pluginConfig = CloudWatchPluginConfig( - logGroupName: 'logGroupName', - region: 'region', - loggingConstraints: loggingConstraints2, - enable: true, - ); - setUp(() { - mockCloudWatchLogsClient = MockCloudWatchLogsClient(); - mockQueuedItemStore = MockQueuedItemStore(); - mockCloudWatchLogStreamProvider = MockCloudWatchLogStreamProvider(); - plugin = CloudWatchLoggerPlugin.testPlugin( - client: mockCloudWatchLogsClient, - pluginConfig: pluginConfig, - logStore: mockQueuedItemStore, - logStreamProvider: mockCloudWatchLogStreamProvider, - ); + test('logs are added to the log store when above user log level', () async { + when( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, + ), + ).thenAnswer((_) async => {}); - when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); - }); - tearDownAll(hubEventController.close); + when(() => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB)) + .thenReturn(false); - test('logs when log level meets default constraint', () async { - final entry = LogEntry( - level: LogLevel.error, - loggerName: '', - message: '', - ); + plugin.enable(); - await plugin.handleLogEntry(entry); - verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); - }); + hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); - test('does not log when log level is below default constraint', () async { - final entry = LogEntry( - level: LogLevel.debug, - loggerName: '', - message: '', + await expectLater( + plugin.handleLogEntry(authInfoLog), + completes, ); - await plugin.handleLogEntry(entry); - verifyNever(() => mockQueuedItemStore.addItem(any(), any())); - }); - - test('logs when log level meets category override', () async { - final entry = LogEntry( - level: LogLevel.debug, - loggerName: 'Amplify', - message: '', - ); + verify( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, + ), + ).called(1); - await plugin.handleLogEntry(entry); - verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); + verify( + () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), + ).called(1); }); - test('does not log when category override blocks log', () async { - final entry = LogEntry( - level: LogLevel.info, - loggerName: 'Auth', - message: '', + test( + 'Category level logs are not logged if not loggable with user level logs', + () async { + plugin.enable(); + hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); + when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); + await expectLater( + plugin.handleLogEntry(authVerboseLog), + completes, ); - - await plugin.handleLogEntry(entry); - verifyNever(() => mockQueuedItemStore.addItem(any(), any())); + verifyZeroInteractions(mockQueuedItemStore); }); - test('applies userLogLevel filter', () { - const loggingConstraints3 = LoggingConstraints( - userLogLevel: { - 'mockUserId': UserLogLevel( - defaultLogLevel: LogLevel.warn, - categoryLogLevel: {}, - ), - }, - ); - const config2 = CloudWatchPluginConfig( - logGroupName: 'logGroupName', - region: 'region', - loggingConstraints: loggingConstraints3, - enable: true, - ); - - hubEventController.add( - AuthHubEvent.signedIn( - MockAuthUser(), + test( + 'logs are added to the log store if above user default level with no category log set', + () async { + when( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, ), - ); - - plugin = CloudWatchLoggerPlugin.testPlugin( - client: mockCloudWatchLogsClient, - pluginConfig: config2, - logStore: mockQueuedItemStore, - logStreamProvider: mockCloudWatchLogStreamProvider, - ); - - final entry = LogEntry(level: LogLevel.info, loggerName: '', message: ''); - plugin.handleLogEntry(entry); - verifyNever(() => mockQueuedItemStore.addItem(any(), any())); - }); + ).thenAnswer((_) async => {}); - test('logs at default level', () async { - final entry = LogEntry( - level: LogLevel.warn, - message: '', - loggerName: '', - ); + when(() => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB)) + .thenReturn(false); - await plugin.handleLogEntry(entry); - verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); - }); + plugin.enable(); - test('does not log below default level', () async { - final entry = - LogEntry(level: LogLevel.debug, message: '', loggerName: ''); + hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); - await plugin.handleLogEntry(entry); - verifyNever(() => mockQueuedItemStore.addItem(any(), any())); - }); + await expectLater( + plugin.handleLogEntry(warnLog), + completes, + ); - test('logs at category override level', () async { - const pluginConfig = CloudWatchPluginConfig( - loggingConstraints: LoggingConstraints( - categoryLogLevel: {'Amplify': LogLevel.debug}, + verify( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, ), - region: 'region', - logGroupName: 'logGroupName', - ); + ).called(1); - plugin = CloudWatchLoggerPlugin.testPlugin( - client: mockCloudWatchLogsClient, - pluginConfig: pluginConfig, - logStore: mockQueuedItemStore, - logStreamProvider: mockCloudWatchLogStreamProvider, - ); + verify( + () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), + ).called(1); + }); - final entry = LogEntry( - level: LogLevel.debug, - loggerName: 'Amplify', - message: '', + test('Logs are not logged if not loggable with user default level', + () async { + plugin.enable(); + hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); + when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); + await expectLater( + plugin.handleLogEntry(infoLog), + completes, ); - - await plugin.handleLogEntry(entry); - - verify(() => mockQueuedItemStore.addItem(any(), any())).called(1); + verifyZeroInteractions(mockQueuedItemStore); }); }); } diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart index dbdd69c5b0..f8a64bd8e4 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart @@ -20,5 +20,11 @@ class MockRemoteLoggingConstraintProvider extends Mock class MockAuthUser extends Mock implements AuthUser { @override - String get userId => 'mockUserId'; + final String userId = 'mockUserId'; + + @override + final String username = 'mockUser'; + + @override + final String _userId = 'mockUserId'; } From fda880980f93a27263e30646eda1df39f93e0667 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Mon, 9 Oct 2023 11:47:37 -0700 Subject: [PATCH 12/15] chore: added future.delay(0) to tests --- .../test/cloudwatch_logger_plugin_test.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart index e52320cd9c..f3d87fb1f4 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart @@ -997,6 +997,7 @@ void main() { plugin.enable(); hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); + await Future.delayed(Duration.zero); await expectLater( plugin.handleLogEntry(authInfoLog), @@ -1046,6 +1047,7 @@ void main() { plugin.enable(); hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); + await Future.delayed(Duration.zero); await expectLater( plugin.handleLogEntry(warnLog), From 8adbc333cd2d4e3c33b88f8777ce62121086c18c Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Mon, 9 Oct 2023 12:22:17 -0700 Subject: [PATCH 13/15] chore: updated remote_constraint_provider_test --- .../test/remote_constraint_provider_test.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/remote_constraint_provider_test.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/remote_constraint_provider_test.dart index 38ed51af6d..003679c272 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/remote_constraint_provider_test.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/remote_constraint_provider_test.dart @@ -140,8 +140,8 @@ void main() { "cognito-sub-xyz-123": { "defaultLogLevel": "VERBOSE", "categoryLogLevel": { - "API": "error", - "AUTH": "debug" + "API": "ERROR", + "AUTH": "DEBUG" } } } From 10a4d8d8fe6c0e763a6d5c8f3ee7288b2a89b90b Mon Sep 17 00:00:00 2001 From: Nika Hassani Date: Mon, 9 Oct 2023 12:43:33 -0700 Subject: [PATCH 14/15] updated the tests --- .../test/cloudwatch_logger_plugin_test.dart | 223 ++++++------------ .../aws_logging_cloudwatch/test/mocks.dart | 3 - 2 files changed, 68 insertions(+), 158 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart index f3d87fb1f4..aeaa155959 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/cloudwatch_logger_plugin_test.dart @@ -12,22 +12,6 @@ import 'package:test/test.dart'; import 'mocks.dart'; -class MockRemoteLoggingConstraintProvider - extends RemoteLoggingConstraintProvider { - @override - LoggingConstraints get loggingConstraint { - return const LoggingConstraints( - userLogLevel: { - 'user1': UserLogLevel( - defaultLogLevel: LogLevel.warn, - categoryLogLevel: {}, - ), - }, - // ... other properties ... - ); - } -} - void main() { late MockCloudWatchLogsClient mockCloudWatchLogsClient; late MockQueuedItemStore mockQueuedItemStore; @@ -55,7 +39,7 @@ void main() { 'Auth': LogLevel.info, 'DataStore': LogLevel.warn, }, - ) + ), }, ); const pluginConfig = CloudWatchPluginConfig( @@ -89,8 +73,8 @@ void main() { ); final datastoreInfoLog = LogEntry( - level: LogLevel.verbose, - message: 'info message', + level: LogLevel.info, + message: 'debug message', loggerName: 'DataStore', ); @@ -142,6 +126,9 @@ void main() { ]; group('enable/disable: ', () { + final hubEventController = StreamController.broadcast(); + Amplify.Hub.addChannel(HubChannel.Auth, hubEventController.stream); + setUp(() { mockCloudWatchLogsClient = MockCloudWatchLogsClient(); mockQueuedItemStore = MockQueuedItemStore(); @@ -154,7 +141,11 @@ void main() { ); }); - test('when enabled, logs are added to the item store', () async { + tearDownAll(hubEventController.close); + + test( + 'when enabled, logs are added to the item store ' + 'if loggable at default log level', () async { when( () => mockQueuedItemStore.addItem( any(), @@ -167,11 +158,15 @@ void main() { .thenReturn(false); plugin.enable(); - await expectLater( plugin.handleLogEntry(errorLog), completes, ); + // should not log this because it is below default log level. + await expectLater( + plugin.handleLogEntry(warnLog), + completes, + ); verify( () => mockQueuedItemStore.addItem( @@ -180,13 +175,14 @@ void main() { enableQueueRotation: false, ), ).called(1); - verify( () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), ).called(1); }); - test('Category logs are added to the item store when loggable', () async { + test( + 'when enabled, logs are added to the item store ' + 'if loggable at category log level', () async { when( () => mockQueuedItemStore.addItem( any(), @@ -199,11 +195,19 @@ void main() { .thenReturn(false); plugin.enable(); - await expectLater( plugin.handleLogEntry(authWarnLog), completes, ); + await expectLater( + plugin.handleLogEntry(datastoreDebugLog), + completes, + ); + // should not log this because it is below auth category log level. + await expectLater( + plugin.handleLogEntry(authInfoLog), + completes, + ); verify( () => mockQueuedItemStore.addItem( @@ -211,16 +215,15 @@ void main() { any(), enableQueueRotation: false, ), - ).called(1); - + ).called(2); verify( () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), - ).called(1); + ).called(2); }); test( - 'Category logs are added to the item store when loggable even when below default log level', - () async { + 'when enabled, logs are added to the log store if' + ' loggable at user log level', () async { when( () => mockQueuedItemStore.addItem( any(), @@ -233,9 +236,29 @@ void main() { .thenReturn(false); plugin.enable(); + hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); + await Future.delayed(Duration.zero); await expectLater( - plugin.handleLogEntry(datastoreDebugLog), + plugin.handleLogEntry(authWarnLog), + completes, + ); + await expectLater( + plugin.handleLogEntry(datastoreInfoLog), + completes, + ); + await expectLater( + plugin.handleLogEntry(warnLog), + completes, + ); + + // should not log these because they are below user log level. + await expectLater( + plugin.handleLogEntry(authVerboseLog), + completes, + ); + await expectLater( + plugin.handleLogEntry(infoLog), completes, ); @@ -245,44 +268,30 @@ void main() { any(), enableQueueRotation: false, ), - ).called(1); - + ).called(3); verify( () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), - ).called(1); - }); + ).called(3); - test('when enabled, logs are not added to the log store if not loggable', - () async { - plugin.enable(); - await expectLater( - plugin.handleLogEntry(warnLog), - completes, - ); - verifyZeroInteractions(mockQueuedItemStore); - }); + hubEventController.add(AuthHubEvent.signedOut()); + await Future.delayed(Duration.zero); - test( - 'when enabled, category logs are not added to the log store if not loggable', - () async { - plugin.enable(); + // should not log this because it is below auth category log level. await expectLater( plugin.handleLogEntry(authDebugLog), completes, ); - verifyZeroInteractions(mockQueuedItemStore); - }); - test( - 'when enabled, category logs are not added to the log store if not loggable below category log level', - () async { - plugin.enable(); - when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); - await expectLater( - plugin.handleLogEntry(datastoreInfoLog), - completes, + verifyNever( + () => mockQueuedItemStore.addItem( + any(), + any(), + enableQueueRotation: false, + ), + ); + verifyNever( + () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), ); - verifyZeroInteractions(mockQueuedItemStore); }); test( @@ -901,6 +910,7 @@ void main() { AuthHubEvent.signedOut, AuthHubEvent.userDeleted, ]; + Amplify.Hub.addChannel(HubChannel.Auth, hubEventController.stream); setUp(() { mockCloudWatchLogsClient = MockCloudWatchLogsClient(); @@ -981,102 +991,5 @@ void main() { () => mockQueuedItemStore.clear(), ); }); - - test('logs are added to the log store when above user log level', () async { - when( - () => mockQueuedItemStore.addItem( - any(), - any(), - enableQueueRotation: false, - ), - ).thenAnswer((_) async => {}); - - when(() => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB)) - .thenReturn(false); - - plugin.enable(); - - hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); - await Future.delayed(Duration.zero); - - await expectLater( - plugin.handleLogEntry(authInfoLog), - completes, - ); - - verify( - () => mockQueuedItemStore.addItem( - any(), - any(), - enableQueueRotation: false, - ), - ).called(1); - - verify( - () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), - ).called(1); - }); - - test( - 'Category level logs are not logged if not loggable with user level logs', - () async { - plugin.enable(); - hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); - when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); - await expectLater( - plugin.handleLogEntry(authVerboseLog), - completes, - ); - verifyZeroInteractions(mockQueuedItemStore); - }); - - test( - 'logs are added to the log store if above user default level with no category log set', - () async { - when( - () => mockQueuedItemStore.addItem( - any(), - any(), - enableQueueRotation: false, - ), - ).thenAnswer((_) async => {}); - - when(() => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB)) - .thenReturn(false); - - plugin.enable(); - - hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); - await Future.delayed(Duration.zero); - - await expectLater( - plugin.handleLogEntry(warnLog), - completes, - ); - - verify( - () => mockQueuedItemStore.addItem( - any(), - any(), - enableQueueRotation: false, - ), - ).called(1); - - verify( - () => mockQueuedItemStore.isFull(pluginConfig.localStoreMaxSizeInMB), - ).called(1); - }); - - test('Logs are not logged if not loggable with user default level', - () async { - plugin.enable(); - hubEventController.add(AuthHubEvent.signedIn(MockAuthUser())); - when(() => mockQueuedItemStore.isFull(any())).thenReturn(false); - await expectLater( - plugin.handleLogEntry(infoLog), - completes, - ); - verifyZeroInteractions(mockQueuedItemStore); - }); }); } diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart index f8a64bd8e4..b9832bfd26 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/test/mocks.dart @@ -24,7 +24,4 @@ class MockAuthUser extends Mock implements AuthUser { @override final String username = 'mockUser'; - - @override - final String _userId = 'mockUserId'; } From fdcdfde25ca7ea88d17fc8a3cc3a8fa40e007233 Mon Sep 17 00:00:00 2001 From: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Date: Mon, 9 Oct 2023 13:42:34 -0700 Subject: [PATCH 15/15] chore: flattened if statement --- .../lib/src/cloudwatch_logger_plugin.dart | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart index 1945ffebd8..4c02a1cdbb 100644 --- a/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart +++ b/packages/logging_cloudwatch/aws_logging_cloudwatch/lib/src/cloudwatch_logger_plugin.dart @@ -309,27 +309,23 @@ class CloudWatchLoggerPlugin extends AWSLoggerPlugin /// Whether a [logEntry] should be logged by this plugin. bool _isLoggable(LogEntry logEntry) { - if (!_enabled) { - return false; - } + if (!_enabled) return false; final loggingConstraint = _getLoggingConstraint(); - if (loggingConstraint.userLogLevel.containsKey(_userId)) { + final hasUserLogLevel = loggingConstraint.userLogLevel.containsKey(_userId); + LogLevel? logLevel; + + if (hasUserLogLevel) { final userLogLevel = loggingConstraint.userLogLevel[_userId]!; - final userCategoryLogLevel = - _getCategoryLogLevel(userLogLevel.categoryLogLevel, logEntry); - if (userCategoryLogLevel != null) { - return logEntry.level >= userCategoryLogLevel; - } - return logEntry.level >= userLogLevel.defaultLogLevel; + logLevel = + _getCategoryLogLevel(userLogLevel.categoryLogLevel, logEntry) ?? + userLogLevel.defaultLogLevel; + } else { + logLevel = + _getCategoryLogLevel(loggingConstraint.categoryLogLevel, logEntry); } - final categoryLogLevel = - _getCategoryLogLevel(loggingConstraint.categoryLogLevel, logEntry); - if (categoryLogLevel != null) { - return logEntry.level >= categoryLogLevel; - } - return logEntry.level >= loggingConstraint.defaultLogLevel; + return logEntry.level >= (logLevel ?? loggingConstraint.defaultLogLevel); } LogLevel? _getCategoryLogLevel(