From 9c635c7dca097c0b4c355289b2e12bdaa5a8a8fd Mon Sep 17 00:00:00 2001 From: Travis Sharp <94011425+msft-tsharp@users.noreply.github.com> Date: Fri, 21 Mar 2025 14:11:29 -0700 Subject: [PATCH 1/4] Enabling Exception Analyzers --- .globalconfig | 13 +++++++++++++ .../Microsoft.Azure.Cosmos.Encryption.Custom.csproj | 4 +++- .../src/Microsoft.Azure.Cosmos.Encryption.csproj | 4 +++- Microsoft.Azure.Cosmos.sln | 1 + .../FaultInjection/src/FaultInjection.csproj | 9 +++++++-- .../src/Microsoft.Azure.Cosmos.csproj | 10 +++++++--- 6 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 .globalconfig diff --git a/.globalconfig b/.globalconfig new file mode 100644 index 0000000000..4158952430 --- /dev/null +++ b/.globalconfig @@ -0,0 +1,13 @@ +# .NET code analysis rule set +is_global = true + +# Current +dotnet_diagnostic.CDX1000.severity = suggestion # DontConvertExceptionToObject +dotnet_diagnostic.CDX1001.severity = suggestion # DontUseExceptionInInterpolation +dotnet_diagnostic.CDX1002.severity = suggestion # DontUseExceptionStackTrace +dotnet_diagnostic.CDX1003.severity = suggestion # DontUseExceptionToString + +# 📊 Experimental Analyzer Features +dotnet_diagnostic.CDX1004.severity = suggestion # Experimental - DontCreateNestedExceptions +dotnet_diagnostic.CDX1005.severity = suggestion # Experimental - DontThrowExceptions +dotnet_diagnostic.CDX1006.severity = suggestion # Experimental - DontCatchGenericExceptions \ No newline at end of file diff --git a/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj b/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj index a9d6be5f76..ffc350141f 100644 --- a/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj +++ b/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj @@ -59,9 +59,11 @@ + - + + diff --git a/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj b/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj index be4c854f0b..65bc009f36 100644 --- a/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj +++ b/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj @@ -54,9 +54,11 @@ + - + + diff --git a/Microsoft.Azure.Cosmos.sln b/Microsoft.Azure.Cosmos.sln index caafa0b41a..cec2d9a5f4 100644 --- a/Microsoft.Azure.Cosmos.sln +++ b/Microsoft.Azure.Cosmos.sln @@ -22,6 +22,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{804C595B-D0DA-48F1-A40D-97BB014736CB}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig + .globalconfig = .globalconfig EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Encryption.Custom", "Encryption.Custom", "{51F858D8-707E-4F21-BCC6-4D6123832E4F}" diff --git a/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj b/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj index 4480bcc08f..f917de0a76 100644 --- a/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj +++ b/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj @@ -66,8 +66,13 @@ - - + + + + + + + true true ..\..\..\35MSSharedLib1024.snk diff --git a/Microsoft.Azure.Cosmos/src/Microsoft.Azure.Cosmos.csproj b/Microsoft.Azure.Cosmos/src/Microsoft.Azure.Cosmos.csproj index 30b9bf5ac5..f5491489fb 100644 --- a/Microsoft.Azure.Cosmos/src/Microsoft.Azure.Cosmos.csproj +++ b/Microsoft.Azure.Cosmos/src/Microsoft.Azure.Cosmos.csproj @@ -133,11 +133,9 @@ - - @@ -150,7 +148,13 @@ - + + + + + + + From 3cdc486ebb50a603577ceb44d62aa5b49f0ba75c Mon Sep 17 00:00:00 2001 From: Arooshi Avasthy Date: Tue, 25 Mar 2025 16:09:15 -0700 Subject: [PATCH 2/4] Add Code Analyzers for Telemetry files. --- ...Microsoft.Azure.Cosmos.Encryption.Custom.csproj | 4 +--- .../src/Microsoft.Azure.Cosmos.Encryption.csproj | 4 +--- .../FaultInjection/src/FaultInjection.csproj | 5 ----- .../src/Authorization/TokenCredentialCache.cs | 14 +++++++------- Microsoft.Azure.Cosmos/src/DocumentClient.cs | 10 +++++----- .../src/Telemetry/ClientTelemetry.cs | 8 ++++---- .../src/Telemetry/ClientTelemetryHelper.cs | 2 +- .../src/Telemetry/ClientTelemetryProcessor.cs | 2 +- .../src/Telemetry/Collector/TelemetryCollector.cs | 4 ++-- .../AppInsightClassicAttributeKeys.cs | 2 +- .../Telemetry/OpenTelemetry/CosmosDbMeterUtil.cs | 2 +- .../OpenTelemetry/CosmosDbOperationMeter.cs | 2 +- .../OpenTelemetry/OpenTelemetryAttributeKeys.cs | 2 +- .../OpenTelemetry/OpenTelemetryResponse.cs | 4 ++-- .../OpenTelemetry/OpenTelemetryResponse{T}.cs | 4 ++-- .../src/Telemetry/TelemetryToServiceHelper.cs | 8 ++++---- Microsoft.Azure.Cosmos/src/ThinClientStoreModel.cs | 2 +- Microsoft.Azure.Cosmos/src/Util/Extensions.cs | 14 ++++++-------- .../src/WebExceptionRetryPolicy.cs | 2 +- 19 files changed, 42 insertions(+), 53 deletions(-) diff --git a/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj b/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj index ffc350141f..a9d6be5f76 100644 --- a/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj +++ b/Microsoft.Azure.Cosmos.Encryption.Custom/src/Microsoft.Azure.Cosmos.Encryption.Custom.csproj @@ -59,11 +59,9 @@ - - - + diff --git a/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj b/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj index 65bc009f36..be4c854f0b 100644 --- a/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj +++ b/Microsoft.Azure.Cosmos.Encryption/src/Microsoft.Azure.Cosmos.Encryption.csproj @@ -54,11 +54,9 @@ - - - + diff --git a/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj b/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj index f917de0a76..e2c985fbdc 100644 --- a/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj +++ b/Microsoft.Azure.Cosmos/FaultInjection/src/FaultInjection.csproj @@ -67,11 +67,6 @@ - - - - - true true diff --git a/Microsoft.Azure.Cosmos/src/Authorization/TokenCredentialCache.cs b/Microsoft.Azure.Cosmos/src/Authorization/TokenCredentialCache.cs index ca4eeeb5ed..588a2814db 100644 --- a/Microsoft.Azure.Cosmos/src/Authorization/TokenCredentialCache.cs +++ b/Microsoft.Azure.Cosmos/src/Authorization/TokenCredentialCache.cs @@ -219,9 +219,9 @@ private async ValueTask RefreshCachedTokenWithRetryHelperAsync( lastException = requestFailedException; getTokenTrace.AddDatum( $"RequestFailedException at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}", - requestFailedException); + requestFailedException.Message); - DefaultTrace.TraceError($"TokenCredential.GetToken() failed with RequestFailedException. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException}"); + DefaultTrace.TraceError($"TokenCredential.GetToken() failed with RequestFailedException. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException.Message}"); // Don't retry on auth failures if (requestFailedException.Status == (int)HttpStatusCode.Unauthorized || @@ -236,10 +236,10 @@ private async ValueTask RefreshCachedTokenWithRetryHelperAsync( lastException = operationCancelled; getTokenTrace.AddDatum( $"OperationCanceledException at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}", - operationCancelled); + operationCancelled.Message); DefaultTrace.TraceError( - $"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException}"); + $"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException.Message}"); throw CosmosExceptionFactory.CreateRequestTimeoutException( message: ClientResources.FailedToGetAadToken, @@ -255,10 +255,10 @@ private async ValueTask RefreshCachedTokenWithRetryHelperAsync( lastException = exception; getTokenTrace.AddDatum( $"Exception at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}", - exception); + exception.Message); DefaultTrace.TraceError( - $"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException}"); + $"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException.Message}"); } } } @@ -339,7 +339,7 @@ private async void StartBackgroundTokenRefreshLoop() DefaultTrace.TraceWarning( "BackgroundTokenRefreshLoop() - Unable to refresh token credential cache. Exception: {0}", - ex.ToString()); + ex.Message); // Since it failed retry again in with half the token life span again. if (!this.userDefinedBackgroundTokenCredentialRefreshInterval.HasValue && this.cachedAccessToken.HasValue) diff --git a/Microsoft.Azure.Cosmos/src/DocumentClient.cs b/Microsoft.Azure.Cosmos/src/DocumentClient.cs index 6828ed56c1..6ba1691909 100644 --- a/Microsoft.Azure.Cosmos/src/DocumentClient.cs +++ b/Microsoft.Azure.Cosmos/src/DocumentClient.cs @@ -687,7 +687,7 @@ private async Task OpenPrivateAsync(CancellationToken cancellationToken) enableAsyncCacheExceptionNoSharing: this.enableAsyncCacheExceptionNoSharing); this.partitionKeyRangeCache = new PartitionKeyRangeCache(this, this.GatewayStoreModel, this.collectionCache, this.GlobalEndpointManager, this.enableAsyncCacheExceptionNoSharing); - DefaultTrace.TraceWarning("{0} occurred while OpenAsync. Exception Message: {1}", ex.ToString(), ex.Message); + DefaultTrace.TraceWarning("Exception occurred while OpenAsync. Exception Message: {0}", ex.Message); } } @@ -1027,7 +1027,7 @@ internal virtual void Initialize(Uri serviceEndpoint, // UnobservedTaskException by using ContinueWith method w/ TaskContinuationOptions.OnlyOnFaulted // and accessing the Exception property on the target task. #pragma warning disable VSTHRD110 // Observe result of async calls - initTask.ContinueWith(t => DefaultTrace.TraceWarning("initializeTask failed {0}", t.Exception), TaskContinuationOptions.OnlyOnFaulted); + initTask.ContinueWith(t => DefaultTrace.TraceWarning("initializeTask failed {0}", t.Exception?.Message), TaskContinuationOptions.OnlyOnFaulted); #pragma warning restore VSTHRD110 // Observe result of async calls this.traceId = Interlocked.Increment(ref DocumentClient.idCounter); @@ -1352,7 +1352,7 @@ public void Dispose() catch (Exception exception) { DefaultTrace.TraceWarning("Exception {0} thrown during dispose of HttpClient, this could happen if there are inflight request during the dispose of client", - exception); + exception.Message); } this.httpClient = null; @@ -1620,8 +1620,8 @@ internal virtual async Task EnsureValidClientAsync(ITrace trace) } catch (Exception e) { - DefaultTrace.TraceWarning("EnsureValidClientAsync initializeTask failed {0}", e); - childTrace.AddDatum("initializeTask failed", e); + DefaultTrace.TraceWarning("EnsureValidClientAsync initializeTask failed {0}", e.Message); + childTrace.AddDatum("initializeTask failed", e.Message); throw; } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetry.cs b/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetry.cs index a56bc1b0b2..1c4b780fbe 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetry.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetry.cs @@ -200,7 +200,7 @@ ConcurrentDictionary cacheRefreshInfo } catch (Exception ex) { - DefaultTrace.TraceError("Exception in EnrichAndSendAsync() : {0}", ex); + DefaultTrace.TraceError("Exception in EnrichAndSendAsync() : {0}", ex.Message); } DefaultTrace.TraceInformation("Telemetry Job Stopped."); @@ -275,7 +275,7 @@ internal void PushCacheDatapoint(string cacheName, TelemetryInformation data) } catch (Exception ex) { - DefaultTrace.TraceError("Latency Recording Failed by Telemetry. Exception : {0}", ex); + DefaultTrace.TraceError("Latency Recording Failed by Telemetry. Exception : {0}", ex.Message); } } @@ -316,7 +316,7 @@ internal void PushOperationDatapoint(TelemetryInformation data) } catch (Exception ex) { - DefaultTrace.TraceError("Latency Recording Failed by Telemetry. Exception : {0}", ex); + DefaultTrace.TraceError("Latency Recording Failed by Telemetry. Exception : {0}", ex.Message); } } @@ -332,7 +332,7 @@ internal void PushOperationDatapoint(TelemetryInformation data) } catch (Exception ex) { - DefaultTrace.TraceError("Request Charge Recording Failed by Telemetry. Request Charge Value : {0} Exception : {1} ", requestChargeToRecord, ex); + DefaultTrace.TraceError("Request Charge Recording Failed by Telemetry. Request Charge Value : {0} Exception : {1} ", requestChargeToRecord, ex.Message); } } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryHelper.cs b/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryHelper.cs index 2399bcb9fb..7b852703a0 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryHelper.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryHelper.cs @@ -99,7 +99,7 @@ internal static List RecordSystemUtilization(DiagnosticsHandlerHelpe } catch (Exception ex) { - DefaultTrace.TraceError("System Usage Recording Error : {0} ", ex); + DefaultTrace.TraceError("System Usage Recording Error : {0} ", ex.Message); } return null; } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryProcessor.cs b/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryProcessor.cs index fbbfb68c45..48ebe68e36 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryProcessor.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/ClientTelemetryProcessor.cs @@ -51,7 +51,7 @@ await ClientTelemetryPayloadWriter.SerializedPayloadChunksAsync( } catch (Exception ex) { - DefaultTrace.TraceError("Exception while serializing telemetry payload or sending data to service: {0}", ex); + DefaultTrace.TraceError("Exception while serializing telemetry payload or sending data to service: {0}", ex.Message); } } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/Collector/TelemetryCollector.cs b/Microsoft.Azure.Cosmos/src/Telemetry/Collector/TelemetryCollector.cs index 9f2161469a..4d81ea3f50 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/Collector/TelemetryCollector.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/Collector/TelemetryCollector.cs @@ -44,7 +44,7 @@ public void CollectCacheInfo(string cacheName, Func functi } catch (Exception ex) { - DefaultTrace.TraceError("Error while collecting cache {0} telemetry. Exception : {1}", cacheName, ex); + DefaultTrace.TraceError("Error while collecting cache {0} telemetry. Exception : {1}", cacheName, ex.Message); } } @@ -65,7 +65,7 @@ public void CollectOperationAndNetworkInfo(Func functionFo } catch (Exception ex) { - DefaultTrace.TraceError("Error while collecting operation telemetry. Exception : {0}", ex); + DefaultTrace.TraceError("Error while collecting operation telemetry. Exception : {0}", ex.Message); } } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs index 942ece28db..c69e00c0d2 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs @@ -140,7 +140,7 @@ public void PopulateAttributes(DiagnosticScope scope, public void PopulateAttributes(DiagnosticScope scope, Exception exception) { - scope.AddAttribute(AppInsightClassicAttributeKeys.ExceptionStacktrace, exception.StackTrace); + scope.AddAttribute(AppInsightClassicAttributeKeys.ExceptionMessage, exception.Message); scope.AddAttribute(AppInsightClassicAttributeKeys.ExceptionType, exception.GetType().Name); // If Exception is not registered with open Telemetry diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbMeterUtil.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbMeterUtil.cs index 920f7f3d90..a5cd04c853 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbMeterUtil.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbMeterUtil.cs @@ -35,7 +35,7 @@ internal static void RecordHistogramMetric( } catch (Exception ex) { - DefaultTrace.TraceWarning($"Failed to record metric. {ex}"); + DefaultTrace.TraceWarning($"Failed to record metric. {ex.Message}"); } } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbOperationMeter.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbOperationMeter.cs index 2f214f5246..7f0063cd7f 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbOperationMeter.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/CosmosDbOperationMeter.cs @@ -144,7 +144,7 @@ internal static void AdjustInstanceCount(Uri accountEndpoint, int adjustment) } catch (Exception ex) { - DefaultTrace.TraceWarning($"Failed to adjust instance count. {ex.StackTrace}"); + DefaultTrace.TraceWarning($"Failed to adjust instance count. {ex.Message}"); } } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs index d315f03577..1770cc99a1 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs @@ -225,7 +225,7 @@ public void PopulateAttributes(DiagnosticScope scope, public void PopulateAttributes(DiagnosticScope scope, Exception exception) { - scope.AddAttribute(OpenTelemetryAttributeKeys.ExceptionStacktrace, exception.StackTrace); + scope.AddAttribute(OpenTelemetryAttributeKeys.ExceptionMessage, exception?.Message); scope.AddAttribute(OpenTelemetryAttributeKeys.ExceptionType, exception.GetType().Name); // If Exception is not registered with open Telemetry diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse.cs index e22c836a51..d74a5462cf 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse.cs @@ -92,7 +92,7 @@ private static Headers GetHeader(TransactionalBatchResponse responseMessage) } catch (NotImplementedException ex) { - DefaultTrace.TraceVerbose("Failed to get headers from TransactionalBatchResponse. Exception: {0}", ex); + DefaultTrace.TraceVerbose("Failed to get headers from TransactionalBatchResponse. Exception: {0}", ex.Message); return null; } } @@ -105,7 +105,7 @@ private static Headers GetHeader(ResponseMessage responseMessage) } catch (NotImplementedException ex) { - DefaultTrace.TraceVerbose("Failed to get headers from ResponseMessage. Exception: {0}", ex); + DefaultTrace.TraceVerbose("Failed to get headers from ResponseMessage. Exception: {0}", ex.Message); return null; } } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse{T}.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse{T}.cs index a6f3e73380..45ab965bf3 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse{T}.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryResponse{T}.cs @@ -74,7 +74,7 @@ private static Headers GetHeader(FeedResponse responseMessage) } catch (NotImplementedException ex) { - DefaultTrace.TraceWarning("Failed to get headers from FeedResponse. Exception: {0}", ex); + DefaultTrace.TraceWarning("Failed to get headers from FeedResponse. Exception: {0}", ex.Message); return null; } } @@ -87,7 +87,7 @@ private static Headers GetHeader(Response responseMessage) } catch (NotImplementedException ex) { - DefaultTrace.TraceWarning("Failed to get headers from Response. Exception: {0}", ex); + DefaultTrace.TraceWarning("Failed to get headers from Response. Exception: {0}", ex.Message); return null; } } diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/TelemetryToServiceHelper.cs b/Microsoft.Azure.Cosmos/src/Telemetry/TelemetryToServiceHelper.cs index 13092d9d59..421e3006fb 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/TelemetryToServiceHelper.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/TelemetryToServiceHelper.cs @@ -115,7 +115,7 @@ private async Task RetrieveConfigAndInitiateTelemetryAsync(bool faultInjectionCl } else if (!this.cancellationTokenSource.IsCancellationRequested) { - DefaultTrace.TraceWarning("Exception while calling client config {0} ", databaseAccountClientConfigs.Exception); + DefaultTrace.TraceWarning("Exception while calling client config {0} ", databaseAccountClientConfigs.Exception?.Message); } await Task.Delay( @@ -125,7 +125,7 @@ await Task.Delay( } catch (Exception ex) { - DefaultTrace.TraceWarning("Exception while running client config job: {0}", ex); + DefaultTrace.TraceWarning("Exception while running client config job: {0}", ex.Message); } } @@ -267,7 +267,7 @@ private void InitializeClientTelemetry(AccountClientConfiguration clientConfig) } catch (Exception ex) { - DefaultTrace.TraceWarning($"Error While starting Telemetry Job : {0}. Hence disabling Client Telemetry", ex); + DefaultTrace.TraceWarning($"Error While starting Telemetry Job : {0}. Hence disabling Client Telemetry", ex.Message); this.connectionPolicy.CosmosClientTelemetryOptions.DisableSendingMetricsToService = true; } } @@ -300,7 +300,7 @@ private void StopClientTelemetry() } catch (Exception ex) { - DefaultTrace.TraceWarning("Error While stopping Telemetry Job : {0}", ex); + DefaultTrace.TraceWarning("Error While stopping Telemetry Job : {0}", ex.Message); } } } diff --git a/Microsoft.Azure.Cosmos/src/ThinClientStoreModel.cs b/Microsoft.Azure.Cosmos/src/ThinClientStoreModel.cs index 53a9ee77e8..b8ae6d4c3e 100644 --- a/Microsoft.Azure.Cosmos/src/ThinClientStoreModel.cs +++ b/Microsoft.Azure.Cosmos/src/ThinClientStoreModel.cs @@ -132,7 +132,7 @@ protected override void Dispose(bool disposing) catch (Exception exception) { DefaultTrace.TraceWarning("Exception {0} thrown during dispose of HttpClient, this could happen if there are inflight request during the dispose of client", - exception); + exception.Message); } this.thinClientStoreClient = null; } diff --git a/Microsoft.Azure.Cosmos/src/Util/Extensions.cs b/Microsoft.Azure.Cosmos/src/Util/Extensions.cs index aaeaaecba7..492c03cbd5 100644 --- a/Microsoft.Azure.Cosmos/src/Util/Extensions.cs +++ b/Microsoft.Azure.Cosmos/src/Util/Extensions.cs @@ -138,7 +138,7 @@ internal static ResponseMessage ToCosmosResponseMessage(this DocumentClientExcep subStatusCode: cosmosException.Headers.SubStatusCode, responseTimeUtc: DateTime.UtcNow, requestCharge: cosmosException.Headers.RequestCharge, - errorMessage: documentClientException.ToString(), + errorMessage: documentClientException?.Message, method: requestMessage?.Method, requestUri: requestMessage?.RequestUriString, requestSessionToken: requestMessage?.Headers?.Session, @@ -160,7 +160,7 @@ internal static ResponseMessage ToCosmosResponseMessage(this DocumentClientExcep if (requestMessage != null) { requestMessage.Properties.Remove(nameof(DocumentClientException)); - requestMessage.Properties.Add(nameof(DocumentClientException), documentClientException); + requestMessage.Properties.Add(nameof(DocumentClientException), documentClientException?.Message); } return responseMessage; @@ -202,21 +202,19 @@ private static void TraceExceptionInternal(Exception exception) if (exception is SocketException socketException) { DefaultTrace.TraceWarning( - "Exception {0}: RequesteUri: {1}, SocketErrorCode: {2}, {3}, {4}", + "Exception {0}: RequesteUri: {1}, SocketErrorCode: {2}, {3}", exception.GetType(), requestUri, socketException.SocketErrorCode, - exception.Message, - exception.StackTrace); + exception.Message); } else { DefaultTrace.TraceWarning( - "Exception {0}: RequestUri: {1}, {2}, {3}", + "Exception {0}: RequestUri: {1}, {2}", exception.GetType(), requestUri, - exception.Message, - exception.StackTrace); + exception.Message); } exception = exception.InnerException; diff --git a/Microsoft.Azure.Cosmos/src/WebExceptionRetryPolicy.cs b/Microsoft.Azure.Cosmos/src/WebExceptionRetryPolicy.cs index be02f3391f..1c65c9310d 100644 --- a/Microsoft.Azure.Cosmos/src/WebExceptionRetryPolicy.cs +++ b/Microsoft.Azure.Cosmos/src/WebExceptionRetryPolicy.cs @@ -56,7 +56,7 @@ public Task ShouldRetryAsync( this.currentBackoffSeconds *= WebExceptionRetryPolicy.backoffMultiplier; } - DefaultTrace.TraceWarning("Received retriable web exception, will retry, {0}", exception); + DefaultTrace.TraceWarning("Received retriable web exception, will retry, {0}", exception.Message); return Task.FromResult(ShouldRetryResult.RetryAfter(backoffTime)); } From 97e6c0503b47e7aca437789d48b0e74dea0ea4d0 Mon Sep 17 00:00:00 2001 From: Arooshi Avasthy Date: Wed, 26 Mar 2025 12:12:31 -0700 Subject: [PATCH 3/4] Suppress code analyzers at necessary places. --- Microsoft.Azure.Cosmos/src/DocumentClient.cs | 4 +++- .../Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs | 4 +++- .../src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs | 4 +++- Microsoft.Azure.Cosmos/src/Util/Extensions.cs | 4 +++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/Microsoft.Azure.Cosmos/src/DocumentClient.cs b/Microsoft.Azure.Cosmos/src/DocumentClient.cs index 3743d9f321..00fb2228c1 100644 --- a/Microsoft.Azure.Cosmos/src/DocumentClient.cs +++ b/Microsoft.Azure.Cosmos/src/DocumentClient.cs @@ -1030,7 +1030,9 @@ internal virtual void Initialize(Uri serviceEndpoint, // UnobservedTaskException by using ContinueWith method w/ TaskContinuationOptions.OnlyOnFaulted // and accessing the Exception property on the target task. #pragma warning disable VSTHRD110 // Observe result of async calls - initTask.ContinueWith(t => DefaultTrace.TraceWarning("initializeTask failed {0}", t.Exception?.Message), TaskContinuationOptions.OnlyOnFaulted); +#pragma warning disable CDX1000 // DontConvertExceptionToObject + initTask.ContinueWith(t => DefaultTrace.TraceWarning("initializeTask failed {0}", t.Exception), TaskContinuationOptions.OnlyOnFaulted); +#pragma warning restore CDX1000 // DontConvertExceptionToObject #pragma warning restore VSTHRD110 // Observe result of async calls this.traceId = Interlocked.Increment(ref DocumentClient.idCounter); diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs index c69e00c0d2..dc1251169f 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/AppInsightClassicAttributeKeys.cs @@ -140,7 +140,9 @@ public void PopulateAttributes(DiagnosticScope scope, public void PopulateAttributes(DiagnosticScope scope, Exception exception) { - scope.AddAttribute(AppInsightClassicAttributeKeys.ExceptionMessage, exception.Message); +#pragma warning disable CDX1002 // DontUseExceptionStackTrace + scope.AddAttribute(AppInsightClassicAttributeKeys.ExceptionStacktrace, exception.StackTrace); +#pragma warning restore CDX1002 // DontUseExceptionStackTrace scope.AddAttribute(AppInsightClassicAttributeKeys.ExceptionType, exception.GetType().Name); // If Exception is not registered with open Telemetry diff --git a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs index 1770cc99a1..e0db3e9c1f 100644 --- a/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs +++ b/Microsoft.Azure.Cosmos/src/Telemetry/OpenTelemetry/OpenTelemetryAttributeKeys.cs @@ -225,7 +225,9 @@ public void PopulateAttributes(DiagnosticScope scope, public void PopulateAttributes(DiagnosticScope scope, Exception exception) { - scope.AddAttribute(OpenTelemetryAttributeKeys.ExceptionMessage, exception?.Message); +#pragma warning disable CDX1002 // DontUseExceptionStackTrace + scope.AddAttribute(OpenTelemetryAttributeKeys.ExceptionStacktrace, exception.StackTrace); +#pragma warning restore CDX1002 // DontUseExceptionStackTrace scope.AddAttribute(OpenTelemetryAttributeKeys.ExceptionType, exception.GetType().Name); // If Exception is not registered with open Telemetry diff --git a/Microsoft.Azure.Cosmos/src/Util/Extensions.cs b/Microsoft.Azure.Cosmos/src/Util/Extensions.cs index 492c03cbd5..244fb0d8a1 100644 --- a/Microsoft.Azure.Cosmos/src/Util/Extensions.cs +++ b/Microsoft.Azure.Cosmos/src/Util/Extensions.cs @@ -160,7 +160,9 @@ internal static ResponseMessage ToCosmosResponseMessage(this DocumentClientExcep if (requestMessage != null) { requestMessage.Properties.Remove(nameof(DocumentClientException)); - requestMessage.Properties.Add(nameof(DocumentClientException), documentClientException?.Message); +#pragma warning disable CDX1000 // DontConvertExceptionToObject + requestMessage.Properties.Add(nameof(DocumentClientException), documentClientException); +#pragma warning restore CDX1000 // DontConvertExceptionToObject } return responseMessage; From 5d3e528017315c310b0e833059068eb965adfc64 Mon Sep 17 00:00:00 2001 From: "Arooshi Avasthy (from Dev Box)" Date: Wed, 26 Mar 2025 22:58:02 -0700 Subject: [PATCH 4/4] Update failing test --- .../TransportWrapperTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/TransportWrapperTests.cs b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/TransportWrapperTests.cs index 9e7394bf21..a5c61a66bc 100644 --- a/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/TransportWrapperTests.cs +++ b/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/TransportWrapperTests.cs @@ -92,7 +92,7 @@ private void ValidateTransportException(CosmosException cosmosException) Assert.IsTrue(message.Contains("TransportException: A client transport error occurred: The connection failed"), "StoreResult Exception is missing"); string diagnostics = cosmosException.Diagnostics.ToString(); Assert.IsNotNull(diagnostics); - Assert.IsTrue(diagnostics.Contains("TransportException: A client transport error occurred: The connection failed")); + Assert.IsTrue(diagnostics.Contains("A client transport error occurred: The connection failed")); } private void ValidateTransportException(ResponseMessage responseMessage) @@ -104,7 +104,7 @@ private void ValidateTransportException(ResponseMessage responseMessage) Assert.IsTrue(message.Contains("Reason: (Channel is closed"), "Should contain exception message"); string diagnostics = responseMessage.Diagnostics.ToString(); Assert.IsNotNull(diagnostics); - Assert.IsTrue(diagnostics.Contains("TransportException: A client transport error occurred: The connection failed")); + Assert.IsTrue(diagnostics.Contains("A client transport error occurred: The connection failed")); } private static void Interceptor(