Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jul 7, 2025

Link issues

fixes #6367

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add a new EnableLog option to SocketClientOptions to allow conditional detailed logging of TCP socket send and receive operations and update the client and tests to use this flag.

New Features:

  • Add EnableLog boolean property to SocketClientOptions to control logging.
  • Log detailed send operations (data length, content, endpoints, and result) when EnableLog is true.
  • Log detailed receive operations (data length, content, and endpoints) when EnableLog is true.

Tests:

  • Update TcpSocketFactoryTest to set EnableLog to true when creating a client.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jul 7, 2025

Reviewer's Guide

Introduces an EnableLog flag in SocketClientOptions to control detailed TCP send/receive logging, incorporates conditional logging in the client implementation, and updates tests to enable logging.

Class diagram for updated SocketClientOptions and TcpSocketClientBase

classDiagram
    class SocketClientOptions {
        IPEndPoint LocalEndPoint
        bool EnableLog
    }
    class TcpSocketClientBase {
        +ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token)
        +ValueTask<int> ReceiveCoreAsync(ISocketClientProvider client, Memory<byte> buffer, CancellationToken token)
        -Log(LogLevel, Exception, string)
        -_localEndPoint
        -_remoteEndPoint
        -options: SocketClientOptions
    }
    TcpSocketClientBase --> SocketClientOptions : uses
Loading

File-Level Changes

Change Details Files
Add EnableLog property to socket client options
  • Declare bool EnableLog property with XML documentation
  • Initialize default value to false
src/BootstrapBlazor/Services/TcpSocket/SocketClientOptions.cs
Add conditional detailed logging in TCP socket client
  • Wrap SendAsync logging in if(options.EnableLog)
  • Wrap ReceiveCoreAsync logging in if(options.EnableLog)
src/BootstrapBlazor/Services/TcpSocket/TcpSocketClientBase.cs
Enable logging in socket factory tests
  • Set op.EnableLog = true in test client setup
test/UnitTest/Services/TcpSocketFactoryTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6367 Add a SocketLogger provider.
#6367 Add an EnableLog parameter to SocketClientOptions.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@bb-auto bb-auto bot added the enhancement New feature or request label Jul 7, 2025
@bb-auto bb-auto bot added this to the 9.8.0 milestone Jul 7, 2025
@ArgoZhang ArgoZhang merged commit 7e2f1f1 into main Jul 7, 2025
4 checks passed
@ArgoZhang ArgoZhang deleted the feat-socket-log branch July 7, 2025 06:25
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @ArgoZhang - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/Services/TcpSocket/TcpSocketClientBase.cs:169` </location>
<code_context>
             Log(LogLevel.Error, ex, $"TCP Socket send failed from {_localEndPoint} to {_remoteEndPoint}");
         }
+
+        if (options.EnableLog)
+        {
+            Log(LogLevel.Information, null, $"Sending data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {data.Length} Data Content: {BitConverter.ToString(data.ToArray())} Result: {ret}");
+        }
         return ret;
</code_context>

<issue_to_address>
Logging raw data content may expose sensitive information.

Redact or limit logged data content, or make logging configurable to avoid exposing sensitive information.
</issue_to_address>

### Comment 2
<location> `src/BootstrapBlazor/Services/TcpSocket/TcpSocketClientBase.cs:171` </location>
<code_context>
+
+        if (options.EnableLog)
+        {
+            Log(LogLevel.Information, null, $"Sending data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {data.Length} Data Content: {BitConverter.ToString(data.ToArray())} Result: {ret}");
+        }
         return ret;
</code_context>

<issue_to_address>
Converting ReadOnlyMemory<byte> to array may impact performance.

ToArray() allocates and copies data, which can be costly for large or frequent logs. Consider limiting logged data size or using a more efficient method.

Suggested implementation:

```csharp
        if (options.EnableLog)
        {
            const int MaxLogBytes = 64;
            int logLength = Math.Min(data.Length, MaxLogBytes);
            string dataContent;
            if (logLength > 0)
            {
                var span = data.Span.Slice(0, logLength);
                dataContent = BitConverter.ToString(span.ToArray());
                if (data.Length > MaxLogBytes)
                {
                    dataContent += "...(truncated)";
                }
            }
            else
            {
                dataContent = string.Empty;
            }
            Log(LogLevel.Information, null, $"Sending data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {data.Length} Data Content: {dataContent} Result: {ret}");
        }
        return ret;

```

```csharp
        if (options.EnableLog)
        {
            const int MaxLogBytes = 64;
            int logLength = Math.Min(len, MaxLogBytes);
            string dataContent;
            if (logLength > 0)
            {
                var span = buffer.Span.Slice(0, logLength);
                dataContent = BitConverter.ToString(span.ToArray());
                if (len > MaxLogBytes)
                {
                    dataContent += "...(truncated)";
                }
            }
            else
            {
                dataContent = string.Empty;
            }
            Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {dataContent}");
        }

```
</issue_to_address>

### Comment 3
<location> `src/BootstrapBlazor/Services/TcpSocket/TcpSocketClientBase.cs:269` </location>
<code_context>
+
+        if (options.EnableLog)
+        {
+            Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {BitConverter.ToString(buffer.ToArray())}");
+        }
         return len;
</code_context>

<issue_to_address>
Repeated ToArray() calls on buffer may be inefficient.

For large or frequently used buffers, this conversion can impact performance. Consider logging a subset of the buffer or a more efficient format.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        if (options.EnableLog)
        {
            Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {BitConverter.ToString(buffer.ToArray())}");
        }
        return len;
=======
        if (options.EnableLog)
        {
            const int maxLogBytes = 32;
            var logBytes = buffer.Count > maxLogBytes ? buffer.Slice(0, maxLogBytes).ToArray() : buffer.ToArray();
            var dataContent = BitConverter.ToString(logBytes);
            if (buffer.Count > maxLogBytes)
            {
                dataContent += $"... (truncated, total {buffer.Count} bytes)";
            }
            Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {dataContent}");
        }
        return len;
>>>>>>> REPLACE

</suggested_fix>

### Comment 4
<location> `test/UnitTest/Services/TcpSocketFactoryTest.cs:646` </location>
<code_context>
         var provider = sc.BuildServiceProvider();
         var factory = provider.GetRequiredService<ITcpSocketFactory>();
-        var client = factory.GetOrCreate("test", op => op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0));
+        var client = factory.GetOrCreate("test", op =>
+        {
+            op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0);
+            op.EnableLog = true;
+        });
         return client;
</code_context>

<issue_to_address>
No test coverage for EnableLog=false scenario.

Please add a test to cover the default EnableLog=false case and confirm that logging is not triggered.

Suggested implementation:

```csharp

        var provider = sc.BuildServiceProvider();
        var factory = provider.GetRequiredService<ITcpSocketFactory>();
        var client = factory.GetOrCreate("test", op =>
        {
            op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0);
            op.EnableLog = true;
        });
        return client;
    }

    [Fact]
    public void GetOrCreate_DefaultEnableLogFalse_DoesNotTriggerLogging()
    {
        // Arrange
        var sc = new ServiceCollection();
        // Register ITcpSocketFactory and any required dependencies, including a mock logger if needed
        var mockLogger = new Mock<ILogger>();
        sc.AddSingleton<ILogger>(mockLogger.Object);
        sc.AddSingleton<ITcpSocketFactory, TcpSocketFactory>();
        var provider = sc.BuildServiceProvider();
        var factory = provider.GetRequiredService<ITcpSocketFactory>();

        // Act
        var client = factory.GetOrCreate("test-default", op =>
        {
            op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0);
            // Do not set EnableLog, should default to false
        });

        // Assert
        // Check that logging was not triggered
        mockLogger.Verify(
            logger => logger.Log(
                It.IsAny<LogLevel>(),
                It.IsAny<EventId>(),
                It.IsAny<It.IsAnyType>(),
                It.IsAny<Exception>(),
                (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
            Times.Never
        );
    }


```

- If your project uses a different logging abstraction or does not use dependency injection for the logger, you may need to adjust the mocking and registration code accordingly.
- If `TcpSocketFactory` does not use `ILogger`, or logging is handled differently, adapt the assertion to match your actual logging mechanism.
- Ensure you have the necessary using directives at the top of the file:
  ```csharp
  using Xunit;
  using Moq;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Logging;
  ```
- If you do not have Moq installed, add it to your test project.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +169 to +171
if (options.EnableLog)
{
Log(LogLevel.Information, null, $"Sending data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {data.Length} Data Content: {BitConverter.ToString(data.ToArray())} Result: {ret}");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 issue (security): Logging raw data content may expose sensitive information.

Redact or limit logged data content, or make logging configurable to avoid exposing sensitive information.


if (options.EnableLog)
{
Log(LogLevel.Information, null, $"Sending data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {data.Length} Data Content: {BitConverter.ToString(data.ToArray())} Result: {ret}");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Converting ReadOnlyMemory to array may impact performance.

ToArray() allocates and copies data, which can be costly for large or frequent logs. Consider limiting logged data size or using a more efficient method.

Suggested implementation:

        if (options.EnableLog)
        {
            const int MaxLogBytes = 64;
            int logLength = Math.Min(data.Length, MaxLogBytes);
            string dataContent;
            if (logLength > 0)
            {
                var span = data.Span.Slice(0, logLength);
                dataContent = BitConverter.ToString(span.ToArray());
                if (data.Length > MaxLogBytes)
                {
                    dataContent += "...(truncated)";
                }
            }
            else
            {
                dataContent = string.Empty;
            }
            Log(LogLevel.Information, null, $"Sending data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {data.Length} Data Content: {dataContent} Result: {ret}");
        }
        return ret;
        if (options.EnableLog)
        {
            const int MaxLogBytes = 64;
            int logLength = Math.Min(len, MaxLogBytes);
            string dataContent;
            if (logLength > 0)
            {
                var span = buffer.Span.Slice(0, logLength);
                dataContent = BitConverter.ToString(span.ToArray());
                if (len > MaxLogBytes)
                {
                    dataContent += "...(truncated)";
                }
            }
            else
            {
                dataContent = string.Empty;
            }
            Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {dataContent}");
        }

Comment on lines +267 to 271
if (options.EnableLog)
{
Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {BitConverter.ToString(buffer.ToArray())}");
}
return len;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Repeated ToArray() calls on buffer may be inefficient.

For large or frequently used buffers, this conversion can impact performance. Consider logging a subset of the buffer or a more efficient format.

Suggested change
if (options.EnableLog)
{
Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {BitConverter.ToString(buffer.ToArray())}");
}
return len;
if (options.EnableLog)
{
const int maxLogBytes = 32;
var logBytes = buffer.Count > maxLogBytes ? buffer.Slice(0, maxLogBytes).ToArray() : buffer.ToArray();
var dataContent = BitConverter.ToString(logBytes);
if (buffer.Count > maxLogBytes)
{
dataContent += $"... (truncated, total {buffer.Count} bytes)";
}
Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {dataContent}");
}
return len;

Comment on lines +646 to +649
var client = factory.GetOrCreate("test", op =>
{
op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0);
op.EnableLog = true;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): No test coverage for EnableLog=false scenario.

Please add a test to cover the default EnableLog=false case and confirm that logging is not triggered.

Suggested implementation:

        var provider = sc.BuildServiceProvider();
        var factory = provider.GetRequiredService<ITcpSocketFactory>();
        var client = factory.GetOrCreate("test", op =>
        {
            op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0);
            op.EnableLog = true;
        });
        return client;
    }

    [Fact]
    public void GetOrCreate_DefaultEnableLogFalse_DoesNotTriggerLogging()
    {
        // Arrange
        var sc = new ServiceCollection();
        // Register ITcpSocketFactory and any required dependencies, including a mock logger if needed
        var mockLogger = new Mock<ILogger>();
        sc.AddSingleton<ILogger>(mockLogger.Object);
        sc.AddSingleton<ITcpSocketFactory, TcpSocketFactory>();
        var provider = sc.BuildServiceProvider();
        var factory = provider.GetRequiredService<ITcpSocketFactory>();

        // Act
        var client = factory.GetOrCreate("test-default", op =>
        {
            op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0);
            // Do not set EnableLog, should default to false
        });

        // Assert
        // Check that logging was not triggered
        mockLogger.Verify(
            logger => logger.Log(
                It.IsAny<LogLevel>(),
                It.IsAny<EventId>(),
                It.IsAny<It.IsAnyType>(),
                It.IsAny<Exception>(),
                (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
            Times.Never
        );
    }
  • If your project uses a different logging abstraction or does not use dependency injection for the logger, you may need to adjust the mocking and registration code accordingly.
  • If TcpSocketFactory does not use ILogger, or logging is handled differently, adapt the assertion to match your actual logging mechanism.
  • Ensure you have the necessary using directives at the top of the file:
    using Xunit;
    using Moq;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
  • If you do not have Moq installed, add it to your test project.

@codecov
Copy link

codecov bot commented Jul 7, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (786b2c1) to head (e4a1be1).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #6371   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          718       718           
  Lines        31615     31624    +9     
  Branches      4461      4463    +2     
=========================================
+ Hits         31615     31624    +9     
Flag Coverage Δ
BB 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(SocketClientOptions): add EnableLog parameter

2 participants