Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/mono/corefx.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStephen Toub <stoub@microsoft.com>2016-10-28 22:52:50 +0300
committerStephen Toub <stoub@microsoft.com>2016-10-29 17:01:53 +0300
commit92fd5c0814bcc0c03acfa9f3ad857661828b35a6 (patch)
tree15b25d563bde09612baabe0a300b7e6fa5c3cede
parentaed38c1da30baa8b93598745d13ab98088f3a745 (diff)
Overhaul System.Net library logging
This PR overhauls how logging is accomplished in the System.Net libraries. There are a few problems with the existing solution: 1. In the original sources, logging was split across a GlobalLog class and a Logging class. Global-related tracing went to GlobalLog, and library-specific tracing went to Logging. When the sources were moved to corefx, this evolved into multiple EventSource-based types, most of which were in Common and were then src-included into each System.Net assembly. This has a significant problem, though, which is that the name/Guid identity of an EventSource can only exist once in a process, and subsequent EventSource instances with the same identity fail. This means that whichever assembly ends up logging something first wins, and all other tracing from other System.Net assemblies ends up being lost. 2. The split also may have made sense when all components shared the same GlobalLog, but now that GlobalLog is included as a unique EventSource instance in each assembly, it's no longer global. This means that we're not only loading multiple EventSources unnecessarily (each has its own costs), but we're also duplicating logging, as some logging is done to one or the other, but some logging is done to both. 3. Due to sharing the Logging class, which evolved into an EventSource-based type, many logging calls had to include which component they came from as an enum value, leading to bloating at the call sites. 4. Additionally, many logging operations included the name of the method in which the calling was being done, which meant both longer call sites as well as stale values as members got renamed over time. 5. Call sites ended up getting fairly long due to lots of string concatenation operations and other manipulations in the logging call. This also then led to most call sites needing to be guarded behind checks for IsEnabled, leading to lots of code at every call site and obscuring the actual information being traced. 6. An additional requirement that got added with the move to corefx was that certain failure conditions should both Debug.Fail and do tracing, leading to some tracing operations taking upwards of 10 lines of code. All of these issues are addressed by this PR. - Each System.Net assembly that needs to log now loads a single NetEventSource type for doing logging, each with its own identity. - That implementation is split across a common, partial NetEventSource.Common.cs file used by all such assemblies, and then a per-assembly partial NetEventSource.AssemblyName.cs file used by the individual assembly. The former file contains most of the logging implementation. The latter files typically contain just the partial class declaration along with the [EventSource] attribute that gives that assembly's NetEventSource its unique identity / name. - The logging operations in NetEventSource.Common.cs use a variety of relatively-recent language enhancements to improve the logging. Each operation uses a [CallerMemberName] so that the call sites don't need to specify the caller. FormattableString is used so that call sites can use string interpolation while still providing the logging implementation the flexibility to format the individual components in a desired fashion (e.g. IntPtrs are formatted as hex, SafeHandles are rendered in a way that includes their name+hashcode+handle, etc.), along with a mechanism that allows individual libraries to add additional formatting rules. Each operation allows the this reference (or another this-like context object) to be passed in, to simply identify the source of the call (in concert with the caller member name). A debug-only mechanism is included in the tracing to help find potential perf issues due to misuse of the logger. Etc. - A Fail logging operation is included that both traces and does a Debug.Fail. With these changes, most call sites are greatly simplified. Some examples: Before: ```C# if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("ContextAwareResult#{0}::ContextCopy|Called on completed result.", LoggingHash.HashString(this)); } Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::ContextCopy |Called on completed result."); ``` After: ```C# NetEventSource.Fail(this, "Called on completed result."); ``` Before: ```C# if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", handler); ``` After: ```C# NetEventSource.Enter(this, handler); ``` Etc. In addition to fixing up all of the event sources, I of course also fixed up all usage in order to clean up the call sites. However, this was a rather mechanical change: I did not remove existing logging (other than duplication) nor did I add new logging. At some point, we should review the actual logging being done to determine what's missing and what's not needed. I also did not revise the additional existing events on the sockets and security event sources, but we may want to remove those (or some of those) in favor of just using the shared events.
-rw-r--r--Documentation/debugging/windows-instructions.md26
-rw-r--r--src/Common/src/Interop/Windows/SChannel/SecPkgContext_ConnectionInfo.cs7
-rw-r--r--src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs7
-rw-r--r--src/Common/src/Interop/Windows/Winsock/SafeNativeOverlapped.cs15
-rw-r--r--src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs15
-rw-r--r--src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs13
-rw-r--r--src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs5
-rw-r--r--src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs235
-rw-r--r--src/Common/src/Interop/Windows/sspicli/SecPkgContext_Sizes.cs7
-rw-r--r--src/Common/src/Interop/Windows/sspicli/SecPkgContext_StreamSizes.cs7
-rw-r--r--src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs25
-rw-r--r--src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs192
-rw-r--r--src/Common/src/System/Net/ContextAwareResult.Windows.cs28
-rw-r--r--src/Common/src/System/Net/ContextAwareResult.cs94
-rw-r--r--src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs12
-rw-r--r--src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs12
-rw-r--r--src/Common/src/System/Net/DebugSafeHandle.cs7
-rw-r--r--src/Common/src/System/Net/DebugSafeHandleMinusOneIsInvalid.cs12
-rw-r--r--src/Common/src/System/Net/InternalException.cs9
-rw-r--r--src/Common/src/System/Net/LazyAsyncResult.cs101
-rw-r--r--src/Common/src/System/Net/Logging/DebugThreadTracking.cs184
-rw-r--r--src/Common/src/System/Net/Logging/EventSourceLogging.cs79
-rw-r--r--src/Common/src/System/Net/Logging/GlobalLog.cs304
-rw-r--r--src/Common/src/System/Net/Logging/HttpEventSource.cs205
-rw-r--r--src/Common/src/System/Net/Logging/LoggingHash.cs108
-rw-r--r--src/Common/src/System/Net/Logging/MailEventSource.cs82
-rw-r--r--src/Common/src/System/Net/Logging/NetEventSource.Common.cs739
-rw-r--r--src/Common/src/System/Net/Logging/NetEventSource.cs302
-rw-r--r--src/Common/src/System/Net/Logging/SecurityEventSource.Windows.cs184
-rw-r--r--src/Common/src/System/Net/Logging/SecurityEventSource.cs425
-rw-r--r--src/Common/src/System/Net/Logging/SocketsEventSource.cs219
-rw-r--r--src/Common/src/System/Net/SafeCloseSocket.Unix.cs25
-rw-r--r--src/Common/src/System/Net/SafeCloseSocket.Windows.cs47
-rw-r--r--src/Common/src/System/Net/SafeCloseSocket.cs55
-rw-r--r--src/System.Net.Http/System.Net.Http.sln14
-rw-r--r--src/System.Net.Http/src/System.Net.Http.csproj11
-rw-r--r--src/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/ByteArrayHeaderParser.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs4
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs6
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpClient.cs33
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpContent.cs11
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpMessageHandler.cs3
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs12
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs14
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs12
-rw-r--r--src/System.Net.Http/src/System/Net/Http/MultipartContent.cs10
-rw-r--r--src/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs67
-rw-r--r--src/System.Net.Http/src/System/Net/Http/StreamContent.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs5
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.EasyRequest.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs14
-rw-r--r--src/System.Net.Http/src/netcore50/System/Net/cookie.cs4
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/LoggingTest.cs21
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj3
-rw-r--r--src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj13
-rw-r--r--src/System.Net.Mail/src/System.Net.Mail.csproj17
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/MailMessage.cs4
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/MailPriority.cs4
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/NetEventSource.Mail.cs13
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs155
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs37
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/SmtpLoginAuthenticationModule.cs4
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs28
-rw-r--r--src/System.Net.Mail/tests/Functional/LoggingTest.cs21
-rw-r--r--src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj1
-rw-r--r--src/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj19
-rw-r--r--src/System.Net.NameResolution/src/System.Net.NameResolution.csproj15
-rw-r--r--src/System.Net.NameResolution/src/System/Net/DNS.cs126
-rw-r--r--src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs17
-rw-r--r--src/System.Net.NameResolution/src/System/Net/NetEventSource.NameResolution.cs11
-rw-r--r--src/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs22
-rw-r--r--src/System.Net.NameResolution/tests/FunctionalTests/System.Net.NameResolution.Functional.Tests.csproj1
-rw-r--r--src/System.Net.NameResolution/tests/PalTests/Fakes/DebugThreadTracking.cs (renamed from src/System.Net.NameResolution/tests/PalTests/Fakes/GlobalLog.cs)12
-rw-r--r--src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj7
-rw-r--r--src/System.Net.NameResolution/tests/UnitTests/System.Net.NameResolution.Unit.Tests.csproj13
-rw-r--r--src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj15
-rw-r--r--src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs11
-rw-r--r--src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs5
-rw-r--r--src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs5
-rw-r--r--src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs30
-rw-r--r--src/System.Net.NetworkInformation/tests/FunctionalTests/LoggingTest.cs21
-rw-r--r--src/System.Net.NetworkInformation/tests/FunctionalTests/System.Net.NetworkInformation.Functional.Tests.csproj1
-rw-r--r--src/System.Net.NetworkInformation/tests/UnitTests/System.Net.NetworkInformation.WinRT.Unit.Tests.csproj8
-rw-r--r--src/System.Net.Ping/src/System.Net.Ping.csproj8
-rw-r--r--src/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.cs11
-rw-r--r--src/System.Net.Ping/tests/FunctionalTests/LoggingTest.cs21
-rw-r--r--src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj1
-rw-r--r--src/System.Net.Primitives/src/System.Net.Primitives.csproj11
-rw-r--r--src/System.Net.Primitives/src/System/Net/Cookie.cs11
-rw-r--r--src/System.Net.Primitives/src/System/Net/CookieCollection.cs4
-rw-r--r--src/System.Net.Primitives/src/System/Net/CookieContainer.cs9
-rw-r--r--src/System.Net.Primitives/src/System/Net/CredentialCache.cs84
-rw-r--r--src/System.Net.Primitives/src/System/Net/NetEventSource.Primitives.cs11
-rw-r--r--src/System.Net.Primitives/src/System/Net/SocketException.Unix.cs6
-rw-r--r--src/System.Net.Primitives/src/System/Net/SocketException.cs6
-rw-r--r--src/System.Net.Primitives/src/System/Net/SocketException.netstandard17.cs5
-rw-r--r--src/System.Net.Primitives/tests/FunctionalTests/LoggingTest.cs21
-rw-r--r--src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj1
-rw-r--r--src/System.Net.Primitives/tests/PalTests/Fakes/GlobalLog.cs19
-rw-r--r--src/System.Net.Primitives/tests/PalTests/Fakes/NetEventSource.cs13
-rw-r--r--src/System.Net.Primitives/tests/PalTests/System.Net.Primitives.Pal.Tests.csproj2
-rw-r--r--src/System.Net.Primitives/tests/UnitTests/Fakes/GlobalLog.cs23
-rw-r--r--src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj8
-rw-r--r--src/System.Net.Requests/src/System.Net.Requests.csproj15
-rw-r--r--src/System.Net.Requests/src/System/Net/CommandStream.cs15
-rw-r--r--src/System.Net.Requests/src/System/Net/FtpControlStream.cs33
-rw-r--r--src/System.Net.Requests/src/System/Net/FtpDataStream.cs10
-rw-r--r--src/System.Net.Requests/src/System/Net/FtpWebRequest.cs232
-rw-r--r--src/System.Net.Requests/src/System/Net/FtpWebResponse.cs19
-rw-r--r--src/System.Net.Requests/src/System/Net/HttpWebRequest.cs16
-rw-r--r--src/System.Net.Requests/src/System/Net/NetEventSource.Requests.cs11
-rw-r--r--src/System.Net.Requests/src/System/Net/TimerThread.cs85
-rw-r--r--src/System.Net.Requests/src/System/Net/WebRequest.cs16
-rw-r--r--src/System.Net.Requests/tests/LoggingTest.cs21
-rw-r--r--src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj5
-rw-r--r--src/System.Net.Security/src/System.Net.Security.csproj24
-rw-r--r--src/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs33
-rw-r--r--src/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs63
-rw-r--r--src/System.Net.Security/src/System/Net/FixedSizeReader.cs14
-rw-r--r--src/System.Net.Security/src/System/Net/HelperAsyncResults.cs14
-rw-r--r--src/System.Net.Security/src/System/Net/NTAuthentication.cs88
-rw-r--r--src/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs2
-rw-r--r--src/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs14
-rw-r--r--src/System.Net.Security/src/System/Net/Security/NegoState.cs14
-rw-r--r--src/System.Net.Security/src/System/Net/Security/NegotiateStream.cs44
-rw-r--r--src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs22
-rw-r--r--src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs70
-rw-r--r--src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs90
-rw-r--r--src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs334
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SSPIHandleCache.cs9
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SecureChannel.cs362
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SecurityBuffer.cs21
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs46
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslState.cs90
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs20
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs12
-rw-r--r--src/System.Net.Security/src/System/Net/SslStreamContext.cs7
-rw-r--r--src/System.Net.Security/src/System/Net/StreamFramer.cs28
-rw-r--r--src/System.Net.Security/tests/FunctionalTests/LoggingTest.cs21
-rw-r--r--src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj3
-rw-r--r--src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj8
-rw-r--r--src/System.Net.Sockets/src/System.Net.Sockets.csproj18
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs30
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Unix.cs7
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs56
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.cs7
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs66
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs80
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs45
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs16
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs12
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs1462
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs4
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs84
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs30
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs5
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs94
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.netstandard17.cs60
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs132
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs6
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/LoggingTest.cs21
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj3
-rw-r--r--src/System.Net.WebHeaderCollection/src/System.Net.WebHeaderCollection.csproj9
-rw-r--r--src/System.Net.WebHeaderCollection/src/System/Net/NetEventSource.WebHeaderCollection.cs11
-rw-r--r--src/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs35
-rw-r--r--src/System.Net.WebHeaderCollection/tests/LoggingTest.cs21
-rw-r--r--src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj1
-rw-r--r--src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj8
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs16
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/NetEventSource.WebSockets.cs11
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Win32.cs7
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.WinRT.cs6
-rw-r--r--src/System.Net.WebSockets.Client/tests/LoggingTest.cs22
-rw-r--r--src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj1
175 files changed, 3100 insertions, 6167 deletions
diff --git a/Documentation/debugging/windows-instructions.md b/Documentation/debugging/windows-instructions.md
index e7a6548b9f..a6da9330a4 100644
--- a/Documentation/debugging/windows-instructions.md
+++ b/Documentation/debugging/windows-instructions.md
@@ -89,11 +89,10 @@ Logs are going to be placed in %SYSTEMDRIVE%\sockets.etl.
#### Trace multiple providers
-1. Create a new file containing all the GUIDs. Create a file called providers.txt:
+1. Create a file called providers.txt with the following contents:
```
"{e03c0352-f9c9-56ff-0ea7-b94ba8cabc6b}"
- "{501a994a-eb63-5415-9af1-1b031260f16c}"
"{066c0e27-a02d-5a98-9a4d-078cc3b1a896}"
"{bdd9a83e-1929-5482-0d73-2fe5e1c0e16d}"
```
@@ -138,31 +137,36 @@ Logs are going to be placed in %SYSTEMDRIVE%\sockets.etl.
### Built-in EventSource tracing
-The following EventSources are built-in CoreFX. The ones that are not marked as [__TestCode__] or [__FEATURE_TRACING__] can be enabled in production scenarios for log collection.
+The following EventSources are built-in to CoreFX. The ones that are not marked as [__TestCode__] can be enabled in production scenarios for log collection.
#### Global
* `*System.Diagnostics.Eventing.FrameworkEventSource {8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1}`: Global EventSource used by multiple namespaces.
#### System.Collections
-* `*System.Collections.Concurrent.ConcurrentCollectionsEventSource {35167F8E-49B2-4b96-AB86-435B59336B5E}`: [__FEATURE_TRACING__] Provides an event source for tracing Coordination Data Structure collection information.
+* `*System.Collections.Concurrent.ConcurrentCollectionsEventSource {35167F8E-49B2-4b96-AB86-435B59336B5E}`: Provides an event source for tracing Coordination Data Structure collection information.
#### System.Linq
* `*System.Linq.Parallel.PlinqEventSource {159eeeec-4a14-4418-a8fe-faabcd987887}`: Provides an event source for tracing PLINQ information.
#### System.Net namespaces
-
-* `*Microsoft-System-Net-Debug {99e4576b-9d7e-585f-8b32-0ac3082f2282}`: Highly verbose, low-level debugging traces in production code.
+* `*Microsoft-System-Net-Http {bdd9a83e-1929-5482-0d73-2fe5e1c0e16d}`: HTTP-related traces.
+* `*Microsoft-System-Net-Mail {42c8027b-f048-58d2-537d-a4a9d5ee7038}`: SMTP-related traces.
+* `*Microsoft-System-Net-NameResolution {5f302add-3825-520e-8fa0-627b206e2e7e}`: DNS-related traces.
+* `*Microsoft-System-Net-NetworkInformation {b8e42167-0eb2-5e39-97b5-acaca593d3a2}`: Network configuration-related traces.
+* `*Microsoft-System-Net-Ping {a771ec4a-7260-59ce-0475-db257437ed8c}`: Ping-related traces.
+* `*Microsoft-System-Net-Primitives {a9f9e4e1-0cf5-5005-b530-3d37959d5e84}`: Traces related to core networking-related types.
+* `*Microsoft-System-Net-Requests {3763dc7e-7046-5576-9041-5616e21cc2cf}`: WebRequest-related traces.
+* `*Microsoft-System-Net-Sockets {e03c0352-f9c9-56ff-0ea7-b94ba8cabc6b}`: Sockets-related traces.
+* `*Microsoft-System-Net-Security {066c0e27-a02d-5a98-9a4d-078cc3b1a896}`: Security-related traces.
+* `*Microsoft-System-Net-WebHeaderCollection {fd36452f-9f2b-5850-d212-6c436231e3dc}`: WebHeaderCollection-related traces.
+* `*Microsoft-System-Net-WebSockets-Client {71cddde3-cf58-52d5-094f-927828a09337}`: ClientWebSocket-related traces.
* `*Microsoft-System-Net-TestLogging {18579866-5c03-5954-91ff-bdc63681458c}`: [__TestCode__] Test-code tracing (I/O async completions, performance test reporting).
-* `*Microsoft-System-Net {501a994a-eb63-5415-9af1-1b031260f16c}`: Common tracing shared by System.Net components.
-* `*Microsoft-System-Net-Sockets {e03c0352-f9c9-56ff-0ea7-b94ba8cabc6b}`: Sockets specific traces.
-* `*Microsoft-System-Net-Security {066c0e27-a02d-5a98-9a4d-078cc3b1a896}`: Security specific traces.
-* `*Microsoft-System-Net-Http {bdd9a83e-1929-5482-0d73-2fe5e1c0e16d}`: Http specific traces.
#### System.Threading
* `*System.Threading.SynchronizationEventSource {EC631D38-466B-4290-9306-834971BA0217}`: Provides an event source for tracing Coordination Data Structure synchronization information.
* `*System.Threading.Tasks.TplEventSource {2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5}`: Provides an event source for tracing TPL information.
* `*System.Threading.Tasks.Parallel.EventSource`: Provides an event source for tracing TPL information.
-* `*System.Threading.Tasks.Dataflow.DataflowEventSource {16F53577-E41D-43D4-B47E-C17025BF4025}`: [__FEATURE_TRACING__] Provides an event source for tracing Dataflow information.
+* `*System.Threading.Tasks.Dataflow.DataflowEventSource {16F53577-E41D-43D4-B47E-C17025BF4025}`: Provides an event source for tracing Dataflow information.
## Notes
* You can find the test invocation command-line by looking at the logs generated after the `msbuild /t:rebuild,test` within the test folder.
diff --git a/src/Common/src/Interop/Windows/SChannel/SecPkgContext_ConnectionInfo.cs b/src/Common/src/Interop/Windows/SChannel/SecPkgContext_ConnectionInfo.cs
index e9510816fd..57b6eb3405 100644
--- a/src/Common/src/Interop/Windows/SChannel/SecPkgContext_ConnectionInfo.cs
+++ b/src/Common/src/Interop/Windows/SChannel/SecPkgContext_ConnectionInfo.cs
@@ -38,12 +38,7 @@ namespace System.Net
}
catch (OverflowException)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslConnectionInfo::.ctor", "Negative size.");
- }
-
- Debug.Fail("SslConnectionInfo::.ctor", "Negative size.");
+ NetEventSource.Fail(this, "Negative size");
throw;
}
}
diff --git a/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs b/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs
index 7042329218..a64928f333 100644
--- a/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs
+++ b/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs
@@ -38,12 +38,7 @@ namespace System.Net
}
var cert = new X509Certificate2(new IntPtr(next));
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "UnmanagedCertificateContext::GetRemoteCertificatesFromStoreContext " +
- "adding remote certificate:" + cert.Subject + cert.Thumbprint);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(certContext, $"Adding remote certificate:{cert}");
result.Add(cert);
last = next;
diff --git a/src/Common/src/Interop/Windows/Winsock/SafeNativeOverlapped.cs b/src/Common/src/Interop/Windows/Winsock/SafeNativeOverlapped.cs
index 5d880b4125..54619569f8 100644
--- a/src/Common/src/Interop/Windows/Winsock/SafeNativeOverlapped.cs
+++ b/src/Common/src/Interop/Windows/Winsock/SafeNativeOverlapped.cs
@@ -15,10 +15,7 @@ namespace System.Net.Sockets
private SafeNativeOverlapped()
: this(IntPtr.Zero)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeNativeOverlapped#" + LoggingHash.HashString(this) + "::ctor(null)");
- }
+ NetEventSource.Info(this);
}
private SafeNativeOverlapped(IntPtr handle)
@@ -32,10 +29,7 @@ namespace System.Net.Sockets
{
SocketHandle = socketHandle;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeNativeOverlapped#" + LoggingHash.HashString(this) + "::ctor(socket#" + LoggingHash.HashString(socketHandle) + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"socketHandle:{socketHandle}");
#if DEBUG
SocketHandle.AddRef();
@@ -57,10 +51,7 @@ namespace System.Net.Sockets
protected override bool ReleaseHandle()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeNativeOverlapped#" + LoggingHash.HashString(this) + "::ReleaseHandle()");
- }
+ NetEventSource.Info(this);
FreeNativeOverlapped();
diff --git a/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs b/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs
index e420e97942..c238003cfc 100644
--- a/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs
+++ b/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs
@@ -16,18 +16,12 @@ namespace System.Net
{
if (safeHandle.IsInvalid)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NegotiationInfoClass::.ctor() the handle is invalid:" + (safeHandle.DangerousGetHandle()).ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Invalid handle:{safeHandle}");
return;
}
IntPtr packageInfo = safeHandle.DangerousGetHandle();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:X}");
if (negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_COMPLETE
|| negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_OPTIMISTIC)
@@ -39,10 +33,7 @@ namespace System.Net
name = Marshal.PtrToStringUni(unmanagedString);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8") + " name:" + LoggingHash.ObjectToString(name));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState} name:{name}");
// An optimization for future string comparisons.
if (string.Compare(name, Kerberos, StringComparison.OrdinalIgnoreCase) == 0)
diff --git a/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs b/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs
index 446b6da3b7..4d377a35f8 100644
--- a/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs
+++ b/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs
@@ -28,10 +28,7 @@ namespace System.Net
public int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIAuthType::EnumerateSecurityPackages()");
- }
+ NetEventSource.Info(this);
return SafeFreeContextBuffer.EnumeratePackages(out pkgnum, out pkgArray);
}
@@ -108,16 +105,10 @@ namespace System.Net
if (status == 0 && qop == Interop.SspiCli.SECQOP_WRAP_NO_ENCRYPT)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SspiCli.DecryptMessage", "Expected qop = 0, returned value = " + qop.ToString("x", CultureInfo.InvariantCulture));
- }
-
- Debug.Fail("SspiCli.DecryptMessage", "Expected qop = 0, returned value = " + qop.ToString("x", CultureInfo.InvariantCulture));
+ NetEventSource.Fail(this, $"Expected qop = 0, returned value = {qop}");
throw new InvalidOperationException(SR.net_auth_message_not_encrypted);
}
-
return status;
}
diff --git a/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs b/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs
index 58ce7f3a44..9b843a9e27 100644
--- a/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs
+++ b/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs
@@ -26,10 +26,7 @@ namespace System.Net
public int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPISecureChannelType::EnumerateSecurityPackages()");
- }
+ NetEventSource.Info(this);
return SafeFreeContextBuffer.EnumeratePackages(out pkgnum, out pkgArray);
}
diff --git a/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs b/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs
index d92d864f12..7f30735c9c 100644
--- a/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs
+++ b/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs
@@ -14,10 +14,7 @@ namespace System.Net
{
internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterface secModule)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter(nameof(EnumerateSecurityPackages));
- }
+ NetEventSource.Enter(null);
if (secModule.SecurityPackages == null)
{
@@ -30,10 +27,7 @@ namespace System.Net
try
{
int errorCode = secModule.EnumerateSecurityPackages(out moduleCount, out arrayBaseHandle);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::arrayBase: " + (arrayBaseHandle.DangerousGetHandle().ToString("x")));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"arrayBase: {arrayBaseHandle}");
if (errorCode != 0)
{
throw new Win32Exception(errorCode);
@@ -45,10 +39,7 @@ namespace System.Net
for (i = 0; i < moduleCount; i++)
{
securityPackages[i] = new SecurityPackageInfoClass(arrayBaseHandle, i);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.EnumerateSecurityPackages(securityPackages[i].Name);
- }
+ NetEventSource.Log.EnumerateSecurityPackages(securityPackages[i].Name);
}
secModule.SecurityPackages = securityPackages;
@@ -64,10 +55,7 @@ namespace System.Net
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave(nameof(EnumerateSecurityPackages));
- }
+ NetEventSource.Exit(null);
return secModule.SecurityPackages;
}
@@ -90,10 +78,7 @@ namespace System.Net
}
}
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.SspiPackageNotFound(packageName);
- }
+ NetEventSource.Log.SspiPackageNotFound(packageName);
if (throwIfMissing)
{
@@ -105,33 +90,16 @@ namespace System.Net
public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): using " + package);
- }
+ NetEventSource.Enter(null, package);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.AcquireDefaultCredential(package, intent);
- }
+ NetEventSource.Log.AcquireDefaultCredential(package, intent);
SafeFreeCredentials outCredential = null;
int errorCode = secModule.AcquireDefaultCredential(package, intent, out outCredential);
if (errorCode != 0)
{
-#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): error " + Interop.MapSecurityStatus((uint)errorCode));
- }
-#endif
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireDefaultCredential()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(AcquireDefaultCredential), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
return outCredential;
@@ -139,15 +107,8 @@ namespace System.Net
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.SEC_WINNT_AUTH_IDENTITY_W authdata)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): using " + package);
- }
-
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.AcquireCredentialsHandle(package, intent, authdata);
- }
+ NetEventSource.Enter(null, package);
+ NetEventSource.Log.AcquireCredentialsHandle(package, intent, authdata);
SafeFreeCredentials credentialsHandle = null;
int errorCode = secModule.AcquireCredentialsHandle(package,
@@ -157,16 +118,7 @@ namespace System.Net
if (errorCode != 0)
{
-#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): error " + Interop.MapSecurityStatus((uint)errorCode));
- }
-#endif
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
@@ -175,21 +127,14 @@ namespace System.Net
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.AcquireCredentialsHandle(package, intent, authdata);
- }
+ NetEventSource.Log.AcquireCredentialsHandle(package, intent, authdata);
SafeFreeCredentials credentialsHandle = null;
int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle);
if (errorCode != 0)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
@@ -198,15 +143,8 @@ namespace System.Net
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCHANNEL_CRED scc)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): using " + package);
- }
-
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.AcquireCredentialsHandle(package, intent, scc);
- }
+ NetEventSource.Enter(null, package);
+ NetEventSource.Log.AcquireCredentialsHandle(package, intent, scc);
SafeFreeCredentials outCredential = null;
int errorCode = secModule.AcquireCredentialsHandle(
@@ -217,100 +155,54 @@ namespace System.Net
if (errorCode != 0)
{
-#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): error " + Interop.MapSecurityStatus((uint)errorCode));
- }
-#endif
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
-#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): cred handle = " + outCredential.ToString());
- }
-#endif
+ NetEventSource.Exit(null, outCredential);
return outCredential;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.InitializeSecurityContext(credential.ToString(),
- LoggingHash.ObjectToString(context),
- targetName,
- inFlags);
- }
+ NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
int errorCode = secModule.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, datarep, inputBuffer, outputBuffer, ref outFlags);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.SecurityContextInputBuffer(nameof(InitializeSecurityContext), (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
- }
-
+ NetEventSource.Log.SecurityContextInputBuffer(nameof(InitializeSecurityContext), inputBuffer?.size ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
+
return errorCode;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.InitializeSecurityContext(credential.ToString(),
- LoggingHash.ObjectToString(context),
- targetName,
- inFlags);
- }
+ NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
int errorCode = secModule.InitializeSecurityContext(credential, ref context, targetName, inFlags, datarep, inputBuffers, outputBuffer, ref outFlags);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.SecurityContextInputBuffers(nameof(InitializeSecurityContext), (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
- }
+ NetEventSource.Log.SecurityContextInputBuffers(nameof(InitializeSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int AcceptSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.AcceptSecurityContext(credential.ToString(), LoggingHash.ObjectToString(context), inFlags);
- }
+ NetEventSource.Log.AcceptSecurityContext(credential, context, inFlags);
int errorCode = secModule.AcceptSecurityContext(ref credential, ref context, inputBuffer, inFlags, datarep, outputBuffer, ref outFlags);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.SecurityContextInputBuffer(nameof(AcceptSecurityContext), (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
- }
+ NetEventSource.Log.SecurityContextInputBuffer(nameof(AcceptSecurityContext), inputBuffer?.size ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int AcceptSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.AcceptSecurityContext(credential.ToString(), LoggingHash.ObjectToString(context), inFlags);
- }
+ NetEventSource.Log.AcceptSecurityContext(credential, context, inFlags);
int errorCode = secModule.AcceptSecurityContext(credential, ref context, inputBuffers, inFlags, datarep, outputBuffer, ref outFlags);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.SecurityContextInputBuffers(nameof(AcceptSecurityContext), (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
- }
+ NetEventSource.Log.SecurityContextInputBuffers(nameof(AcceptSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
@@ -319,10 +211,7 @@ namespace System.Net
{
int errorCode = secModule.CompleteAuthToken(ref context, inputBuffers);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.OperationReturnedSomething("CompleteAuthToken()", (Interop.SECURITY_STATUS)errorCode);
- }
+ NetEventSource.Log.OperationReturnedSomething(nameof(CompleteAuthToken), (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
@@ -331,10 +220,7 @@ namespace System.Net
{
int errorCode = secModule.ApplyControlToken(ref context, inputBuffers);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.OperationReturnedSomething("ApplyControlToken()", (Interop.SECURITY_STATUS)errorCode);
- }
+ NetEventSource.Log.OperationReturnedSomething(nameof(ApplyControlToken), (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
@@ -422,12 +308,7 @@ namespace System.Net
break;
default:
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
- }
-
- Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
+ if (NetEventSource.IsEnabled) NetEventSource.Fail(null, $"Unknown OP: {op}");
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
@@ -468,12 +349,7 @@ namespace System.Net
if (j >= input.Length)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
- }
-
- Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
+ NetEventSource.Fail(null, "Output buffer out of range.");
iBuffer.size = 0;
iBuffer.offset = 0;
iBuffer.token = null;
@@ -484,34 +360,24 @@ namespace System.Net
// Backup validate the new sizes.
if (iBuffer.offset < 0 || iBuffer.offset > (iBuffer.token == null ? 0 : iBuffer.token.Length))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'offset' out of range. [{0}]", iBuffer.offset);
- }
-
- Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'offset' out of range. [" + iBuffer.offset + "]");
+ NetEventSource.Fail(null, $"'offset' out of range. [{iBuffer.offset}]");
}
if (iBuffer.size < 0 || iBuffer.size > (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'size' out of range. [{0}]", iBuffer.size);
- }
-
- Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'size' out of range. [" + iBuffer.size + "]");
+ NetEventSource.Fail(null, $"'size' out of range. [{iBuffer.size}]");
}
}
- if (errorCode != 0 && NetEventSource.Log.IsEnabled())
+ if (errorCode != 0 && NetEventSource.IsEnabled)
{
if (errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE)
{
- NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE"));
+ NetEventSource.Error(null, SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE"));
}
else
{
- NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, op, String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
+ NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, op, $"0x{0:X}"));
}
}
@@ -532,26 +398,17 @@ namespace System.Net
public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter(nameof(QueryContextChannelBinding), contextAttribute.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute);
SafeFreeContextBufferChannelBinding result;
int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);
if (errorCode != 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave(nameof(QueryContextChannelBinding), "ERROR = " + ErrorDescription(errorCode));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave(nameof(QueryContextChannelBinding), LoggingHash.HashString(result));
- }
+ NetEventSource.Exit(null, result);
return result;
}
@@ -563,10 +420,7 @@ namespace System.Net
public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, out int errorCode)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter(nameof(QueryContextAttributes), contextAttribute.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute);
int nativeBlockSize = IntPtr.Size;
Type handleType = null;
@@ -627,10 +481,7 @@ namespace System.Net
errorCode = secModule.QueryContextAttributes(securityContext, contextAttribute, nativeBuffer, handleType, out sspiHandle);
if (errorCode != 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("Win32:QueryContextAttributes", "ERROR = " + ErrorDescription(errorCode));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
@@ -694,11 +545,7 @@ namespace System.Net
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave(nameof(QueryContextAttributes), LoggingHash.ObjectToString(attribute));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, attribute);
return attribute;
}
diff --git a/src/Common/src/Interop/Windows/sspicli/SecPkgContext_Sizes.cs b/src/Common/src/Interop/Windows/sspicli/SecPkgContext_Sizes.cs
index 7ad645cf1c..48cdd54d2a 100644
--- a/src/Common/src/Interop/Windows/sspicli/SecPkgContext_Sizes.cs
+++ b/src/Common/src/Interop/Windows/sspicli/SecPkgContext_Sizes.cs
@@ -31,12 +31,7 @@ namespace System.Net
}
catch (OverflowException)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecSizes::.ctor", "Negative size.");
- }
-
- Debug.Fail("SecSizes::.ctor", "Negative size.");
+ NetEventSource.Fail(this, "Negative size.");
throw;
}
}
diff --git a/src/Common/src/Interop/Windows/sspicli/SecPkgContext_StreamSizes.cs b/src/Common/src/Interop/Windows/sspicli/SecPkgContext_StreamSizes.cs
index 32f78a0b92..519b607da7 100644
--- a/src/Common/src/Interop/Windows/sspicli/SecPkgContext_StreamSizes.cs
+++ b/src/Common/src/Interop/Windows/sspicli/SecPkgContext_StreamSizes.cs
@@ -33,12 +33,7 @@ namespace System.Net
}
catch (OverflowException)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("StreamSizes::.ctor", "Negative size.");
- }
-
- Debug.Fail("StreamSizes::.ctor", "Negative size.");
+ NetEventSource.Fail(this, "Negative size.");
throw;
}
}
diff --git a/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs b/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs
index 04a0e9bda9..6d34e2cbe0 100644
--- a/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs
+++ b/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs
@@ -27,18 +27,12 @@ namespace System.Net
{
if (safeHandle.IsInvalid)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecurityPackageInfoClass::.ctor() the pointer is invalid: " + (safeHandle.DangerousGetHandle()).ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Invalid handle: {safeHandle}");
return;
}
IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecurityPackageInfoClass::.ctor() unmanagedPointer: " + ((long)unmanagedAddress).ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"unmanagedAddress: {unmanagedAddress}");
// TODO (Issue #3114): replace with Marshal.PtrToStructure.
Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Capabilities"));
@@ -52,26 +46,17 @@ namespace System.Net
if (unmanagedString != IntPtr.Zero)
{
Name = Marshal.PtrToStringUni(unmanagedString);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Name: " + Name);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Name: {Name}");
}
unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Comment"));
if (unmanagedString != IntPtr.Zero)
{
Comment = Marshal.PtrToStringUni(unmanagedString);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Comment: " + Comment);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Comment: {Comment}");
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecurityPackageInfoClass::.ctor(): " + ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, this.ToString());
}
public override string ToString()
diff --git a/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs b/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs
index 478536feb0..26628bcefb 100644
--- a/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs
+++ b/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs
@@ -226,13 +226,7 @@ namespace System.Net.Security
ref Interop.SspiCli.SEC_WINNT_AUTH_IDENTITY_W authdata,
out SafeFreeCredentials outCredential)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#1("
- + package + ", "
- + intent + ", "
- + authdata + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata);
int errorCode = -1;
long timeStamp;
@@ -250,12 +244,7 @@ namespace System.Net.Security
ref outCredential._handle,
out timeStamp);
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
- + String.Format("{0:x}", errorCode)
- + ", handle = " + outCredential.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle:{outCredential}");
#endif
if (errorCode != 0)
@@ -271,12 +260,7 @@ namespace System.Net.Security
Interop.SspiCli.CredentialUse intent,
out SafeFreeCredentials outCredential)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeFreeCredentials::AcquireDefaultCredential("
- + package + ", "
- + intent + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent);
int errorCode = -1;
long timeStamp;
@@ -295,12 +279,7 @@ namespace System.Net.Security
out timeStamp);
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
- + errorCode.ToString("x")
- + ", handle = " + outCredential.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}");
#endif
if (errorCode != 0)
@@ -346,13 +325,7 @@ namespace System.Net.Security
ref Interop.SspiCli.SCHANNEL_CRED authdata,
out SafeFreeCredentials outCredential)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#2("
- + package + ", "
- + intent + ", "
- + authdata + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata);
int errorCode = -1;
long timeStamp;
@@ -388,12 +361,7 @@ namespace System.Net.Security
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x"
- + errorCode.ToString("x")
- + ", handle = " + outCredential.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}");
#endif
if (errorCode != 0)
@@ -524,43 +492,27 @@ namespace System.Net.Security
ref Interop.SspiCli.ContextFlags outFlags)
{
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Enter("SafeDeleteContext::InitializeSecurityContext");
- GlobalLog.Print(" credential = " + inCredentials.ToString());
- GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
- GlobalLog.Print(" targetName = " + targetName);
- GlobalLog.Print(" inFlags = " + inFlags);
- GlobalLog.Print(" reservedI = 0x0");
- GlobalLog.Print(" endianness = " + endianness);
-
+ NetEventSource.Enter(null, $"credential:{inCredentials}, crefContext:{refContext}, targetName:{targetName}, inFlags:{inFlags}, endianness:{endianness}");
if (inSecBuffers == null)
{
- GlobalLog.Print(" inSecBuffers = (null)");
+ NetEventSource.Info(null, $"inSecBuffers = (null)");
}
else
{
- GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
+ NetEventSource.Info(null, $"inSecBuffers = {inSecBuffers}");
}
}
#endif
+
if (outSecBuffer == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null");
- }
-
- Debug.Fail("SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null");
+ NetEventSource.Fail(null, "outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null");
- }
-
- Debug.Fail("SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null");
+ NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null");
}
if (inCredentials == null)
@@ -633,10 +585,7 @@ namespace System.Net.Security
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}");
#endif
}
}
@@ -688,11 +637,8 @@ namespace System.Net.Security
outFreeContextBuffer);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeDeleteContext:InitializeSecurityContext Marshalling OUT buffer");
- }
-
+ NetEventSource.Info(null, "Marshalling OUT buffer");
+
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer;
outSecBuffer.type = outUnmanagedBuffer[0].BufferType;
@@ -731,11 +677,7 @@ namespace System.Net.Security
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SafeDeleteContext::InitializeSecurityContext() unmanaged InitializeSecurityContext()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
@@ -838,41 +780,27 @@ namespace System.Net.Security
ref Interop.SspiCli.ContextFlags outFlags)
{
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex");
- GlobalLog.Print(" credential = " + inCredentials.ToString());
- GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
-
- GlobalLog.Print(" inFlags = " + inFlags);
-
+ NetEventSource.Enter(null, $"credential={inCredentials}, refContext={refContext}, inFlags={inFlags}");
if (inSecBuffers == null)
{
- GlobalLog.Print(" inSecBuffers = (null)");
+ NetEventSource.Info(null, "inSecBuffers = (null)");
}
else
{
- GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
+ NetEventSource.Info(null, $"inSecBuffers[] = (inSecBuffers)");
}
}
#endif
+
if (outSecBuffer == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
- }
-
- Debug.Fail("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
+ NetEventSource.Fail(null, "outSecBuffer != null");
}
if (inSecBuffer != null && inSecBuffers != null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");
- }
-
- Debug.Fail("SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");
+ NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null");
}
if (inCredentials == null)
@@ -945,10 +873,7 @@ namespace System.Net.Security
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}");
#endif
}
}
@@ -993,10 +918,7 @@ namespace System.Net.Security
ref outFlags,
outFreeContextBuffer);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext Marshalling OUT buffer");
- }
+ NetEventSource.Info(null, "Marshaling OUT buffer");
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer;
@@ -1037,11 +959,7 @@ namespace System.Net.Security
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
@@ -1133,22 +1051,15 @@ namespace System.Net.Security
ref SafeDeleteContext refContext,
SecurityBuffer[] inSecBuffers)
{
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Enter("SafeDeleteContext::CompleteAuthToken");
- GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
-#if TRACE_VERBOSE
- GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
-#endif
+ NetEventSource.Enter(null, "SafeDeleteContext::CompleteAuthToken");
+ NetEventSource.Info(null, $" refContext = {refContext}");
+ NetEventSource.Info(null, $" inSecBuffers[] = {inSecBuffers}");
}
if (inSecBuffers == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null");
- }
-
- Debug.Fail("SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null");
+ NetEventSource.Fail(null, "inSecBuffers == null");
}
var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length);
@@ -1188,10 +1099,7 @@ namespace System.Net.Security
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType: {securityBuffer.type}");
#endif
}
}
@@ -1234,11 +1142,7 @@ namespace System.Net.Security
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SafeDeleteContext::CompleteAuthToken() unmanaged CompleteAuthToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}");
return errorCode;
}
@@ -1246,23 +1150,16 @@ namespace System.Net.Security
ref SafeDeleteContext refContext,
SecurityBuffer[] inSecBuffers)
{
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Enter("SafeDeleteContext::ApplyControlToken");
- GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext));
-#if TRACE_VERBOSE
- GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length);
-#endif
+ NetEventSource.Enter(null);
+ NetEventSource.Info(null, $" refContext = {refContext}");
+ NetEventSource.Info(null, $" inSecBuffers[] = length:{inSecBuffers.Length}");
}
if (inSecBuffers == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeDeleteContext::ApplyControlToken()|inSecBuffers == null");
- }
-
- Debug.Fail("SafeDeleteContext::ApplyControlToken()|inSecBuffers == null");
+ NetEventSource.Fail(null, "inSecBuffers == null");
}
var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length);
@@ -1302,10 +1199,7 @@ namespace System.Net.Security
inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}");
#endif
}
}
@@ -1351,11 +1245,7 @@ namespace System.Net.Security
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SafeDeleteContext::ApplyControlToken() unmanaged ApplyControlToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}");
return errorCode;
}
}
diff --git a/src/Common/src/System/Net/ContextAwareResult.Windows.cs b/src/Common/src/System/Net/ContextAwareResult.Windows.cs
index f27ffb5751..9a25cccc98 100644
--- a/src/Common/src/System/Net/ContextAwareResult.Windows.cs
+++ b/src/Common/src/System/Net/ContextAwareResult.Windows.cs
@@ -28,12 +28,7 @@ namespace System.Net
{
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::Identity|Called on completed result.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::Identity |Called on completed result.");
+ NetEventSource.Fail(this, "Called on completed result.");
}
throw new InvalidOperationException(SR.net_completed_result);
@@ -47,12 +42,7 @@ namespace System.Net
// Make sure the identity was requested.
if ((_flags & StateFlags.CaptureIdentity) == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::Identity|No identity captured - specify captureIdentity.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::Identity |No identity captured - specify captureIdentity.");
+ NetEventSource.Fail(this, "No identity captured - specify captureIdentity.");
}
// Just use the lock to block. We might be on the thread that owns the lock which is great, it means we
@@ -61,12 +51,7 @@ namespace System.Net
{
if (_lock == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::Identity|Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling Identity (unless it's only called after FinishPostingAsyncOp).", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::Identity |Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling Identity (unless it's only called after FinishPostingAsyncOp).");
+ NetEventSource.Fail(this, "Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling Identity (unless it's only called after FinishPostingAsyncOp).");
}
lock (_lock) { }
@@ -76,12 +61,7 @@ namespace System.Net
{
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::Identity|Result became completed during call.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::Identity |Result became completed during call.");
+ NetEventSource.Fail(this, "Result became completed during call.");
}
throw new InvalidOperationException(SR.net_completed_result);
diff --git a/src/Common/src/System/Net/ContextAwareResult.cs b/src/Common/src/System/Net/ContextAwareResult.cs
index af9ad42a5e..4f761aff5a 100644
--- a/src/Common/src/System/Net/ContextAwareResult.cs
+++ b/src/Common/src/System/Net/ContextAwareResult.cs
@@ -134,12 +134,7 @@ namespace System.Net
{
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::ContextCopy|Called on completed result.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::ContextCopy |Called on completed result.");
+ NetEventSource.Fail(this, "Called on completed result.");
}
throw new InvalidOperationException(SR.net_completed_result);
@@ -154,12 +149,7 @@ namespace System.Net
// Make sure the context was requested.
if (AsyncCallback == null && (_flags & StateFlags.CaptureContext) == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::ContextCopy|No context captured - specify a callback or forceCaptureContext.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::ContextCopy |No context captured - specify a callback or forceCaptureContext.");
+ NetEventSource.Fail(this, "No context captured - specify a callback or forceCaptureContext.");
}
// Just use the lock to block. We might be on the thread that owns the lock which is great, it means we
@@ -168,12 +158,7 @@ namespace System.Net
{
if (_lock == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::ContextCopy|Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp).", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::ContextCopy |Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp).");
+ NetEventSource.Fail(this, "Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp).");
}
lock (_lock) { }
}
@@ -182,12 +167,7 @@ namespace System.Net
{
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::ContextCopy|Result became completed during call.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::ContextCopy |Result became completed during call.");
+ NetEventSource.Fail(this, "Result became completed during call.");
}
throw new InvalidOperationException(SR.net_completed_result);
@@ -221,12 +201,7 @@ namespace System.Net
{
if (InternalPeekCompleted)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::StartPostingAsyncOp|Called on completed result.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::StartPostingAsyncOp |Called on completed result.");
+ NetEventSource.Fail(this, "Called on completed result.");
}
DebugProtectState(true);
@@ -301,12 +276,7 @@ namespace System.Net
protected override void Cleanup()
{
base.Cleanup();
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::Cleanup()");
- }
-
+ NetEventSource.Info(this);
CleanupInternal();
}
@@ -319,12 +289,7 @@ namespace System.Net
{
if ((_flags & StateFlags.PostBlockStarted) == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::CaptureOrComplete|Called without calling StartPostingAsyncOp.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::CaptureOrComplete |Called without calling StartPostingAsyncOp.");
+ NetEventSource.Fail(this, "Called without calling StartPostingAsyncOp.");
}
// See if we're going to need to capture the context.
@@ -335,11 +300,7 @@ namespace System.Net
// capturing the context won't be sufficient.
if ((_flags & StateFlags.CaptureIdentity) != 0 && !InternalPeekCompleted && (!capturingContext))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::CaptureOrComplete() starting identity capture");
- }
-
+ NetEventSource.Info(this, "starting identity capture");
SafeCaptureIdentity();
}
@@ -347,10 +308,7 @@ namespace System.Net
// Note that Capture() can return null, for example if SuppressFlow() is in effect.
if (capturingContext && !InternalPeekCompleted)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::CaptureOrComplete() starting capture");
- }
+ NetEventSource.Info(this, "starting capture");
if (cachedContext == null)
{
@@ -370,28 +328,17 @@ namespace System.Net
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::CaptureOrComplete() _Context:" + LoggingHash.HashString(_context));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context:{_context}");
}
else
{
// Otherwise we have to have completed synchronously, or not needed the context.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::CaptureOrComplete() skipping capture");
- }
+ NetEventSource.Info(this, "Skipping capture");
cachedContext = null;
if (AsyncCallback != null && !CompletedSynchronously)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ContextAwareResult#{0}::CaptureOrComplete|Didn't capture context, but didn't complete synchronously!", LoggingHash.HashString(this));
- }
-
- Debug.Fail("ContextAwareResult#" + LoggingHash.HashString(this) + "::CaptureOrComplete |Didn't capture context, but didn't complete synchronously!");
+ NetEventSource.Fail(this, "Didn't capture context, but didn't complete synchronously!");
}
}
@@ -402,11 +349,7 @@ namespace System.Net
DebugProtectState(false);
if (CompletedSynchronously)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::CaptureOrComplete() completing synchronously");
- }
-
+ NetEventSource.Info(this, "Completing synchronously");
base.Complete(IntPtr.Zero);
return true;
}
@@ -417,10 +360,7 @@ namespace System.Net
// This method is guaranteed to be called only once. If called with a non-zero userToken, the context is not flowed.
protected override void Complete(IntPtr userToken)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::Complete() _Context(set):" + (_context != null).ToString() + " userToken:" + userToken.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context(set):{_context != null} userToken:{userToken}");
// If no flowing, just complete regularly.
if ((_flags & StateFlags.PostBlockStarted) == 0)
@@ -452,11 +392,7 @@ namespace System.Net
private void CompleteCallback()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::CompleteCallback() Context set, calling callback.");
- }
-
+ NetEventSource.Info(this, "Context set, calling callback.");
base.Complete(IntPtr.Zero);
}
}
diff --git a/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs b/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs
index c58b6c4a3d..309d230de2 100644
--- a/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs
+++ b/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs
@@ -23,10 +23,7 @@ namespace System.Net
private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Creating SafeHandle, type = " + this.GetType().FullName);
- }
+ NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
@@ -35,11 +32,8 @@ namespace System.Net
~DebugCriticalHandleMinusOneIsInvalid()
{
- GlobalLog.SetThreadSource(ThreadKinds.Finalization);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(_trace);
- }
+ DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
+ NetEventSource.Info(this, _trace);
}
}
#endif // DEBUG
diff --git a/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs b/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs
index 7c63173760..3037f223bd 100644
--- a/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs
+++ b/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs
@@ -23,10 +23,7 @@ namespace System.Net
private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Creating SafeHandle, type = " + this.GetType().FullName);
- }
+ NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
@@ -35,11 +32,8 @@ namespace System.Net
~DebugCriticalHandleZeroOrMinusOneIsInvalid()
{
- GlobalLog.SetThreadSource(ThreadKinds.Finalization);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(_trace);
- }
+ DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
+ NetEventSource.Info(this, _trace);
}
}
#endif // DEBUG
diff --git a/src/Common/src/System/Net/DebugSafeHandle.cs b/src/Common/src/System/Net/DebugSafeHandle.cs
index bf9f494a8d..775e1d953c 100644
--- a/src/Common/src/System/Net/DebugSafeHandle.cs
+++ b/src/Common/src/System/Net/DebugSafeHandle.cs
@@ -43,11 +43,8 @@ namespace System.Net
~DebugSafeHandle()
{
- GlobalLog.SetThreadSource(ThreadKinds.Finalization);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(_trace);
- }
+ DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
+ NetEventSource.Info(this, _trace);
}
}
#endif // DEBUG
diff --git a/src/Common/src/System/Net/DebugSafeHandleMinusOneIsInvalid.cs b/src/Common/src/System/Net/DebugSafeHandleMinusOneIsInvalid.cs
index 000d613ea9..8dd7ab2bf5 100644
--- a/src/Common/src/System/Net/DebugSafeHandleMinusOneIsInvalid.cs
+++ b/src/Common/src/System/Net/DebugSafeHandleMinusOneIsInvalid.cs
@@ -29,10 +29,7 @@ namespace System.Net
private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Creating SafeHandle, type = " + this.GetType().FullName);
- }
+ NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
@@ -41,11 +38,8 @@ namespace System.Net
~DebugSafeHandleMinusOneIsInvalid()
{
- GlobalLog.SetThreadSource(ThreadKinds.Finalization);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(_trace);
- }
+ DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
+ NetEventSource.Info(this, _trace);
}
}
#endif // DEBUG
diff --git a/src/Common/src/System/Net/InternalException.cs b/src/Common/src/System/Net/InternalException.cs
index 7af0ee21ba..c86e808a57 100644
--- a/src/Common/src/System/Net/InternalException.cs
+++ b/src/Common/src/System/Net/InternalException.cs
@@ -2,20 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Diagnostics;
-
namespace System.Net
{
internal class InternalException : Exception
{
internal InternalException()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("InternalException thrown.");
- }
-
- Debug.Fail("InternalException thrown.");
+ NetEventSource.Fail(this, "InternalException thrown.");
}
}
}
diff --git a/src/Common/src/System/Net/LazyAsyncResult.cs b/src/Common/src/System/Net/LazyAsyncResult.cs
index 70fb8f67d0..2e039e7437 100644
--- a/src/Common/src/System/Net/LazyAsyncResult.cs
+++ b/src/Common/src/System/Net/LazyAsyncResult.cs
@@ -64,10 +64,7 @@ namespace System.Net
_asyncState = myState;
_asyncCallback = myCallBack;
_result = DBNull.Value;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor()");
- }
+ NetEventSource.Info(this);
}
// Allows creating a pre-completed result with less interlockeds. Beware! Constructor calls the callback.
@@ -76,12 +73,7 @@ namespace System.Net
{
if (result == DBNull.Value)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("LazyAsyncResult#{0}::.ctor()|Result can't be set to DBNull - it's a special internal value.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor()|Result can't be set to DBNull - it's a special internal value.");
+ NetEventSource.Fail(this, "Result can't be set to DBNull - it's a special internal value.");
}
_asyncObject = myObject;
@@ -92,21 +84,15 @@ namespace System.Net
if (_asyncCallback != null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() invoking callback");
- }
+ NetEventSource.Info(this, "Invoking callback");
_asyncCallback(this);
}
- else if (GlobalLog.IsEnabled)
+ else
{
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() no callback to invoke");
+ NetEventSource.Info(this, "No callback to invoke");
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor() (pre-completed)");
- }
+ NetEventSource.Info(this, "(pre-completed)");
}
// Interface method to return the original async object.
@@ -150,10 +136,7 @@ namespace System.Net
{
get
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_AsyncWaitHandle()");
- }
+ NetEventSource.Enter(this);
#if DEBUG
// Can't be called when state is protected.
@@ -184,11 +167,7 @@ namespace System.Net
LazilyCreateEvent(out asyncEvent);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_AsyncWaitHandle() _event:" + LoggingHash.HashString(_event));
- }
-
+ NetEventSource.Exit(this, asyncEvent);
return asyncEvent;
}
}
@@ -247,10 +226,7 @@ namespace System.Net
{
get
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_CompletedSynchronously()");
- }
+ NetEventSource.Enter(this);
#if DEBUG
// Can't be called when state is protected.
@@ -267,11 +243,7 @@ namespace System.Net
result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_CompletedSynchronously() returns: " + ((result > 0) ? "true" : "false"));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result > 0);
return result > 0;
}
}
@@ -281,10 +253,7 @@ namespace System.Net
{
get
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_IsCompleted()");
- }
+ NetEventSource.Enter(this);
#if DEBUG
// Can't be called when state is protected.
@@ -333,22 +302,12 @@ namespace System.Net
// It's an error to call after the result has been completed or with DBNull.
if (value == DBNull.Value)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("LazyAsyncResult#{0}::set_Result()|Result can't be set to DBNull - it's a special internal value.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("LazyAsyncResult#" + LoggingHash.HashString(this) + "::set_Result()|Result can't be set to DBNull - it's a special internal value.");
+ NetEventSource.Fail(this, "Result can't be set to DBNull - it's a special internal value.");
}
if (InternalPeekCompleted)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("LazyAsyncResult#{0}::set_Result()|Called on completed result.", LoggingHash.HashString(this));
- }
-
- Debug.Fail("LazyAsyncResult#" + LoggingHash.HashString(this) + "::set_Result()|Called on completed result.");
+ NetEventSource.Fail(this, "Called on completed result.");
}
_result = value;
}
@@ -385,12 +344,7 @@ namespace System.Net
// the equivalent of InvokeCallback().
protected void ProtectedInvokeCallback(object result, IntPtr userToken)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::ProtectedInvokeCallback() result = " +
- (result is Exception ? ((Exception)result).Message : result == null ? "<null>" : result.ToString()) +
- ", userToken:" + userToken.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, result, userToken);
// Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion.
if (result == DBNull.Value)
@@ -455,17 +409,11 @@ namespace System.Net
++threadContext._nestedIOCount;
if (_asyncCallback != null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() invoking callback");
- }
+ NetEventSource.Info(this, "Invoking callback");
if (threadContext._nestedIOCount >= ForceAsyncCount)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult::Complete *** OFFLOADED the user callback ***");
- }
+ NetEventSource.Info(this, "*** OFFLOADED the user callback ****");
Task.Factory.StartNew(
s => WorkerThreadComplete(s),
@@ -481,9 +429,9 @@ namespace System.Net
_asyncCallback(this);
}
}
- else if (GlobalLog.IsEnabled)
+ else
{
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() no callback to invoke");
+ NetEventSource.Info(this, "No callback to invoke");
}
}
finally
@@ -546,11 +494,7 @@ namespace System.Net
{
try
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() Waiting for completion _event#" + LoggingHash.HashString(waitHandle));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Waiting for completion event {waitHandle}");
waitHandle.WaitOne(Timeout.Infinite);
}
catch (ObjectDisposedException)
@@ -585,12 +529,7 @@ namespace System.Net
sw.SpinOnce();
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() done: " +
- (_result is Exception ? ((Exception)_result).Message : _result == null ? "<null>" : _result.ToString()));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _result);
return _result;
}
diff --git a/src/Common/src/System/Net/Logging/DebugThreadTracking.cs b/src/Common/src/System/Net/Logging/DebugThreadTracking.cs
new file mode 100644
index 0000000000..6fe235b35a
--- /dev/null
+++ b/src/Common/src/System/Net/Logging/DebugThreadTracking.cs
@@ -0,0 +1,184 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Globalization;
+
+namespace System.Net
+{
+ internal static class DebugThreadTracking
+ {
+ [ThreadStatic]
+ private static Stack<ThreadKinds> t_threadKindStack;
+
+ private static Stack<ThreadKinds> ThreadKindStack => t_threadKindStack ?? (t_threadKindStack = new Stack<ThreadKinds>());
+
+ internal static ThreadKinds CurrentThreadKind => ThreadKindStack.Count > 0 ? ThreadKindStack.Peek() : ThreadKinds.Other;
+
+ internal static IDisposable SetThreadKind(ThreadKinds kind)
+ {
+ if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown)
+ {
+ throw new InternalException();
+ }
+
+ // Ignore during shutdown.
+ if (Environment.HasShutdownStarted)
+ {
+ return null;
+ }
+
+ ThreadKinds threadKind = CurrentThreadKind;
+ ThreadKinds source = threadKind & ThreadKinds.SourceMask;
+
+ // Special warnings when doing dangerous things on a thread.
+ if ((threadKind & ThreadKinds.User) != 0 && (kind & ThreadKinds.System) != 0)
+ {
+ NetEventSource.Error(null, "Thread changed from User to System; user's thread shouldn't be hijacked.");
+ }
+
+ if ((threadKind & ThreadKinds.Async) != 0 && (kind & ThreadKinds.Sync) != 0)
+ {
+ NetEventSource.Error(null, "Thread changed from Async to Sync, may block an Async thread.");
+ }
+ else if ((threadKind & (ThreadKinds.Other | ThreadKinds.CompletionPort)) == 0 && (kind & ThreadKinds.Sync) != 0)
+ {
+ NetEventSource.Error(null, "Thread from a limited resource changed to Sync, may deadlock or bottleneck.");
+ }
+
+ ThreadKindStack.Push(
+ (((kind & ThreadKinds.OwnerMask) == 0 ? threadKind : kind) & ThreadKinds.OwnerMask) |
+ (((kind & ThreadKinds.SyncMask) == 0 ? threadKind : kind) & ThreadKinds.SyncMask) |
+ (kind & ~(ThreadKinds.OwnerMask | ThreadKinds.SyncMask)) |
+ source);
+
+ if (CurrentThreadKind != threadKind)
+ {
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Thread becomes:({CurrentThreadKind})");
+ }
+
+ return new ThreadKindFrame();
+ }
+
+ private class ThreadKindFrame : IDisposable
+ {
+ private readonly int _frameNumber;
+
+ internal ThreadKindFrame()
+ {
+ _frameNumber = ThreadKindStack.Count;
+ }
+
+ void IDisposable.Dispose()
+ {
+ // Ignore during shutdown.
+ if (Environment.HasShutdownStarted)
+ {
+ return;
+ }
+
+ if (_frameNumber != ThreadKindStack.Count)
+ {
+ throw new InternalException();
+ }
+
+ ThreadKinds previous = ThreadKindStack.Pop();
+
+ if (CurrentThreadKind != previous && NetEventSource.IsEnabled)
+ {
+ NetEventSource.Info(this, $"Thread reverts:({CurrentThreadKind})");
+ }
+ }
+ }
+
+ internal static void SetThreadSource(ThreadKinds source)
+ {
+ if ((source & ThreadKinds.SourceMask) != source || source == ThreadKinds.Unknown)
+ {
+ throw new ArgumentException("Must specify the thread source.", nameof(source));
+ }
+
+ if (ThreadKindStack.Count == 0)
+ {
+ ThreadKindStack.Push(source);
+ return;
+ }
+
+ if (ThreadKindStack.Count > 1)
+ {
+ NetEventSource.Error(null, "SetThreadSource must be called at the base of the stack, or the stack has been corrupted.");
+ while (ThreadKindStack.Count > 1)
+ {
+ ThreadKindStack.Pop();
+ }
+ }
+
+ if (ThreadKindStack.Peek() != source)
+ {
+ NetEventSource.Error(null, "The stack has been corrupted.");
+ ThreadKinds last = ThreadKindStack.Pop() & ThreadKinds.SourceMask;
+ if (last != source && last != ThreadKinds.Other && NetEventSource.IsEnabled)
+ {
+ NetEventSource.Fail(null, $"Thread source changed.|Was:({last}) Now:({source})");
+ }
+ ThreadKindStack.Push(source);
+ }
+ }
+
+ internal static void ThreadContract(ThreadKinds kind, string errorMsg)
+ {
+ ThreadContract(kind, ThreadKinds.SafeSources, errorMsg);
+ }
+
+ internal static void ThreadContract(ThreadKinds kind, ThreadKinds allowedSources, string errorMsg)
+ {
+ if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown || (allowedSources & ThreadKinds.SourceMask) != allowedSources)
+ {
+ throw new InternalException();
+ }
+
+ if (NetEventSource.IsEnabled)
+ {
+ ThreadKinds threadKind = CurrentThreadKind;
+ if ((threadKind & allowedSources) != 0)
+ {
+ NetEventSource.Fail(null, $"Thread Contract Violation.|Expected source:({allowedSources}) Actual source:({threadKind & ThreadKinds.SourceMask})");
+ }
+ if ((threadKind & kind) == kind)
+ {
+ NetEventSource.Fail(null, $"Thread Contract Violation.|Expected kind:({kind}) Actual kind:({threadKind & ~ThreadKinds.SourceMask})");
+ }
+ }
+ }
+ }
+
+ [Flags]
+ internal enum ThreadKinds
+ {
+ Unknown = 0x0000,
+
+ // Mutually exclusive.
+ User = 0x0001, // Thread has entered via an API.
+ System = 0x0002, // Thread has entered via a system callback (e.g. completion port) or is our own thread.
+
+ // Mutually exclusive.
+ Sync = 0x0004, // Thread should block.
+ Async = 0x0008, // Thread should not block.
+
+ // Mutually exclusive, not always known for a user thread. Never changes.
+ Timer = 0x0010, // Thread is the timer thread. (Can't call user code.)
+ CompletionPort = 0x0020, // Thread is a ThreadPool completion-port thread.
+ Worker = 0x0040, // Thread is a ThreadPool worker thread.
+ Finalization = 0x0080, // Thread is the finalization thread.
+ Other = 0x0100, // Unknown source.
+
+ OwnerMask = User | System,
+ SyncMask = Sync | Async,
+ SourceMask = Timer | CompletionPort | Worker | Finalization | Other,
+
+ // Useful "macros"
+ SafeSources = SourceMask & ~(Timer | Finalization), // Methods that "unsafe" sources can call must be explicitly marked.
+ ThreadPool = CompletionPort | Worker, // Like Thread.CurrentThread.IsThreadPoolThread
+ }
+}
diff --git a/src/Common/src/System/Net/Logging/EventSourceLogging.cs b/src/Common/src/System/Net/Logging/EventSourceLogging.cs
deleted file mode 100644
index 6e1bb042fc..0000000000
--- a/src/Common/src/System/Net/Logging/EventSourceLogging.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-
-namespace System.Net
-{
- [EventSource(Name = "Microsoft-System-Net-Debug")]
- internal class EventSourceLogging : EventSource
- {
- private static readonly EventSourceLogging s_log = new EventSourceLogging();
-
- private EventSourceLogging() { }
-
- public static EventSourceLogging Log
- {
- get
- {
- return s_log;
- }
- }
-
- [Event(1, Keywords = Keywords.Default)]
- public void DebugMessage(string message)
- {
- WriteEvent(1, message);
- }
-
- [Event(2, Keywords = Keywords.Debug)]
- public void DebugDumpArray(byte[] bufferSegmentArray)
- {
- WriteEvent(2, bufferSegmentArray);
- }
-
- [Event(3, Keywords = Keywords.Debug, Level = EventLevel.Warning)]
- public void WarningDumpArray(string message)
- {
- WriteEvent(3, message);
- }
-
- [Event(4, Keywords = Keywords.FunctionEntryExit, Message = "{0}({1})")]
- public void FunctionStart(string functionName, string parameters = "*none*")
- {
- WriteEvent(4, functionName, parameters);
- }
-
- [Event(5, Keywords = Keywords.FunctionEntryExit, Message = "{0} returns {1}")]
- public void FunctionStop(string functionName, string result = "")
- {
- WriteEvent(5, functionName, result);
- }
-
- [Event(6, Keywords = Keywords.Default, Level = EventLevel.Warning)]
- public void WarningMessage(string message)
- {
- WriteEvent(6, message);
- }
-
- [Event(7, Keywords = Keywords.Default, Level = EventLevel.Critical)]
- public void AssertFailed(string message, string detailMessage)
- {
- WriteEvent(7, message, detailMessage);
- }
-
- [Event(8, Keywords = Keywords.Default, Level = EventLevel.Critical)]
- public void CriticalMessage(string message, string detailMessage)
- {
- WriteEvent(8, message, detailMessage);
- }
-
- public static class Keywords
- {
- public const EventKeywords Default = (EventKeywords)0x0001;
- public const EventKeywords Debug = (EventKeywords)0x0002;
- public const EventKeywords FunctionEntryExit = (EventKeywords)0x0004;
- }
- }
-}
diff --git a/src/Common/src/System/Net/Logging/GlobalLog.cs b/src/Common/src/System/Net/Logging/GlobalLog.cs
deleted file mode 100644
index 4022783d44..0000000000
--- a/src/Common/src/System/Net/Logging/GlobalLog.cs
+++ /dev/null
@@ -1,304 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Globalization;
-
-namespace System.Net
-{
- internal static class GlobalLog
- {
- [ThreadStatic]
- private static Stack<ThreadKinds> t_threadKindStack;
-
- private static Stack<ThreadKinds> ThreadKindStack
- {
- get
- {
- if (t_threadKindStack == null)
- {
- t_threadKindStack = new Stack<ThreadKinds>();
- }
-
- return t_threadKindStack;
- }
- }
-
- internal static ThreadKinds CurrentThreadKind
- {
- get
- {
- return ThreadKindStack.Count > 0 ? ThreadKindStack.Peek() : ThreadKinds.Other;
- }
- }
-
- internal static IDisposable SetThreadKind(ThreadKinds kind)
- {
- if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown)
- {
- throw new InternalException();
- }
-
- // Ignore during shutdown.
- if (Environment.HasShutdownStarted)
- {
- return null;
- }
-
- ThreadKinds threadKind = CurrentThreadKind;
- ThreadKinds source = threadKind & ThreadKinds.SourceMask;
-
- // Special warnings when doing dangerous things on a thread.
- if ((threadKind & ThreadKinds.User) != 0 && (kind & ThreadKinds.System) != 0)
- {
- EventSourceLogging.Log.WarningMessage("Thread changed from User to System; user's thread shouldn't be hijacked.");
- }
-
- if ((threadKind & ThreadKinds.Async) != 0 && (kind & ThreadKinds.Sync) != 0)
- {
- EventSourceLogging.Log.WarningMessage("Thread changed from Async to Sync, may block an Async thread.");
- }
- else if ((threadKind & (ThreadKinds.Other | ThreadKinds.CompletionPort)) == 0 && (kind & ThreadKinds.Sync) != 0)
- {
- EventSourceLogging.Log.WarningMessage("Thread from a limited resource changed to Sync, may deadlock or bottleneck.");
- }
-
- ThreadKindStack.Push(
- (((kind & ThreadKinds.OwnerMask) == 0 ? threadKind : kind) & ThreadKinds.OwnerMask) |
- (((kind & ThreadKinds.SyncMask) == 0 ? threadKind : kind) & ThreadKinds.SyncMask) |
- (kind & ~(ThreadKinds.OwnerMask | ThreadKinds.SyncMask)) |
- source);
-
- if (CurrentThreadKind != threadKind && IsEnabled)
- {
- Print("Thread becomes:(" + CurrentThreadKind.ToString() + ")");
- }
-
- return new ThreadKindFrame();
- }
-
- private class ThreadKindFrame : IDisposable
- {
- private readonly int _frameNumber;
-
- internal ThreadKindFrame()
- {
- _frameNumber = ThreadKindStack.Count;
- }
-
- void IDisposable.Dispose()
- {
- // Ignore during shutdown.
- if (Environment.HasShutdownStarted)
- {
- return;
- }
-
- if (_frameNumber != ThreadKindStack.Count)
- {
- throw new InternalException();
- }
-
- ThreadKinds previous = ThreadKindStack.Pop();
-
- if (CurrentThreadKind != previous && IsEnabled)
- {
- Print("Thread reverts:(" + CurrentThreadKind.ToString() + ")");
- }
- }
- }
-
- internal static void SetThreadSource(ThreadKinds source)
- {
- if ((source & ThreadKinds.SourceMask) != source || source == ThreadKinds.Unknown)
- {
- throw new ArgumentException("Must specify the thread source.", nameof(source));
- }
-
- if (ThreadKindStack.Count == 0)
- {
- ThreadKindStack.Push(source);
- return;
- }
-
- if (ThreadKindStack.Count > 1)
- {
- EventSourceLogging.Log.WarningMessage("SetThreadSource must be called at the base of the stack, or the stack has been corrupted.");
- while (ThreadKindStack.Count > 1)
- {
- ThreadKindStack.Pop();
- }
- }
-
- if (ThreadKindStack.Peek() != source)
- {
- EventSourceLogging.Log.WarningMessage("The stack has been corrupted.");
- ThreadKinds last = ThreadKindStack.Pop() & ThreadKinds.SourceMask;
- if (last != source && last != ThreadKinds.Other && IsEnabled)
- {
- AssertFormat("Thread source changed.|Was:({0}) Now:({1})", last, source);
- }
- ThreadKindStack.Push(source);
- }
- }
-
- internal static void ThreadContract(ThreadKinds kind, string errorMsg)
- {
- ThreadContract(kind, ThreadKinds.SafeSources, errorMsg);
- }
-
- internal static void ThreadContract(ThreadKinds kind, ThreadKinds allowedSources, string errorMsg)
- {
- if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown || (allowedSources & ThreadKinds.SourceMask) != allowedSources)
- {
- throw new InternalException();
- }
-
- if (IsEnabled)
- {
- ThreadKinds threadKind = CurrentThreadKind;
- if ((threadKind & allowedSources) != 0)
- {
- AssertFormat(errorMsg, "Thread Contract Violation.|Expected source:({0}) Actual source:({1})", allowedSources, threadKind & ThreadKinds.SourceMask);
- }
- if ((threadKind & kind) == kind)
- {
- AssertFormat(errorMsg, "Thread Contract Violation.|Expected kind:({0}) Actual kind:({1})", kind, threadKind & ~ThreadKinds.SourceMask);
- }
- }
- }
-
- public static void Print(string msg)
- {
- EventSourceLogging.Log.DebugMessage(msg);
- }
-
- public static void Enter(string functionName)
- {
- EventSourceLogging.Log.FunctionStart(functionName);
- }
-
- public static void Enter(string functionName, string parameters)
- {
- EventSourceLogging.Log.FunctionStart(functionName, parameters);
- }
-
- public static void AssertFormat(string messageFormat, params object[] data)
- {
- string fullMessage = string.Format(CultureInfo.InvariantCulture, messageFormat, data);
- int pipeIndex = fullMessage.IndexOf('|');
- if (pipeIndex == -1)
- {
- Assert(fullMessage);
- }
- else
- {
- int detailLength = fullMessage.Length - pipeIndex - 1;
- Assert(fullMessage.Substring(0, pipeIndex), detailLength > 0 ? fullMessage.Substring(pipeIndex + 1, detailLength) : null);
- }
- }
-
- public static void AssertFormat(bool condition, string messageFormat, params object[] data)
- {
- if (condition)
- {
- string fullMessage = string.Format(CultureInfo.InvariantCulture, messageFormat, data);
- int pipeIndex = fullMessage.IndexOf('|');
- if (pipeIndex == -1)
- {
- Assert(fullMessage);
- }
- else
- {
- int detailLength = fullMessage.Length - pipeIndex - 1;
- Assert(fullMessage.Substring(0, pipeIndex), detailLength > 0 ? fullMessage.Substring(pipeIndex + 1, detailLength) : null);
- }
- }
- }
-
- public static void Assert(string message)
- {
- Assert(message, null);
- }
-
- public static void Assert(string message, string detailMessage)
- {
- EventSourceLogging.Log.AssertFailed(message, detailMessage);
- }
-
- public static void Leave(string functionName)
- {
- EventSourceLogging.Log.FunctionStop(functionName);
- }
-
- public static void Leave(string functionName, string result)
- {
- EventSourceLogging.Log.FunctionStop(functionName, result);
- }
-
- public static void Leave(string functionName, int returnval)
- {
- EventSourceLogging.Log.FunctionStop(functionName, returnval.ToString());
- }
-
- public static void Leave(string functionName, bool returnval)
- {
- EventSourceLogging.Log.FunctionStop(functionName, returnval.ToString());
- }
-
- public static void Dump(byte[] buffer, int length)
- {
- Dump(buffer, 0, length);
- }
-
- public static void Dump(byte[] buffer, int offset, int length)
- {
- string warning =
- buffer == null ? "buffer is null" :
- offset >= buffer.Length ? "offset out of range" :
- (length < 0) || (length > buffer.Length - offset) ? "length out of range" :
- null;
- if (warning != null)
- {
- EventSourceLogging.Log.WarningDumpArray(warning);
- return;
- }
-
- var bufferSegment = new byte[length];
- Buffer.BlockCopy(buffer, offset, bufferSegment, 0, length);
- EventSourceLogging.Log.DebugDumpArray(bufferSegment);
- }
-
- public static bool IsEnabled { get { return EventSourceLogging.Log.IsEnabled(); } }
- }
-
- [Flags]
- internal enum ThreadKinds
- {
- Unknown = 0x0000,
-
- // Mutually exclusive.
- User = 0x0001, // Thread has entered via an API.
- System = 0x0002, // Thread has entered via a system callback (e.g. completion port) or is our own thread.
-
- // Mutually exclusive.
- Sync = 0x0004, // Thread should block.
- Async = 0x0008, // Thread should not block.
-
- // Mutually exclusive, not always known for a user thread. Never changes.
- Timer = 0x0010, // Thread is the timer thread. (Can't call user code.)
- CompletionPort = 0x0020, // Thread is a ThreadPool completion-port thread.
- Worker = 0x0040, // Thread is a ThreadPool worker thread.
- Finalization = 0x0080, // Thread is the finalization thread.
- Other = 0x0100, // Unknown source.
-
- OwnerMask = User | System,
- SyncMask = Sync | Async,
- SourceMask = Timer | CompletionPort | Worker | Finalization | Other,
-
- // Useful "macros"
- SafeSources = SourceMask & ~(Timer | Finalization), // Methods that "unsafe" sources can call must be explicitly marked.
- ThreadPool = CompletionPort | Worker, // Like Thread.CurrentThread.IsThreadPoolThread
- }
-}
diff --git a/src/Common/src/System/Net/Logging/HttpEventSource.cs b/src/Common/src/System/Net/Logging/HttpEventSource.cs
deleted file mode 100644
index 33434bf0e9..0000000000
--- a/src/Common/src/System/Net/Logging/HttpEventSource.cs
+++ /dev/null
@@ -1,205 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-using System.Net.Http;
-using System.Globalization;
-
-namespace System.Net
-{
- //TODO: If localization resources are not found, logging does not work. Issue #5126.
- [EventSource(Name = "Microsoft-System-Net-Http",
- Guid = "bdd9a83e-1929-5482-0d73-2fe5e1c0e16d",
- LocalizationResources = "FxResources.System.Net.Http.SR")]
- internal sealed class HttpEventSource : EventSource
- {
- private const int AssociateId = 1;
- private const int UriBaseAddressId = 2;
- private const int ContentNullId = 3;
- private const int ClientSendCompletedId = 4;
- private const int HeadersInvalidValueId = 5;
- private const int HandlerMessageId = 6;
-
- private readonly static HttpEventSource s_log = new HttpEventSource();
- private HttpEventSource() { }
- public static HttpEventSource Log
- {
- get
- {
- return s_log;
- }
- }
-
- [NonEvent]
- internal static void Associate(object objA, object objB)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- s_log.Associate(LoggingHash.GetObjectName(objA),
- LoggingHash.HashInt(objA),
- LoggingHash.GetObjectName(objB),
- LoggingHash.HashInt(objB));
- }
-
- [Event(AssociateId, Keywords = Keywords.Default,
- Level = EventLevel.Informational, Message = "[{0}#{1}]<-->[{2}#{3}]")]
- internal unsafe void Associate(string objectA, int objectAHash, string objectB, int objectBHash)
- {
- const int SizeData = 4;
- fixed (char* arg1Ptr = objectA, arg2Ptr = objectB)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
-
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (objectA.Length + 1) * sizeof(char); // Size in bytes, including a null terminator.
- dataDesc[1].DataPointer = (IntPtr)(&objectAHash);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[2].Size = (objectB.Length + 1) * sizeof(char);
- dataDesc[3].DataPointer = (IntPtr)(&objectBHash);
- dataDesc[3].Size = sizeof(int);
-
- WriteEventCore(AssociateId, SizeData, dataDesc);
- }
- }
-
- [NonEvent]
- internal static void UriBaseAddress(object obj, string baseAddress)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- s_log.UriBaseAddress(baseAddress, LoggingHash.GetObjectName(obj), LoggingHash.HashInt(obj));
- }
-
- [Event(UriBaseAddressId, Keywords = Keywords.Debug,
- Level = EventLevel.Informational)]
- internal unsafe void UriBaseAddress(string uriBaseAddress, string objName, int objHash)
- {
- const int SizeData = 3;
- fixed (char* arg1Ptr = uriBaseAddress, arg2Ptr = objName)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
-
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (uriBaseAddress.Length + 1) * sizeof(char); // Size in bytes, including a null terminator.
- dataDesc[1].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[1].Size = (objName.Length + 1) * sizeof(char);
- dataDesc[2].DataPointer = (IntPtr)(&objHash);
- dataDesc[2].Size = sizeof(int);
-
- WriteEventCore(UriBaseAddressId, SizeData, dataDesc);
- }
- }
-
- [NonEvent]
- internal static void ContentNull(object obj)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- s_log.ContentNull(LoggingHash.GetObjectName(obj), LoggingHash.HashInt(obj));
- }
-
- [Event(ContentNullId, Keywords = Keywords.Debug,
- Level = EventLevel.Informational)]
- internal void ContentNull(string objName, int objHash)
- {
- WriteEvent(ContentNullId, objName, objHash);
- }
-
- [NonEvent]
- internal static void ClientSendCompleted(HttpClient httpClient, HttpResponseMessage response, HttpRequestMessage request)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- string responseString = "";
- if (response != null)
- {
- responseString = response.ToString();
- }
-
- s_log.ClientSendCompleted(LoggingHash.HashInt(request), LoggingHash.HashInt(response), responseString, LoggingHash.HashInt(httpClient));
- }
-
- [Event(ClientSendCompletedId, Keywords = Keywords.Debug,
- Level = EventLevel.Verbose)]
- internal unsafe void ClientSendCompleted(int httpRequestMessageHash, int httpResponseMessageHash, string responseString, int httpClientHash)
- {
- const int SizeData = 4;
- fixed (char* arg1Ptr = responseString)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(&httpRequestMessageHash);
- dataDesc[0].Size = sizeof(int);
- dataDesc[1].DataPointer = (IntPtr)(&httpResponseMessageHash);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[2].Size = (responseString.Length + 1) * sizeof(char);
- dataDesc[3].DataPointer = (IntPtr)(&httpClientHash);
- dataDesc[3].Size = sizeof(int);
-
- WriteEventCore(ClientSendCompletedId, SizeData, dataDesc);
- }
- }
-
- [Event(HeadersInvalidValueId, Keywords = Keywords.Debug,
- Level = EventLevel.Verbose)]
- internal void HeadersInvalidValue(string name, string rawValue)
- {
- WriteEvent(HeadersInvalidValueId, name, rawValue);
- }
-
- [Event(HandlerMessageId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)]
- internal unsafe void HandlerMessage(int workerId, int requestId, string memberName, string message)
- {
- if (memberName == null)
- {
- memberName = string.Empty;
- }
-
- if (message == null)
- {
- message = string.Empty;
- }
-
- const int SizeData = 4;
- fixed (char* memberNamePtr = memberName)
- fixed (char* messagePtr = message)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
-
- dataDesc[0].DataPointer = (IntPtr)(&workerId);
- dataDesc[0].Size = sizeof(int);
-
- dataDesc[1].DataPointer = (IntPtr)(&requestId);
- dataDesc[1].Size = sizeof(int);
-
- dataDesc[2].DataPointer = (IntPtr)(memberNamePtr);
- dataDesc[2].Size = (memberName.Length + 1) * sizeof(char);
-
- dataDesc[3].DataPointer = (IntPtr)(messagePtr);
- dataDesc[3].Size = (message.Length + 1) * sizeof(char);
-
- WriteEventCore(HandlerMessageId, SizeData, dataDesc);
- }
- }
-
- public class Keywords
- {
- public const EventKeywords Default = (EventKeywords)0x0001;
- public const EventKeywords Debug = (EventKeywords)0x0002;
- }
- }
-}
diff --git a/src/Common/src/System/Net/Logging/LoggingHash.cs b/src/Common/src/System/Net/Logging/LoggingHash.cs
deleted file mode 100644
index 6db153ed76..0000000000
--- a/src/Common/src/System/Net/Logging/LoggingHash.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Threading;
-
-namespace System.Net
-{
- internal static class LoggingHash
- {
- // Converts an object to a normalized string that can be printed
- // takes System.Net.ObjectNamedFoo and coverts to ObjectNamedFoo,
- // except IPAddress, IPEndPoint, and Uri, which return ToString().
- internal static string GetObjectName(object obj)
- {
- if (obj == null)
- {
- return "null";
- }
- if (obj is Uri || obj is System.Net.IPAddress || obj is System.Net.IPEndPoint || obj is string)
- {
- return obj.ToString();
- }
- else
- {
- return obj.GetType().ToString();
- }
- }
- internal static int HashInt(object objectValue)
- {
- if (objectValue == null)
- {
- return 0;
- }
- else
- {
- return objectValue.GetHashCode();
- }
- }
-
- internal static string ObjectToString(object objectValue)
- {
- if (objectValue == null)
- {
- return "(null)";
- }
- else if (objectValue is string && ((string)objectValue).Length == 0)
- {
- return "(string.empty)";
- }
- else if (objectValue is Exception)
- {
- return ExceptionMessage(objectValue as Exception);
- }
- else if (objectValue is IntPtr)
- {
- return "0x" + ((IntPtr)objectValue).ToString("x");
- }
- else
- {
- return objectValue.ToString();
- }
- }
-
- private static string ExceptionMessage(Exception exception)
- {
- if (exception == null)
- {
- return string.Empty;
- }
-
- if (exception.InnerException == null)
- {
- return exception.Message;
- }
-
- return exception.Message + " (" + ExceptionMessage(exception.InnerException) + ")";
- }
-
- internal static string HashString(object objectValue)
- {
- if (objectValue == null)
- {
- return "(null)";
- }
- else if (objectValue is string && ((string)objectValue).Length == 0)
- {
- return "(string.empty)";
- }
- else
- {
- return objectValue.GetHashCode().ToString(NumberFormatInfo.InvariantInfo);
- }
- }
-
- internal static object[] GetObjectLogHash(object obj)
- {
- object[] hashObject = new object[2];
- hashObject[0] = GetObjectName(obj);
- hashObject[1] = HashInt(obj);
- return hashObject;
- }
- }
-}
diff --git a/src/Common/src/System/Net/Logging/MailEventSource.cs b/src/Common/src/System/Net/Logging/MailEventSource.cs
deleted file mode 100644
index 77334f7247..0000000000
--- a/src/Common/src/System/Net/Logging/MailEventSource.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-using System.Globalization;
-using System.Net.Sockets;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-namespace System.Net
-{
- [EventSource(Name = "Microsoft-System-Net-Mail", LocalizationResources = "FxResources.System.Net.Mail.SR")]
- internal sealed class MailEventSource : EventSource
- {
- private const int RemoveId = 1;
- private const int GetId = 2;
- private const int SetId = 3;
- private const int SendId = 4;
- private const int AssociateId = 5;
-
- private readonly static MailEventSource s_log = new MailEventSource();
- private MailEventSource() { }
- public static MailEventSource Log
- {
- get
- {
- return s_log;
- }
- }
-
- [Event(RemoveId, Level = EventLevel.Informational)]
- internal void Remove(string name)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(RemoveId, name);
- }
-
- [Event(GetId, Level = EventLevel.Informational)]
- internal void Get(string name)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(GetId, name);
- }
-
- [Event(SetId, Level = EventLevel.Informational)]
- internal void Set(string name, string value)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(SetId, string.Format("{0}={1}", name, value));
- }
-
- [Event(SendId, Level = EventLevel.Informational)]
- internal void Send(string name, string value)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(SendId, string.Format("{0}={1}", name, value));
- }
-
- [Event(AssociateId, Level = EventLevel.Informational)]
- internal void Associate(object a, object b)
- {
- WriteEvent(AssociateId, string.Format("Associating {0}#{1} with {2}#{3}", LoggingHash.GetObjectName(a), LoggingHash.HashString(a), LoggingHash.GetObjectName(b), LoggingHash.HashString(b)));
- }
- }
-}
diff --git a/src/Common/src/System/Net/Logging/NetEventSource.Common.cs b/src/Common/src/System/Net/Logging/NetEventSource.Common.cs
new file mode 100644
index 0000000000..a6f2de5b5c
--- /dev/null
+++ b/src/Common/src/System/Net/Logging/NetEventSource.Common.cs
@@ -0,0 +1,739 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+#if DEBUG
+// Uncomment to enable runtime checks to help validate that NetEventSource isn't being misused
+// in a way that will cause performance problems, e.g. unexpected boxing of value types.
+//#define DEBUG_NETEVENTSOURCE_MISUSE
+#endif
+
+using System.Collections;
+using System.Diagnostics;
+using System.Diagnostics.Tracing;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System.Net
+{
+ // Implementation:
+ // This partial file is meant to be consumed into each System.Net.* assembly that needs to log. Each such assembly also provides
+ // its own NetEventSource partial class that adds an appropriate [EventSource] attribute, giving it a unique name for that assembly.
+ // Those partials can then also add additional events if needed, starting numbering from the NextAvailableEventId defined by this partial.
+
+ // Usage:
+ // - Operations that have zero allocations / measurable computations at call sites can use a simple pattern, calling methods like:
+ // NetEventSource.Enter(this); // entering an instance method
+ // NetEventSource.Info(this, "literal string"); // arbitrary message with a literal string
+ // NetEventSource.Enter(this, refArg1, regArg2); // entering an instance method with two reference type arguments
+ // NetEventSource.Enter(null); // entering a static method
+ // NetEventSource.Enter(null, refArg1); // entering a static method with one reference type argument
+ // - Operations that may allocate (e.g. boxing a value type, using string interpolation, etc.) or that may have computations
+ // at call sites should guard access like:
+ // if (NetEventSource.IsEnabled) NetEventSource.Enter(this, refArg1, valueTypeArg2); // entering an instance method with a value type arg
+ // if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Found certificate: {cert}"); // info logging with a formattable string
+ // Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined.
+ // - Messages can be strings, formattable strings, or any other object. Objects (including those used in formattable strings) have special
+ // formatting applied, controlled by the Format method. Partial specializations can also override this formatting by implementing a partial
+ // method that takes an object and optionally provides a string representation of it, in case a particular library wants to customize further.
+ // - NetEventSource.Fail calls typically do not need to be prefixed with an IsEnabled check, even if they allocate, as FailMessage
+ // should only be used in cases similar to Debug.Fail, where they are not expected to happen in retail builds, and thus extra costs
+ // don't matter.
+
+ /// <summary>Provides logging facilities for System.Net libraries.</summary>
+ internal sealed partial class NetEventSource : EventSource
+ {
+ /// <summary>The single event source instance to use for all logging.</summary>
+ public static readonly NetEventSource Log = new NetEventSource();
+
+ #region Metadata
+ public class Keywords
+ {
+ public const EventKeywords Default = (EventKeywords)0x0001;
+ public const EventKeywords Debug = (EventKeywords)0x0002;
+ public const EventKeywords EnterExit = (EventKeywords)0x0004;
+ }
+
+ private const string MissingMember = "(?)";
+ private const string NullInstance = "(null)";
+ private const string StaticMethodObject = "(static)";
+ private const string NoParameters = "";
+ private const int MaxDumpSize = 1024;
+
+ private const int EnterEventId = 1;
+ private const int ExitEventId = 2;
+ private const int AssociateEventId = 3;
+ private const int InfoEventId = 4;
+ private const int ErrorEventId = 5;
+ private const int CriticalFailureEventId = 6;
+ private const int DumpArrayEventId = 7;
+
+ private const int NextAvailableEventId = 8; // Update this value whenever new events are added. Derived types should base all events off of this to avoid conflicts.
+ #endregion
+
+ #region Events
+ #region Enter
+ /// <summary>Logs entrance to a method.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="formattableString">A description of the entrance, including any arguments to the call.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Enter(object thisOrContextObject, FormattableString formattableString = null, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(formattableString);
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ }
+
+ /// <summary>Logs entrance to a method.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="arg0">The object to log.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Enter(object thisOrContextObject, object arg0, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(arg0);
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
+ }
+
+ /// <summary>Logs entrance to a method.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="arg0">The first object to log.</param>
+ /// <param name="arg1">The second object to log.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Enter(object thisOrContextObject, object arg0, object arg1, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(arg0);
+ DebugValidateArg(arg1);
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
+ }
+
+ /// <summary>Logs entrance to a method.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="arg0">The first object to log.</param>
+ /// <param name="arg1">The second object to log.</param>
+ /// <param name="arg2">The third object to log.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Enter(object thisOrContextObject, object arg0, object arg1, object arg2, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(arg0);
+ DebugValidateArg(arg1);
+ DebugValidateArg(arg2);
+ if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
+ }
+
+ [Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
+ private void Enter(string thisOrContextObject, string memberName, string parameters) =>
+ WriteEvent(EnterEventId, thisOrContextObject, memberName ?? MissingMember, parameters);
+ #endregion
+
+ #region Exit
+ /// <summary>Logs exit from a method.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="formattableString">A description of the exit operation, including any return values.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Exit(object thisOrContextObject, FormattableString formattableString = null, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(formattableString);
+ if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ }
+
+ /// <summary>Logs exit from a method.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="arg0">A return value from the member.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Exit(object thisOrContextObject, object arg0, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(arg0);
+ if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
+ }
+
+ /// <summary>Logs exit from a method.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="arg0">A return value from the member.</param>
+ /// <param name="arg1">A second return value from the member.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Exit(object thisOrContextObject, object arg0, object arg1, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(arg0);
+ DebugValidateArg(arg1);
+ if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
+ }
+
+ [Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
+ private void Exit(string thisOrContextObject, string memberName, string result) =>
+ WriteEvent(ExitEventId, thisOrContextObject, memberName ?? MissingMember, result);
+ #endregion
+
+ #region Info
+ /// <summary>Logs an information message.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="formattableString">The message to be logged.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Info(object thisOrContextObject, FormattableString formattableString = null, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(formattableString);
+ if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ }
+
+ /// <summary>Logs an information message.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="message">The message to be logged.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Info(object thisOrContextObject, object message, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(message);
+ if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ }
+
+ [Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)]
+ private void Info(string thisOrContextObject, string memberName, string message) =>
+ WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message);
+ #endregion
+
+ #region Error
+ /// <summary>Logs an error message.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="formattableString">The message to be logged.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Error(object thisOrContextObject, FormattableString formattableString, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(formattableString);
+ if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ }
+
+ /// <summary>Logs an error message.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="message">The message to be logged.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Error(object thisOrContextObject, object message, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(message);
+ if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ }
+
+ [Event(ErrorEventId, Level = EventLevel.Warning, Keywords = Keywords.Default)]
+ private void ErrorMessage(string thisOrContextObject, string memberName, string message) =>
+ WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message);
+ #endregion
+
+ #region Fail
+ /// <summary>Logs a fatal error and raises an assert.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="formattableString">The message to be logged.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Fail(object thisOrContextObject, FormattableString formattableString, [CallerMemberName] string memberName = null)
+ {
+ // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
+ // that should never happen in production, and thus we don't care about extra costs.
+
+ if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
+ }
+
+ /// <summary>Logs a fatal error and raises an assert.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="message">The message to be logged.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Fail(object thisOrContextObject, object message, [CallerMemberName] string memberName = null)
+ {
+ // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
+ // that should never happen in production, and thus we don't care about extra costs.
+
+ if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
+ }
+
+ [Event(CriticalFailureEventId, Level = EventLevel.Critical, Keywords = Keywords.Debug)]
+ private void CriticalFailure(string thisOrContextObject, string memberName, string message) =>
+ WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message);
+ #endregion
+
+ #region DumpArray
+ /// <summary>Logs the contents of a buffer.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="buffer">The buffer to be logged.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void DumpArray(object thisOrContextObject, byte[] buffer, [CallerMemberName] string memberName = null)
+ {
+ DumpArray(thisOrContextObject, buffer, 0, buffer.Length, memberName);
+ }
+
+ /// <summary>Logs the contents of a buffer.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="buffer">The buffer to be logged.</param>
+ /// <param name="offset">The starting offset from which to log.</param>
+ /// <param name="count">The number of bytes to log.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void DumpArray(object thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string memberName = null)
+ {
+ if (IsEnabled)
+ {
+ if (offset < 0 || offset > buffer.Length - count)
+ {
+ Fail(thisOrContextObject, $"Invalid {nameof(DumpArray)} Args. Length={buffer.Length}, Offset={offset}, Count={count}", memberName);
+ return;
+ }
+
+ count = Math.Min(count, MaxDumpSize);
+
+ byte[] slice = buffer;
+ if (offset != 0 || count != buffer.Length)
+ {
+ slice = new byte[count];
+ Buffer.BlockCopy(buffer, offset, slice, 0, count);
+ }
+
+ Log.DumpArray(IdOf(thisOrContextObject), memberName, slice);
+ }
+ }
+
+ /// <summary>Logs the contents of a buffer.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="bufferPtr">The starting location of the buffer to be logged.</param>
+ /// <param name="count">The number of bytes to log.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static unsafe void DumpArray(object thisOrContextObject, IntPtr bufferPtr, int count, [CallerMemberName] string memberName = null)
+ {
+ Debug.Assert(bufferPtr != IntPtr.Zero);
+ Debug.Assert(count >= 0);
+
+ if (IsEnabled)
+ {
+ var buffer = new byte[Math.Min(count, MaxDumpSize)];
+ fixed (byte* targetPtr = buffer)
+ {
+ Buffer.MemoryCopy((byte*)bufferPtr, targetPtr, buffer.Length, buffer.Length);
+ }
+ Log.DumpArray(IdOf(thisOrContextObject), memberName, buffer);
+ }
+ }
+
+ [Event(DumpArrayEventId, Level = EventLevel.Verbose, Keywords = Keywords.Debug)]
+ private unsafe void DumpArray(string thisOrContextObject, string memberName, byte[] buffer) =>
+ WriteEvent(DumpArrayEventId, thisOrContextObject, memberName ?? MissingMember, buffer);
+ #endregion
+
+ #region Associate
+ /// <summary>Logs a relationship between two objects.</summary>
+ /// <param name="first">The first object.</param>
+ /// <param name="second">The second object.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Associate(object first, object second, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(first);
+ DebugValidateArg(second);
+ if (IsEnabled) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
+ }
+
+ /// <summary>Logs a relationship between two objects.</summary>
+ /// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
+ /// <param name="first">The first object.</param>
+ /// <param name="second">The second object.</param>
+ /// <param name="memberName">The calling member.</param>
+ [NonEvent]
+ public static void Associate(object thisOrContextObject, object first, object second, [CallerMemberName] string memberName = null)
+ {
+ DebugValidateArg(thisOrContextObject);
+ DebugValidateArg(first);
+ DebugValidateArg(second);
+ if (IsEnabled) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
+ }
+
+ [Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")]
+ private void Associate(string thisOrContextObject, string memberName, string first, string second) =>
+ WriteEvent(AssociateEventId, thisOrContextObject, memberName ?? MissingMember, first, second);
+ #endregion
+ #endregion
+
+ #region Helpers
+ [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
+ private static void DebugValidateArg(object arg)
+ {
+ if (!IsEnabled)
+ {
+ Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check");
+ Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
+ }
+ }
+
+ [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
+ private static void DebugValidateArg(FormattableString arg)
+ {
+ Debug.Assert(IsEnabled || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
+ }
+
+ public static new bool IsEnabled => Log.IsEnabled();
+
+ [NonEvent]
+ public static string IdOf(object value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
+
+ [NonEvent]
+ public static int GetHashCode(object value) => value?.GetHashCode() ?? 0;
+
+ [NonEvent]
+ public static object Format(object value)
+ {
+ // If it's null, return a known string for null values
+ if (value == null)
+ {
+ return NullInstance;
+ }
+
+ // Give another partial implementation a chance to provide its own string representation
+ string result = null;
+ AdditionalCustomizedToString(value, ref result);
+ if (result != null)
+ {
+ return result;
+ }
+
+ // Format arrays with their element type name and length
+ Array arr = value as Array;
+ if (arr != null)
+ {
+ return $"{arr.GetType().GetElementType()}[{((Array)value).Length}]";
+ }
+
+ // Format ICollections as the name and count
+ ICollection c = value as ICollection;
+ if (c != null)
+ {
+ return $"{c.GetType().Name}({c.Count})";
+ }
+
+ // Format SafeHandles as their type, hash code, and pointer value
+ SafeHandle handle = value as SafeHandle;
+ if (handle != null)
+ {
+ return $"{handle.GetType().Name}:{handle.GetHashCode()}(0x{handle.DangerousGetHandle():X})";
+ }
+
+ // Format IntPtrs as hex
+ if (value is IntPtr)
+ {
+ return $"0x{value:X}";
+ }
+
+ // If the string representation of the instance would just be its type name,
+ // use its id instead.
+ string toString = value.ToString();
+ if (toString == null || toString == value.GetType().FullName)
+ {
+ return IdOf(value);
+ }
+
+ // Otherwise, return the original object so that the caller does default formatting.
+ return value;
+ }
+
+ [NonEvent]
+ private static string Format(FormattableString s)
+ {
+ switch (s.ArgumentCount)
+ {
+ case 0: return s.Format;
+ case 1: return string.Format(s.Format, Format(s.GetArgument(0)));
+ case 2: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)));
+ case 3: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)), Format(s.GetArgument(2)));
+ default:
+ object[] args = s.GetArguments();
+ object[] formattedArgs = new object[args.Length];
+ for (int i = 0; i < args.Length; i++)
+ {
+ formattedArgs[i] = Format(args[i]);
+ }
+ return string.Format(s.Format, formattedArgs);
+ }
+ }
+
+ static partial void AdditionalCustomizedToString<T>(T value, ref string result);
+ #endregion
+
+ #region Custom WriteEvent overloads
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, int arg1, int arg2, string arg3, string arg4)
+ {
+ if (IsEnabled())
+ {
+ if (arg3 == null) arg3 = "";
+ if (arg4 == null) arg4 = "";
+
+ fixed (char* string3Bytes = arg3)
+ fixed (char* string4Bytes = arg4)
+ {
+ const int NumEventDatas = 4;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)(&arg1);
+ descrs[0].Size = sizeof(int);
+
+ descrs[1].DataPointer = (IntPtr)(&arg2);
+ descrs[1].Size = sizeof(int);
+
+ descrs[2].DataPointer = (IntPtr)string3Bytes;
+ descrs[2].Size = ((arg3.Length + 1) * 2);
+
+ descrs[3].DataPointer = (IntPtr)string4Bytes;
+ descrs[3].Size = ((arg4.Length + 1) * 2);
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3, string arg4)
+ {
+ if (IsEnabled())
+ {
+ if (arg1 == null) arg1 = "";
+ if (arg2 == null) arg2 = "";
+ if (arg3 == null) arg3 = "";
+ if (arg4 == null) arg4 = "";
+
+ fixed (char* string1Bytes = arg1)
+ fixed (char* string2Bytes = arg2)
+ fixed (char* string3Bytes = arg3)
+ fixed (char* string4Bytes = arg4)
+ {
+ const int NumEventDatas = 4;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)string1Bytes;
+ descrs[0].Size = ((arg1.Length + 1) * 2);
+
+ descrs[1].DataPointer = (IntPtr)string2Bytes;
+ descrs[1].Size = ((arg2.Length + 1) * 2);
+
+ descrs[2].DataPointer = (IntPtr)string3Bytes;
+ descrs[2].Size = ((arg3.Length + 1) * 2);
+
+ descrs[3].DataPointer = (IntPtr)string4Bytes;
+ descrs[3].Size = ((arg4.Length + 1) * 2);
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, string arg1, string arg2, byte[] arg3)
+ {
+ if (IsEnabled())
+ {
+ if (arg1 == null) arg1 = "";
+ if (arg2 == null) arg2 = "";
+ if (arg3 == null) arg3 = Array.Empty<byte>();
+
+ fixed (char* arg1Ptr = arg1)
+ fixed (char* arg2Ptr = arg2)
+ fixed (byte* arg3Ptr = arg3)
+ {
+ int bufferLength = arg3.Length;
+ const int NumEventDatas = 4;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)arg1Ptr;
+ descrs[0].Size = (arg1.Length + 1) * sizeof(char);
+
+ descrs[1].DataPointer = (IntPtr)arg2Ptr;
+ descrs[1].Size = (arg2.Length + 1) * sizeof(char);
+
+ descrs[2].DataPointer = (IntPtr)(&bufferLength);
+ descrs[2].Size = 4;
+
+ descrs[3].DataPointer = (IntPtr)arg3Ptr;
+ descrs[3].Size = bufferLength;
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int arg4)
+ {
+ if (IsEnabled())
+ {
+ if (arg1 == null) arg1 = "";
+
+ fixed (char* arg1Ptr = arg1)
+ {
+ const int NumEventDatas = 4;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)(arg1Ptr);
+ descrs[0].Size = (arg1.Length + 1) * sizeof(char);
+
+ descrs[1].DataPointer = (IntPtr)(&arg2);
+ descrs[1].Size = sizeof(int);
+
+ descrs[2].DataPointer = (IntPtr)(&arg3);
+ descrs[2].Size = sizeof(int);
+
+ descrs[3].DataPointer = (IntPtr)(&arg4);
+ descrs[3].Size = sizeof(int);
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8)
+ {
+ if (IsEnabled())
+ {
+ if (arg1 == null) arg1 = "";
+
+ fixed (char* arg1Ptr = arg1)
+ {
+ const int NumEventDatas = 8;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)(arg1Ptr);
+ descrs[0].Size = (arg1.Length + 1) * sizeof(char);
+
+ descrs[1].DataPointer = (IntPtr)(&arg2);
+ descrs[1].Size = sizeof(int);
+
+ descrs[2].DataPointer = (IntPtr)(&arg3);
+ descrs[2].Size = sizeof(int);
+
+ descrs[3].DataPointer = (IntPtr)(&arg4);
+ descrs[3].Size = sizeof(int);
+
+ descrs[3].DataPointer = (IntPtr)(&arg5);
+ descrs[3].Size = sizeof(int);
+
+ descrs[3].DataPointer = (IntPtr)(&arg6);
+ descrs[3].Size = sizeof(int);
+
+ descrs[3].DataPointer = (IntPtr)(&arg7);
+ descrs[3].Size = sizeof(int);
+
+ descrs[3].DataPointer = (IntPtr)(&arg8);
+ descrs[3].Size = sizeof(int);
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, string arg1, int arg2, string arg3)
+ {
+ if (IsEnabled())
+ {
+ if (arg1 == null) arg1 = "";
+ if (arg3 == null) arg3 = "";
+
+ fixed (char* arg1Ptr = arg1)
+ fixed (char* arg3Ptr = arg3)
+ {
+ const int NumEventDatas = 3;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)(arg1Ptr);
+ descrs[0].Size = (arg1.Length + 1) * sizeof(char);
+
+ descrs[1].DataPointer = (IntPtr)(&arg2);
+ descrs[1].Size = sizeof(int);
+
+ descrs[2].DataPointer = (IntPtr)(arg3Ptr);
+ descrs[2].Size = (arg3.Length + 1) * sizeof(char);
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, string arg1, string arg2, int arg3)
+ {
+ if (IsEnabled())
+ {
+ if (arg1 == null) arg1 = "";
+ if (arg2 == null) arg2 = "";
+
+ fixed (char* arg1Ptr = arg1)
+ fixed (char* arg2Ptr = arg2)
+ {
+ const int NumEventDatas = 3;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)(arg1Ptr);
+ descrs[0].Size = (arg1.Length + 1) * sizeof(char);
+
+ descrs[1].DataPointer = (IntPtr)(arg2Ptr);
+ descrs[1].Size = (arg2.Length + 1) * sizeof(char);
+
+ descrs[2].DataPointer = (IntPtr)(&arg3);
+ descrs[2].Size = sizeof(int);
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+
+ [NonEvent]
+ private unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3, int arg4)
+ {
+ if (IsEnabled())
+ {
+ if (arg1 == null) arg1 = "";
+ if (arg2 == null) arg2 = "";
+ if (arg3 == null) arg3 = "";
+
+ fixed (char* arg1Ptr = arg1)
+ fixed (char* arg2Ptr = arg2)
+ fixed (char* arg3Ptr = arg3)
+ {
+ const int NumEventDatas = 4;
+ var descrs = stackalloc EventData[NumEventDatas];
+
+ descrs[0].DataPointer = (IntPtr)(arg1Ptr);
+ descrs[0].Size = (arg1.Length + 1) * sizeof(char);
+
+ descrs[1].DataPointer = (IntPtr)(arg2Ptr);
+ descrs[1].Size = (arg2.Length + 1) * sizeof(char);
+
+ descrs[1].DataPointer = (IntPtr)(arg3Ptr);
+ descrs[1].Size = (arg3.Length + 1) * sizeof(char);
+
+ descrs[3].DataPointer = (IntPtr)(&arg4);
+ descrs[3].Size = sizeof(int);
+
+ WriteEventCore(eventId, NumEventDatas, descrs);
+ }
+ }
+ }
+ #endregion
+ }
+}
diff --git a/src/Common/src/System/Net/Logging/NetEventSource.cs b/src/Common/src/System/Net/Logging/NetEventSource.cs
deleted file mode 100644
index eb25e168ce..0000000000
--- a/src/Common/src/System/Net/Logging/NetEventSource.cs
+++ /dev/null
@@ -1,302 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-using System.Globalization;
-
-namespace System.Net
-{
- // TODO: Issue #5144: This class should not change or it can introduce incompatibility issues.
- [EventSource(Name = "Microsoft-System-Net",
- Guid = "501a994a-eb63-5415-9af1-1b031260f16c")]
- internal sealed class NetEventSource : EventSource
- {
- private const int FunctionStartId = 1;
- private const int FunctionStopId = 2;
- private const int CriticalExceptionId = 3;
- private const int CriticalErrorId = 4;
-
- private readonly static NetEventSource s_log = new NetEventSource();
- private NetEventSource() { }
- public static NetEventSource Log
- {
- get
- {
- return s_log;
- }
- }
-
- [NonEvent]
- internal static void Enter(ComponentType componentType, object obj, string method, object paramObject)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- string callerName;
- int callerHash;
- string parametersName = "";
- int parametersHash = 0;
- if (obj is string)
- {
- callerName = obj as string;
- callerHash = 0;
- }
- else
- {
- callerName = LoggingHash.GetObjectName(obj);
- callerHash = LoggingHash.HashInt(obj);
- }
-
- if (paramObject is string)
- {
- parametersName = paramObject as string;
- parametersHash = 0;
- }
- else if (paramObject != null)
- {
- parametersName = LoggingHash.GetObjectName(paramObject);
- parametersHash = LoggingHash.HashInt(paramObject);
- }
-
- s_log.FunctionStart(
- callerName,
- callerHash,
- LoggingHash.GetObjectName(method),
- parametersName,
- parametersHash,
- componentType);
- }
-
- [Event(FunctionStartId, Keywords = Keywords.FunctionEntryExit,
- Level = EventLevel.Verbose, Message = "[{5}] {0}#{1}::{2}({3}#{4})")]
- internal unsafe void FunctionStart(
- string callerName,
- int callerHash,
- string method,
- string parametersName,
- int parametersHash,
- ComponentType componentType)
- {
- const int SizeData = 6;
- fixed (char* arg1Ptr = callerName, arg2Ptr = method, arg3Ptr = parametersName)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
-
- dataDesc[0].DataPointer = (IntPtr)arg1Ptr;
- dataDesc[0].Size = (callerName.Length + 1) * sizeof(char); // Size in bytes, including a null terminator.
- dataDesc[1].DataPointer = (IntPtr)(&callerHash);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[2].Size = (method.Length + 1) * sizeof(char);
- dataDesc[3].DataPointer = (IntPtr)(arg3Ptr);
- dataDesc[3].Size = (parametersName.Length + 1) * sizeof(char);
- dataDesc[4].DataPointer = (IntPtr)(&parametersHash);
- dataDesc[4].Size = sizeof(int);
- dataDesc[5].DataPointer = (IntPtr)(&componentType);
- dataDesc[5].Size = sizeof(int);
-
- WriteEventCore(FunctionStartId, SizeData, dataDesc);
- }
- }
-
- [NonEvent]
- internal static void Exit(ComponentType componentType, object obj, string method, object retObject)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
- string callerName;
- int callerHash;
- string parametersName = "";
- int parametersHash = 0;
- if (obj is string)
- {
- callerName = obj as string;
- callerHash = 0;
- }
- else
- {
- callerName = LoggingHash.GetObjectName(obj);
- callerHash = LoggingHash.HashInt(obj);
- }
-
- if (retObject is string)
- {
- parametersName = retObject as string;
- parametersHash = 0;
- }
-
- else if (retObject != null)
- {
- parametersName = LoggingHash.GetObjectName(retObject);
- parametersHash = LoggingHash.HashInt(retObject);
- }
- s_log.FunctionStop(callerName,
- callerHash,
- LoggingHash.GetObjectName(method),
- parametersName,
- parametersHash,
- componentType);
- }
-
- [Event(FunctionStopId, Keywords = Keywords.FunctionEntryExit,
- Level = EventLevel.Verbose, Message = "[{5}] {0}#{1}::{2}({3}#{4})")]
- internal unsafe void FunctionStop(
- string callerName,
- int callerHash,
- string method,
- string parametersName,
- int parametersHash,
- ComponentType componentType)
- {
- const int SizeData = 6;
- fixed (char* arg1Ptr = callerName, arg2Ptr = method, arg3Ptr = parametersName)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
-
- dataDesc[0].DataPointer = (IntPtr)arg1Ptr;
- dataDesc[0].Size = (callerName.Length + 1) * sizeof(char); // Size in bytes, including a null terminator.
- dataDesc[1].DataPointer = (IntPtr)(&callerHash);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[2].Size = (method.Length + 1) * sizeof(char);
- dataDesc[3].DataPointer = (IntPtr)(arg3Ptr);
- dataDesc[3].Size = (parametersName.Length + 1) * sizeof(char);
- dataDesc[4].DataPointer = (IntPtr)(&parametersHash);
- dataDesc[4].Size = sizeof(int);
- dataDesc[5].DataPointer = (IntPtr)(&componentType);
- dataDesc[5].Size = sizeof(int);
-
- WriteEventCore(FunctionStopId, SizeData, dataDesc);
- }
- }
-
- [NonEvent]
- internal static void Exception(ComponentType componentType, object obj, string method, Exception e)
- {
- s_log.CriticalException(
- LoggingHash.GetObjectName(obj),
- LoggingHash.GetObjectName(method),
- LoggingHash.GetObjectName(e.Message),
- LoggingHash.HashInt(obj),
- LoggingHash.GetObjectName(e.StackTrace),
- componentType);
- }
-
- [Event(CriticalExceptionId, Keywords = Keywords.Default,
- Level = EventLevel.Critical)]
- internal unsafe void CriticalException(string objName, string method, string message, int objHash, string stackTrace, ComponentType componentType)
- {
- const int SizeData = 6;
- fixed (char* arg1Ptr = objName, arg2Ptr = method, arg3Ptr = message, arg4Ptr = stackTrace)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
-
- dataDesc[0].DataPointer = (IntPtr)arg1Ptr;
- dataDesc[0].Size = (objName.Length + 1) * sizeof(char); // Size in bytes, including a null terminator.
- dataDesc[1].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[1].Size = (method.Length + 1) * sizeof(char);
- dataDesc[2].DataPointer = (IntPtr)(arg3Ptr);
- dataDesc[2].Size = (message.Length + 1) * sizeof(char);
- dataDesc[3].DataPointer = (IntPtr)(&objHash);
- dataDesc[3].Size = sizeof(int);
- dataDesc[4].DataPointer = (IntPtr)(arg4Ptr);
- dataDesc[4].Size = (stackTrace.Length + 1) * sizeof(char);
- dataDesc[5].DataPointer = (IntPtr)(&componentType);
- dataDesc[5].Size = sizeof(int);
- WriteEventCore(CriticalExceptionId, SizeData, dataDesc);
- }
- }
-
- [NonEvent]
- internal static void PrintError(ComponentType componentType, string msg)
- {
- if (msg == null)
- {
- return;
- }
-
- s_log.CriticalError(LoggingHash.GetObjectName(msg), "", "", 0, componentType);
- }
-
- [NonEvent]
- internal static void PrintError(ComponentType componentType, object obj, string method, string msg)
- {
- s_log.CriticalError(
- LoggingHash.GetObjectName(msg),
- LoggingHash.GetObjectName(method),
- LoggingHash.GetObjectName(obj),
- LoggingHash.HashInt(obj),
- componentType);
- }
-
- [Event(CriticalErrorId, Keywords = Keywords.Default,
- Level = EventLevel.Critical)]
- internal unsafe void CriticalError(string message, string method, string objName, int objHash, ComponentType componentType)
- {
- const int SizeData = 5;
- fixed (char* arg1Ptr = message, arg2Ptr = method, arg3Ptr = objName)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
-
- dataDesc[0].DataPointer = (IntPtr)arg1Ptr;
- dataDesc[0].Size = (message.Length + 1) * sizeof(char); // Size in bytes, including a null terminator.
- dataDesc[1].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[1].Size = (method.Length + 1) * sizeof(char);
- dataDesc[2].DataPointer = (IntPtr)(arg3Ptr);
- dataDesc[2].Size = (objName.Length + 1) * sizeof(char);
- dataDesc[3].DataPointer = (IntPtr)(&objHash);
- dataDesc[3].Size = sizeof(int);
- dataDesc[4].DataPointer = (IntPtr)(&componentType);
- dataDesc[4].Size = sizeof(int);
- WriteEventCore(CriticalErrorId, SizeData, dataDesc);
- }
- }
-
- // TODO: Issue #12685
- [NonEvent]
- internal static void PrintInfo(ComponentType componentType, object obj, string msg)
- {
- }
-
- // TODO: Issue #12685
- [NonEvent]
- internal static void PrintInfo(ComponentType componentType, object obj, string method, string msg)
- {
- }
-
- // TODO: Issue #12685
- [NonEvent]
- internal static void PrintWarning(ComponentType componentType, string msg)
- {
- }
-
- // TODO: Issue #12685
- [NonEvent]
- internal static void Associate(ComponentType componentType, object obj1, object obj2)
- {
- }
-
- public class Keywords
- {
- public const EventKeywords Default = (EventKeywords)0x0001;
- public const EventKeywords Debug = (EventKeywords)0x0002;
- public const EventKeywords FunctionEntryExit = (EventKeywords)0x0004;
- }
-
- public enum ComponentType
- {
- Socket,
- Http,
- WebSocket,
- Security,
- NetworkInformation,
- Requests,
- Web
- }
- }
-}
diff --git a/src/Common/src/System/Net/Logging/SecurityEventSource.Windows.cs b/src/Common/src/System/Net/Logging/SecurityEventSource.Windows.cs
deleted file mode 100644
index 5109590a58..0000000000
--- a/src/Common/src/System/Net/Logging/SecurityEventSource.Windows.cs
+++ /dev/null
@@ -1,184 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-
-namespace System.Net
-{
- internal sealed partial class SecurityEventSource : EventSource
- {
- [Event(AcquireDefaultCredentialId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void AcquireDefaultCredential(string packageName, Interop.SspiCli.CredentialUse intent)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- string arg1Str = "";
- if (packageName != null)
- {
- arg1Str = packageName;
- }
-
- s_log.WriteEvent(AcquireDefaultCredentialId, arg1Str, intent);
- }
-
- [NonEvent]
- internal static void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, object authdata)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- string arg1Str = "";
- if (packageName != null)
- {
- arg1Str = packageName;
- }
-
- s_log.AcquireCredentialsHandle(arg1Str, intent, LoggingHash.GetObjectName(authdata));
- }
-
- [Event(AcquireCredentialsHandleId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, string authdata)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- const int SizeData = 3;
- fixed (char* arg1Ptr = packageName, arg2Ptr = authdata)
- {
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (packageName.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(&intent);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[2].Size = (authdata.Length + 1) * sizeof(char);
-
- WriteEventCore(AcquireCredentialsHandleId, SizeData, dataDesc);
- }
- }
-
- [Event(InitializeSecurityContextId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void InitializeSecurityContext(string credential, string context, string targetName, Interop.SspiCli.ContextFlags inFlags)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- fixed (char* arg1Ptr = credential, arg2Ptr = context, arg3Ptr = targetName)
- {
- const int SizeData = 4;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (credential.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[1].Size = (context.Length + 1) * sizeof(char);
- dataDesc[2].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[2].Size = (targetName.Length + 1) * sizeof(char);
- dataDesc[3].DataPointer = (IntPtr)(&inFlags);
- dataDesc[3].Size = sizeof(int);
-
- WriteEventCore(InitializeSecurityContextId, SizeData, dataDesc);
- }
- }
-
- [Event(AcceptSecuritContextId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void AcceptSecurityContext(string credential, string context, Interop.SspiCli.ContextFlags inFlags)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- fixed (char* arg1Ptr = credential, arg2Ptr = context)
- {
- const int SizeData = 3;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (credential.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[1].Size = (context.Length + 1) * sizeof(char);
- dataDesc[2].DataPointer = (IntPtr)(&inFlags);
- dataDesc[2].Size = sizeof(int);
-
- WriteEventCore(AcceptSecuritContextId, SizeData, dataDesc);
- }
- }
-
- [Event(OperationReturnedSomethingId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void OperationReturnedSomething(string operation, Interop.SECURITY_STATUS errorCode)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(OperationReturnedSomethingId, operation, errorCode);
- }
-
- [Event(SecurityContextInputBufferId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void SecurityContextInputBuffer(string context, int inputBufferSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- fixed (char* arg1Ptr = context)
- {
- const int SizeData = 4;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (context.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(&inputBufferSize);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(&outputBufferSize);
- dataDesc[2].Size = sizeof(int);
- dataDesc[3].DataPointer = (IntPtr)(&errorCode);
- dataDesc[3].Size = sizeof(int);
-
- WriteEventCore(SecurityContextInputBufferId, SizeData, dataDesc);
- }
- }
-
- [Event(SecurityContextInputBuffersId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void SecurityContextInputBuffers(string context, int inputBuffersSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- fixed (char* arg1Ptr = context)
- {
- const int SizeData = 4;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (context.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(&inputBuffersSize);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(&outputBufferSize);
- dataDesc[2].Size = sizeof(int);
- dataDesc[3].DataPointer = (IntPtr)(&errorCode);
- dataDesc[3].Size = sizeof(int);
-
- WriteEventCore(SecurityContextInputBuffersId, SizeData, dataDesc);
- }
- }
- }
-}
diff --git a/src/Common/src/System/Net/Logging/SecurityEventSource.cs b/src/Common/src/System/Net/Logging/SecurityEventSource.cs
deleted file mode 100644
index 18a1664539..0000000000
--- a/src/Common/src/System/Net/Logging/SecurityEventSource.cs
+++ /dev/null
@@ -1,425 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-using System.Globalization;
-using System.Net.Security;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-
-namespace System.Net
-{
- //TODO: If localization resources are not found, logging does not work. Issue #5126.
- [EventSource(Name = "Microsoft-System-Net-Security",
- Guid = "066c0e27-a02d-5a98-9a4d-078cc3b1a896",
- LocalizationResources = "FxResources.System.Net.Security.SR")]
- internal sealed partial class SecurityEventSource : EventSource
- {
- private const int EnumerateSecurityPackagesId = 1;
- private const int SspiPackageNotFoundId = 2;
- private const int AcquireDefaultCredentialId = 3;
- private const int AcquireCredentialsHandleId = 4;
- private const int SecureChannelCtorId = 5;
- private const int LocatingPrivateKeyId = 6;
- private const int CertIsType2Id = 7;
- private const int FoundCertInStoreId = 8;
- private const int NotFoundCertInStoreId = 9;
- private const int InitializeSecurityContextId = 10;
- private const int SecurityContextInputBufferId = 11;
- private const int SecurityContextInputBuffersId = 12;
- private const int AcceptSecuritContextId = 13;
- private const int OperationReturnedSomethingId = 14;
- private const int RemoteCertificateId = 15;
- private const int CertificateFromDelegateId = 16;
- private const int NoDelegateNoClientCertId = 17;
- private const int NoDelegateButClientCertId = 18;
- private const int AttemptingRestartUsingCertId = 19;
- private const int NoIssuersTryAllCertsId = 20;
- private const int LookForMatchingCertsId = 21;
- private const int SelectedCertId = 22;
- private const int CertsAfterFilteringId = 23;
- private const int FindingMatchingCertsId = 24;
- private const int UsingCachedCredentialId = 25;
- private const int SspiSelectedCipherSuitId = 26;
- private const int RemoteCertificateErrorId = 27;
- private const int RemoteVertificateValidId = 28;
- private const int RemoteCertificateSuccesId = 29;
- private const int REmoteCertificateInvalidId = 30;
-
- private readonly static SecurityEventSource s_log = new SecurityEventSource();
- private SecurityEventSource() { }
- public static SecurityEventSource Log
- {
- get
- {
- return s_log;
- }
- }
-
- [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void EnumerateSecurityPackages(string securityPackage)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- string arg1Str = "";
- if (securityPackage != null)
- {
- arg1Str = securityPackage;
- }
-
- s_log.WriteEvent(EnumerateSecurityPackagesId, arg1Str);
- }
-
- [Event(SspiPackageNotFoundId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void SspiPackageNotFound(string packageName)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- string arg1Str = "";
- if (packageName != null)
- {
- arg1Str = packageName;
- }
-
- s_log.WriteEvent(SspiPackageNotFoundId, arg1Str);
- }
-
- [NonEvent]
- internal static void SecureChannelCtor(
- object secureChannel,
- string hostname,
- X509CertificateCollection clientCertificates,
- EncryptionPolicy encryptionPolicy)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- int clientCertificatesCount = 0;
- string arg1Str = "";
- if (clientCertificates != null)
- {
- clientCertificatesCount = clientCertificates.Count;
- }
-
- if (hostname != null)
- {
- arg1Str = hostname;
- }
-
- s_log.SecureChannelCtor(arg1Str, LoggingHash.HashInt(secureChannel), clientCertificatesCount, encryptionPolicy);
- }
-
- [Event(SecureChannelCtorId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void SecureChannelCtor(string hostname, int secureChannelHash, int clientCertificatesCount, EncryptionPolicy encryptionPolicy)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- fixed (char* arg1Ptr = hostname)
- {
- const int SizeData = 4;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (hostname.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(&secureChannelHash);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(&clientCertificatesCount);
- dataDesc[2].Size = sizeof(int);
- dataDesc[3].DataPointer = (IntPtr)(&encryptionPolicy);
- dataDesc[3].Size = sizeof(int);
-
- WriteEventCore(SecureChannelCtorId, SizeData, dataDesc);
- }
- }
-
- [Event(LocatingPrivateKeyId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void LocatingPrivateKey(string x509Certificate, int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(LocatingPrivateKeyId, x509Certificate, secureChannelHash);
- }
-
- [Event(CertIsType2Id, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void CertIsType2(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(CertIsType2Id, secureChannelHash);
- }
-
- [Event(FoundCertInStoreId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void FoundCertInStore(string store, int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(FoundCertInStoreId, store, secureChannelHash);
- }
-
- [Event(NotFoundCertInStoreId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void NotFoundCertInStore(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(NotFoundCertInStoreId, secureChannelHash);
- }
-
- [Event(RemoteCertificateId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void RemoteCertificate(string remoteCertificate)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(RemoteCertificateId, remoteCertificate);
- }
-
-
- [Event(CertificateFromDelegateId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void CertificateFromDelegate(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(CertificateFromDelegateId, secureChannelHash);
- }
-
- [Event(NoDelegateNoClientCertId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void NoDelegateNoClientCert(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(NoDelegateNoClientCertId, secureChannelHash);
- }
-
- [Event(NoDelegateButClientCertId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void NoDelegateButClientCert(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(NoDelegateButClientCertId, secureChannelHash);
- }
-
- [Event(AttemptingRestartUsingCertId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void AttemptingRestartUsingCert(string clientCertificate, int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(AttemptingRestartUsingCertId, clientCertificate, secureChannelHash);
- }
-
- [Event(NoIssuersTryAllCertsId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void NoIssuersTryAllCerts(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(NoIssuersTryAllCertsId, secureChannelHash);
- }
-
- [Event(LookForMatchingCertsId, Keywords = Keywords.Default,
-Level = EventLevel.Informational)]
- internal void LookForMatchingCerts(int issuersCount, int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(LookForMatchingCertsId, issuersCount, secureChannelHash);
- }
-
- [Event(SelectedCertId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void SelectedCert(string clientCertificate, int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(SelectedCertId, clientCertificate, secureChannelHash);
- }
-
- [Event(CertsAfterFilteringId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void CertsAfterFiltering(int filteredCertsCount, int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(CertsAfterFilteringId, filteredCertsCount, secureChannelHash);
- }
-
- [Event(FindingMatchingCertsId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void FindingMatchingCerts(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(FindingMatchingCertsId, secureChannelHash);
- }
-
- [Event(UsingCachedCredentialId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void UsingCachedCredential(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(UsingCachedCredentialId, secureChannelHash);
- }
-
- [Event(SspiSelectedCipherSuitId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void SspiSelectedCipherSuite(
- string process,
- SslProtocols sslProtocol,
- CipherAlgorithmType cipherAlgorithm,
- int cipherStrength,
- HashAlgorithmType hashAlgorithm,
- int hashStrength,
- ExchangeAlgorithmType keyExchangeAlgorithm,
- int keyExchangeStrength)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- fixed (char* arg1Ptr = process)
- {
- const int SizeData = 8;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (process.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(&sslProtocol);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(&cipherAlgorithm);
- dataDesc[2].Size = sizeof(int);
- dataDesc[3].DataPointer = (IntPtr)(&cipherStrength);
- dataDesc[3].Size = sizeof(int);
- dataDesc[4].DataPointer = (IntPtr)(&hashAlgorithm);
- dataDesc[4].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(&hashStrength);
- dataDesc[2].Size = sizeof(int);
- dataDesc[3].DataPointer = (IntPtr)(&keyExchangeAlgorithm);
- dataDesc[3].Size = sizeof(int);
- dataDesc[4].DataPointer = (IntPtr)(&keyExchangeStrength);
- dataDesc[4].Size = sizeof(int);
- WriteEventCore(SspiSelectedCipherSuitId, SizeData, dataDesc);
- }
- }
-
- [Event(RemoteCertificateErrorId, Keywords = Keywords.Default,
- Level = EventLevel.Verbose)]
- internal void RemoteCertificateError(int secureChannelHash, string message)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(RemoteCertificateErrorId, secureChannelHash, message);
- }
-
- [Event(RemoteVertificateValidId, Keywords = Keywords.Default,
- Level = EventLevel.Verbose)]
- internal void RemoteCertDeclaredValid(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(RemoteVertificateValidId, secureChannelHash);
- }
-
- [Event(RemoteCertificateSuccesId, Keywords = Keywords.Default,
- Level = EventLevel.Verbose)]
- internal void RemoteCertHasNoErrors(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(RemoteCertificateSuccesId, secureChannelHash);
- }
-
- [Event(REmoteCertificateInvalidId, Keywords = Keywords.Default,
- Level = EventLevel.Verbose)]
- internal void RemoteCertUserDeclaredInvalid(int secureChannelHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(REmoteCertificateInvalidId, secureChannelHash);
- }
-
- public class Keywords
- {
- public const EventKeywords Default = (EventKeywords)0x0001;
- public const EventKeywords Debug = (EventKeywords)0x0002;
- }
- }
-}
diff --git a/src/Common/src/System/Net/Logging/SocketsEventSource.cs b/src/Common/src/System/Net/Logging/SocketsEventSource.cs
deleted file mode 100644
index 9f8104d27b..0000000000
--- a/src/Common/src/System/Net/Logging/SocketsEventSource.cs
+++ /dev/null
@@ -1,219 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics.Tracing;
-using System.Globalization;
-using System.Net.Sockets;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-namespace System.Net
-{
- //TODO: If localization resources are not found, logging does not work. Issue #5126.
- [EventSource(Name = "Microsoft-System-Net-Sockets",
- Guid = "e03c0352-f9c9-56ff-0ea7-b94ba8cabc6b",
- LocalizationResources = "FxResources.System.Net.Sockets.SR")]
- internal sealed class SocketsEventSource : EventSource
- {
- private const int AcceptedId = 1;
- private const int ConnectedId = 2;
- private const int ConnectedAsyncDnsId = 3;
- private const int NotLoggedFileId = 4;
- private const int DumpArrayId = 5;
-
- private const int DefaultMaxDumpSize = 1024;
-
- private readonly static SocketsEventSource s_log = new SocketsEventSource();
- private SocketsEventSource() { }
- public static SocketsEventSource Log
- {
- get
- {
- return s_log;
- }
- }
-
- [NonEvent]
- internal static void Accepted(Socket socket, object remoteEp, object localEp)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- s_log.Accepted(LoggingHash.GetObjectName(remoteEp), LoggingHash.GetObjectName(localEp), LoggingHash.HashInt(socket));
- }
-
- [Event(AcceptedId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void Accepted(string remoteEp, string localEp, int socketHash)
- {
- fixed (char* arg1Ptr = remoteEp, arg2Ptr = localEp)
- {
- const int SizeData = 3;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (remoteEp.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[1].Size = (localEp.Length + 1) * sizeof(char);
- dataDesc[2].DataPointer = (IntPtr)(&socketHash);
- dataDesc[2].Size = sizeof(int);
-
- WriteEventCore(AcceptedId, SizeData, dataDesc);
- }
- }
-
- [NonEvent]
- internal static void Connected(Socket socket, object localEp, object remoteEp)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- s_log.Connected(LoggingHash.GetObjectName(localEp), LoggingHash.GetObjectName(remoteEp), LoggingHash.HashInt(socket));
- }
-
- [Event(ConnectedId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void Connected(string localEp, string remoteEp, int socketHash)
- {
- fixed (char* arg1Ptr = localEp, arg2Ptr = remoteEp)
- {
- const int SizeData = 3;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (localEp.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(arg2Ptr);
- dataDesc[1].Size = (remoteEp.Length + 1) * sizeof(char);
- dataDesc[2].DataPointer = (IntPtr)(&socketHash);
- dataDesc[2].Size = sizeof(int);
-
- WriteEventCore(ConnectedId, SizeData, dataDesc);
- }
- }
-
- [Event(ConnectedAsyncDnsId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal void ConnectedAsyncDns(int socketHash)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- WriteEvent(ConnectedAsyncDnsId, socketHash);
- }
-
- [Event(NotLoggedFileId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void NotLoggedFile(string filePath, int socketHash, SocketAsyncOperation completedOperation)
- {
- fixed (char* arg1Ptr = filePath)
- {
- const int SizeData = 3;
- EventData* dataDesc = stackalloc EventSource.EventData[SizeData];
- dataDesc[0].DataPointer = (IntPtr)(arg1Ptr);
- dataDesc[0].Size = (filePath.Length + 1) * sizeof(char);
- dataDesc[1].DataPointer = (IntPtr)(&completedOperation);
- dataDesc[1].Size = sizeof(int);
- dataDesc[2].DataPointer = (IntPtr)(&socketHash);
- dataDesc[2].Size = sizeof(int);
-
- WriteEventCore(NotLoggedFileId, SizeData, dataDesc);
- }
- }
-
- [NonEvent]
- internal static void Dump(IntPtr bufferPtr, int length, [CallerMemberName] string callerName = "")
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- if (length > DefaultMaxDumpSize)
- {
- length = DefaultMaxDumpSize;
- }
-
- byte[] buffer = new byte[length];
- Marshal.Copy(bufferPtr, buffer, 0, length);
- s_log.DebugDumpArray(buffer, callerName);
- }
-
- [NonEvent]
- internal static void Dump(byte[] buffer, int offset, int length, [CallerMemberName] string callerName = "")
- {
- if (!s_log.IsEnabled() || offset > buffer.Length)
- {
- return;
- }
-
- if (length > DefaultMaxDumpSize)
- {
- length = DefaultMaxDumpSize;
- }
-
- if ((length < 0) || (length > buffer.Length - offset))
- {
- length = buffer.Length - offset;
- }
-
- byte[] partialBuffer = new byte[length];
- Buffer.BlockCopy(buffer, offset, partialBuffer, 0, length);
- s_log.DebugDumpArray(partialBuffer, callerName);
- }
-
- [Event(DumpArrayId, Keywords = Keywords.Default,
- Level = EventLevel.Informational)]
- internal unsafe void DebugDumpArray(byte[] buffer, string callerMemberName)
- {
- if (!s_log.IsEnabled())
- {
- return;
- }
-
- const int SizeData = 3;
- EventSource.EventData* descrs = stackalloc EventSource.EventData[SizeData];
- if (buffer == null || buffer.Length == 0)
- {
- int blobSize = 0;
- fixed (char* arg1Ptr = callerMemberName)
- {
-
- descrs[0].DataPointer = (IntPtr)(&blobSize);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)(&blobSize); // Valid address instead of empty contents.
- descrs[1].Size = 0;
- descrs[2].DataPointer = (IntPtr)(arg1Ptr);
- descrs[2].Size = (callerMemberName.Length + 1) * sizeof(char);
- WriteEventCore(DumpArrayId, SizeData, descrs);
- }
- }
- else
- {
- int blobSize = buffer.Length;
- fixed (byte* blob = &buffer[0])
- fixed (char* arg1Ptr = callerMemberName)
- {
-
- descrs[0].DataPointer = (IntPtr)(&blobSize);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)blob;
- descrs[1].Size = blobSize;
- descrs[2].DataPointer = (IntPtr)(arg1Ptr);
- descrs[2].Size = (callerMemberName.Length + 1) * sizeof(char);
- WriteEventCore(DumpArrayId, SizeData, descrs);
- }
- }
- }
-
- public class Keywords
- {
- public const EventKeywords Default = (EventKeywords)0x0001;
- public const EventKeywords Debug = (EventKeywords)0x0002;
- }
- }
-}
diff --git a/src/Common/src/System/Net/SafeCloseSocket.Unix.cs b/src/Common/src/System/Net/SafeCloseSocket.Unix.cs
index 2017f63a60..2722d03c42 100644
--- a/src/Common/src/System/Net/SafeCloseSocket.Unix.cs
+++ b/src/Common/src/System/Net/SafeCloseSocket.Unix.cs
@@ -123,10 +123,7 @@ namespace System.Net.Sockets
// case we need to do some recovery.
if (_blockable)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") Following 'blockable' branch.");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle} Following 'blockable' branch.");
errorCode = Interop.Sys.Close(handle);
if (errorCode == -1)
@@ -134,10 +131,7 @@ namespace System.Net.Sockets
errorCode = (int)Interop.Sys.GetLastError();
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#1:" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#1:{errorCode}");
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
@@ -157,10 +151,7 @@ namespace System.Net.Sockets
// The socket successfully made blocking; retry the close().
errorCode = Interop.Sys.Close(handle);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#2:" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#2:{errorCode}");
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
@@ -181,10 +172,7 @@ namespace System.Net.Sockets
#if DEBUG
_closeSocketLinger = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") setsockopt():" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}");
if (errorCode != 0 && errorCode != (int)Interop.Error.EINVAL && errorCode != (int)Interop.Error.ENOPROTOOPT)
{
@@ -197,10 +185,7 @@ namespace System.Net.Sockets
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close#3():" + (errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode).ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close#3():{(errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode)}");
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
diff --git a/src/Common/src/System/Net/SafeCloseSocket.Windows.cs b/src/Common/src/System/Net/SafeCloseSocket.Windows.cs
index e905eecf2f..85565268d4 100644
--- a/src/Common/src/System/Net/SafeCloseSocket.Windows.cs
+++ b/src/Common/src/System/Net/SafeCloseSocket.Windows.cs
@@ -47,10 +47,7 @@ namespace System.Net.Sockets
if (_iocpBoundHandle == null)
{
// Bind the socket native _handle to the ThreadPool.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket#" + LoggingHash.HashString(this) + "::BindToCompletionPort() calling ThreadPool.BindHandle()");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, "calling ThreadPool.BindHandle()");
try
{
@@ -111,21 +108,15 @@ namespace System.Net.Sockets
// case we need to do some recovery.
if (_blockable)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") Following 'blockable' branch.");
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, Following 'blockable' branch");
errorCode = Interop.Winsock.closesocket(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = errorCode;
#endif
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket()#1:" + errorCode.ToString());
- }
+
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket()#1:{errorCode}");
// If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != SocketError.WouldBlock)
@@ -142,10 +133,7 @@ namespace System.Net.Sockets
ref nonBlockCmd);
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") ioctlsocket()#1:" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, ioctlsocket()#1:{errorCode}");
// This can fail if there's a pending WSAEventSelect. Try canceling it.
if (errorCode == SocketError.InvalidArgument)
@@ -155,10 +143,7 @@ namespace System.Net.Sockets
IntPtr.Zero,
Interop.Winsock.AsyncEventBits.FdNone);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") WSAEventSelect():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, WSAEventSelect()#1:{(errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode)}");
// Now retry the ioctl.
errorCode = Interop.Winsock.ioctlsocket(
@@ -166,10 +151,7 @@ namespace System.Net.Sockets
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref nonBlockCmd);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") ioctlsocket#2():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, ioctlsocket()#2:{(errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode)}");
}
// If that succeeded, try again.
@@ -181,10 +163,7 @@ namespace System.Net.Sockets
_closeSocketResult = errorCode;
#endif
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket#2():" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#2():{errorCode}");
// If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != SocketError.WouldBlock)
@@ -211,10 +190,7 @@ namespace System.Net.Sockets
_closeSocketLinger = errorCode;
#endif
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") setsockopt():" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}");
if (errorCode != SocketError.Success && errorCode != SocketError.InvalidArgument && errorCode != SocketError.ProtocolOption)
{
@@ -227,10 +203,7 @@ namespace System.Net.Sockets
_closeSocketHandle = handle;
_closeSocketResult = errorCode;
#endif
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket#3():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#3():{(errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode)}");
return errorCode;
}
diff --git a/src/Common/src/System/Net/SafeCloseSocket.cs b/src/Common/src/System/Net/SafeCloseSocket.cs
index e03bb8787e..2332340d29 100644
--- a/src/Common/src/System/Net/SafeCloseSocket.cs
+++ b/src/Common/src/System/Net/SafeCloseSocket.cs
@@ -97,10 +97,7 @@ namespace System.Net.Sockets
SafeCloseSocket ret = new SafeCloseSocket();
CreateSocket(socket, ret);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket#" + LoggingHash.HashString(ret) + "::CreateSocket()");
- }
+ NetEventSource.Info(null, ret);
return ret;
}
@@ -142,12 +139,7 @@ namespace System.Net.Sockets
protected override bool ReleaseHandle()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SafeCloseSocket#" + LoggingHash.HashString(this) + "::ReleaseHandle() m_InnerSocket=" +
- (_innerSocket == null ? "null" : LoggingHash.HashString(_innerSocket)));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_innerSocket={_innerSocket}");
_released = true;
InnerSafeCloseSocket innerSocket = _innerSocket == null ? null : Interlocked.Exchange<InnerSafeCloseSocket>(ref _innerSocket, null);
@@ -169,15 +161,10 @@ namespace System.Net.Sockets
internal void CloseAsIs()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SafeCloseSocket#" + LoggingHash.HashString(this) + "::CloseAsIs() m_InnerSocket=" +
- (_innerSocket == null ? "null" : LoggingHash.HashString(_innerSocket)));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_innerSocket={_innerSocket}");
#if DEBUG
- // If this throws it could be very bad.
+ // If this throws it could be very bad.
try
{
#endif
@@ -200,16 +187,9 @@ namespace System.Net.Sockets
InnerReleaseHandle();
#if DEBUG
}
- catch (Exception exception)
+ catch (Exception exception) when (!ExceptionCheck.IsFatal(exception))
{
- if (!ExceptionCheck.IsFatal(exception))
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeCloseSocket::CloseAsIs(handle:" + handle.ToString("x") + ")", exception.Message);
- }
- Debug.Fail("SafeCloseSocket::CloseAsIs(handle:" + handle.ToString("x") + ")", exception.Message);
- }
+ NetEventSource.Fail(this, $"handle:{handle}, error:{exception}");
throw;
}
#endif
@@ -238,10 +218,7 @@ namespace System.Net.Sockets
try
{
#endif
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}");
SocketError errorCode = InnerReleaseHandle();
return ret = errorCode == SocketError.Success;
@@ -251,12 +228,9 @@ namespace System.Net.Sockets
{
if (!ExceptionCheck.IsFatal(exception))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ")", exception.Message);
- }
- Debug.Fail("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ")", exception.Message);
+ NetEventSource.Fail(this, $"handle:{handle}, error:{exception}");
}
+
ret = true; // Avoid a second assert.
throw;
}
@@ -266,11 +240,7 @@ namespace System.Net.Sockets
_closeSocketTick = Environment.TickCount;
if (!ret)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("SafeCloseSocket::ReleaseHandle(handle:{0:x})|ReleaseHandle failed.", handle);
- }
- Debug.Fail("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ")|ReleaseHandle failed.");
+ NetEventSource.Fail(this, $"ReleaseHandle failed. handle:{handle}");
}
}
#endif
@@ -300,10 +270,7 @@ namespace System.Net.Sockets
public void LogRemainingOperations()
{
Interlocked.MemoryBarrier();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("InnerSafeCloseSocket: Releasing with pending operations: " + _refCount);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing with pending operations: {_refCount}");
}
#endif
diff --git a/src/System.Net.Http/System.Net.Http.sln b/src/System.Net.Http/System.Net.Http.sln
index b0c9d85223..060f5b1ee2 100644
--- a/src/System.Net.Http/System.Net.Http.sln
+++ b/src/System.Net.Http/System.Net.Http.sln
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
-VisualStudioVersion = 14.0.23107.0
+VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http", "src\System.Net.Http.csproj", "{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}"
EndProject
@@ -28,18 +28,18 @@ Global
Windows_Release|Any CPU = Windows_Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Debug|Any CPU.ActiveCfg = Windows_netcore50_Debug|Any CPU
- {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Debug|Any CPU.Build.0 = Windows_netcore50_Debug|Any CPU
+ {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Debug|Any CPU.ActiveCfg = Windows_uap101_Debug|Any CPU
+ {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Debug|Any CPU.Build.0 = Windows_uap101_Debug|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Unix_Debug|Any CPU.ActiveCfg = Unix_Debug|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Unix_Debug|Any CPU.Build.0 = Unix_Debug|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Unix_Release|Any CPU.ActiveCfg = Unix_Release|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Unix_Release|Any CPU.Build.0 = Unix_Release|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_Debug|Any CPU.ActiveCfg = Windows_Debug|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_Debug|Any CPU.Build.0 = Windows_Debug|Any CPU
- {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Debug|Any CPU.ActiveCfg = Windows_netcore50_Debug|Any CPU
- {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Debug|Any CPU.Build.0 = Windows_netcore50_Debug|Any CPU
- {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Release|Any CPU.ActiveCfg = Windows_netcore50_Release|Any CPU
- {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Release|Any CPU.Build.0 = Windows_netcore50_Release|Any CPU
+ {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Debug|Any CPU.ActiveCfg = Windows_uap101_Release|Any CPU
+ {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Debug|Any CPU.Build.0 = Windows_uap101_Release|Any CPU
+ {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Release|Any CPU.ActiveCfg = Windows_uap101_Release|Any CPU
+ {1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_netcore50_Release|Any CPU.Build.0 = Windows_uap101_Release|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_Release|Any CPU.ActiveCfg = Windows_Release|Any CPU
{1D422B1D-D7C4-41B9-862D-EB3D98DF37DE}.Windows_Release|Any CPU.Build.0 = Windows_Release|Any CPU
{C85CF035-7804-41FF-9557-48B7C948B58D}.Debug|Any CPU.ActiveCfg = Windows_Debug|Any CPU
diff --git a/src/System.Net.Http/src/System.Net.Http.csproj b/src/System.Net.Http/src/System.Net.Http.csproj
index f0b30755ff..cdd5c6f044 100644
--- a/src/System.Net.Http/src/System.Net.Http.csproj
+++ b/src/System.Net.Http/src/System.Net.Http.csproj
@@ -50,6 +50,7 @@
<Compile Include="System\Net\Http\MessageProcessingHandler.cs" />
<Compile Include="System\Net\Http\MultipartContent.cs" />
<Compile Include="System\Net\Http\MultipartFormDataContent.cs" />
+ <Compile Include="System\Net\Http\NetEventSource.Http.cs" />
<Compile Include="System\Net\Http\StreamContent.cs" />
<Compile Include="System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="System\Net\Http\StringContent.cs" />
@@ -121,14 +122,8 @@
<Compile Include="$(CommonPath)\System\IO\DelegatingStream.cs">
<Link>Common\System\IO\DelegatingStream.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\HttpEventSource.cs">
- <Link>Common\System\Net\Logging\HttpEventSource.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(TargetGroup)' != 'uap101' ">
diff --git a/src/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs b/src/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs
index c0f5a1144e..002b1a83e3 100644
--- a/src/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs
@@ -30,7 +30,7 @@ namespace System.Net.Http
}
CheckDisposedOrStarted();
- if (HttpEventSource.Log.IsEnabled()) HttpEventSource.Associate(this, value);
+ NetEventSource.Associate(this, value);
_innerHandler = value;
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/ByteArrayHeaderParser.cs b/src/System.Net.Http/src/System/Net/Http/Headers/ByteArrayHeaderParser.cs
index 745fa7cf98..aae1cb1bbf 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/ByteArrayHeaderParser.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/ByteArrayHeaderParser.cs
@@ -49,7 +49,7 @@ namespace System.Net.Http.Headers
}
catch (FormatException e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_parser_invalid_base64_string, base64String, e.Message));
+ if (NetEventSource.IsEnabled) NetEventSource.Error(this, SR.Format(SR.net_http_parser_invalid_base64_string, base64String, e.Message));
}
return false;
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs b/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs
index f7e459dccf..9b3d13757c 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs
@@ -79,7 +79,7 @@ namespace System.Net.Http.Headers
return qualityValue;
}
// If the stored value is an invalid quality value, just return null and log a warning.
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_invalid_quality, qualityParameter.Value));
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_invalid_quality, qualityParameter.Value));
}
return null;
}
@@ -307,7 +307,7 @@ namespace System.Net.Http.Headers
}
catch (FormatException e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_wrong_email_format, value, e.Message));
+ NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_wrong_email_format, value, e.Message));
}
return false;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs b/src/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs
index 28ee031ab7..b8f13235c4 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs
@@ -814,7 +814,7 @@ namespace System.Net.Http.Headers
{
if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true))
{
- if (HttpEventSource.Log.IsEnabled()) HttpEventSource.Log.HeadersInvalidValue(name, rawValue);
+ NetEventSource.Log.HeadersInvalidValue(name, rawValue);
}
}
}
@@ -836,7 +836,7 @@ namespace System.Net.Http.Headers
{
if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true))
{
- if (HttpEventSource.Log.IsEnabled()) HttpEventSource.Log.HeadersInvalidValue(name, rawValue);
+ NetEventSource.Log.HeadersInvalidValue(name, rawValue);
}
}
}
@@ -1170,7 +1170,7 @@ namespace System.Net.Http.Headers
{
if (HttpRuleParser.ContainsInvalidNewLine(value))
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_no_newlines, name, value));
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_no_newlines, name, value));
return true;
}
return false;
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpClient.cs b/src/System.Net.Http/src/System/Net/Http/HttpClient.cs
index 634a5ff883..9e4cb550b0 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpClient.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpClient.cs
@@ -55,7 +55,7 @@ namespace System.Net.Http
CheckBaseAddress(value, "value");
CheckDisposedOrStarted();
- if (HttpEventSource.Log.IsEnabled()) HttpEventSource.UriBaseAddress(this, value != null ? value.ToString() : string.Empty);
+ NetEventSource.UriBaseAddress(this, value);
_baseAddress = value;
}
@@ -112,13 +112,13 @@ namespace System.Net.Http
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", handler);
+ NetEventSource.Enter(this, handler);
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Exit(this);
}
#endregion Constructors
@@ -359,7 +359,7 @@ namespace System.Net.Http
await response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize).ConfigureAwait(false);
}
- if (HttpEventSource.Log.IsEnabled()) HttpEventSource.ClientSendCompleted(this, response, request);
+ NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
@@ -376,7 +376,7 @@ namespace System.Net.Http
else
{
LogSendError(request, linkedCts, nameof(SendAsync), e);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, nameof(SendAsync), e);
+ NetEventSource.Error(this, e);
throw;
}
}
@@ -399,8 +399,7 @@ namespace System.Net.Http
public void CancelPendingRequests()
{
CheckDisposed();
-
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
+ NetEventSource.Enter(this);
// With every request we link this cancellation token source.
CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
@@ -409,7 +408,7 @@ namespace System.Net.Http
currentCts.Cancel();
currentCts.Dispose();
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
+ NetEventSource.Exit(this);
}
#endregion Advanced Send Overloads
@@ -546,15 +545,17 @@ namespace System.Net.Http
string method, Exception e)
{
Debug.Assert(request != null);
-
- if (cancellationTokenSource.IsCancellationRequested)
- {
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_canceled, LoggingHash.GetObjectLogHash(request)));
- }
- else
+ if (NetEventSource.IsEnabled)
{
- Debug.Assert(e != null);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_error, LoggingHash.GetObjectLogHash(request), e));
+ if (cancellationTokenSource.IsCancellationRequested)
+ {
+ NetEventSource.Error(this, $"Method={method} Error{SR.Format(SR.net_http_client_send_canceled, NetEventSource.GetHashCode(request))}");
+ }
+ else
+ {
+ Debug.Assert(e != null);
+ NetEventSource.Error(this, $"Method={method} Error{SR.Format(SR.net_http_client_send_error, NetEventSource.GetHashCode(request), e)}");
+ }
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpContent.cs b/src/System.Net.Http/src/System/Net/Http/HttpContent.cs
index 099baab945..a0cb926805 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpContent.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpContent.cs
@@ -151,12 +151,12 @@ namespace System.Net.Http
protected HttpContent()
{
// Log to get an ID for the current content. This ID is used when the content gets associated to a message.
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Enter(this);
// We start with the assumption that we can calculate the content length.
_canCalculateLength = true;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Exit(this);
}
public Task<string> ReadAsStringAsync()
@@ -375,7 +375,7 @@ namespace System.Net.Http
}
catch (Exception e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, nameof(LoadIntoBufferAsync), e);
+ NetEventSource.Error(this, e);
throw;
}
}
@@ -490,8 +490,9 @@ namespace System.Net.Http
{
if (task == null)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_content_no_task_returned_copytoasync, this.GetType().ToString()));
- throw new InvalidOperationException(SR.net_http_content_no_task_returned);
+ var e = new InvalidOperationException(SR.net_http_content_no_task_returned);
+ NetEventSource.Error(this, e);
+ throw e;
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpMessageHandler.cs b/src/System.Net.Http/src/System/Net/Http/HttpMessageHandler.cs
index 6966a16091..46c8e313e0 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpMessageHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpMessageHandler.cs
@@ -14,8 +14,7 @@ namespace System.Net.Http
{
protected HttpMessageHandler()
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", null);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Info(this);
}
protected internal abstract Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs b/src/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs
index 7bf9b0e957..a1ca80a56b 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs
@@ -22,19 +22,19 @@ namespace System.Net.Http
public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", handler);
+ NetEventSource.Enter(this, handler);
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
- if (HttpEventSource.Log.IsEnabled()) HttpEventSource.Associate(this, handler);
+ NetEventSource.Associate(this, handler);
_handler = handler;
_disposeHandler = disposeHandler;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Exit(this);
}
public virtual Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
@@ -46,13 +46,11 @@ namespace System.Net.Http
}
CheckDisposed();
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(NetEventSource.ComponentType.Http, this, "SendAsync",
- LoggingHash.GetObjectLogHash(request) + ": " + request);
+ NetEventSource.Enter(this, request);
Task<HttpResponseMessage> task = _handler.SendAsync(request, cancellationToken);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, "SendAsync", task);
+ NetEventSource.Exit(this, task);
return task;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs b/src/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs
index 72e5cd9afc..14968e99d8 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs
@@ -49,15 +49,15 @@ namespace System.Net.Http
{
CheckDisposed();
- if (HttpEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
if (value == null)
{
- HttpEventSource.ContentNull(this);
+ NetEventSource.ContentNull(this);
}
else
{
- HttpEventSource.Associate(this, value);
+ NetEventSource.Associate(this, value);
}
}
@@ -129,16 +129,16 @@ namespace System.Net.Http
public HttpRequestMessage(HttpMethod method, Uri requestUri)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "Method: " + method + ", Uri: '" + requestUri + "'");
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, method, requestUri);
InitializeValues(method, requestUri);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Exit(this);
}
[SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads",
Justification = "It is OK to provide 'null' values. A Uri instance is created from 'requestUri' if it is != null.")]
public HttpRequestMessage(HttpMethod method, string requestUri)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "Method: " + method + ", Uri: '" + requestUri + "'");
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, method, requestUri);
// It's OK to have a 'null' request Uri. If HttpClient is used, the 'BaseAddress' will be added.
// If there is no 'BaseAddress', sending this request message will throw.
@@ -152,7 +152,7 @@ namespace System.Net.Http
InitializeValues(method, new Uri(requestUri, UriKind.RelativeOrAbsolute));
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Exit(this);
}
public override string ToString()
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs b/src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs
index 49ea7820da..00cc10f730 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs
@@ -43,15 +43,15 @@ namespace System.Net.Http
{
CheckDisposed();
- if (HttpEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
if (value == null)
{
- HttpEventSource.ContentNull(this);
+ NetEventSource.ContentNull(this);
}
else
{
- HttpEventSource.Associate(this, value);
+ NetEventSource.Associate(this, value);
}
}
@@ -115,7 +115,7 @@ namespace System.Net.Http
set
{
CheckDisposed();
- if (HttpEventSource.Log.IsEnabled() && (value != null)) HttpEventSource.Associate(this, value);
+ if (value != null) NetEventSource.Associate(this, value);
_requestMessage = value;
}
}
@@ -132,7 +132,7 @@ namespace System.Net.Http
public HttpResponseMessage(HttpStatusCode statusCode)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "StatusCode: " + (int)statusCode + ", ReasonPhrase: '" + _reasonPhrase + "'");
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, statusCode);
if (((int)statusCode < 0) || ((int)statusCode > 999))
{
@@ -142,7 +142,7 @@ namespace System.Net.Http
_statusCode = statusCode;
_version = HttpUtilities.DefaultResponseVersion;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
+ NetEventSource.Exit(this);
}
public HttpResponseMessage EnsureSuccessStatusCode()
diff --git a/src/System.Net.Http/src/System/Net/Http/MultipartContent.cs b/src/System.Net.Http/src/System/Net/Http/MultipartContent.cs
index 48cb0be597..957b8f75d4 100644
--- a/src/System.Net.Http/src/System/Net/Http/MultipartContent.cs
+++ b/src/System.Net.Http/src/System/Net/Http/MultipartContent.cs
@@ -196,10 +196,7 @@ namespace System.Net.Http
}
catch (Exception ex)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Http, this, nameof(SerializeToStreamAsync), ex);
- }
+ NetEventSource.Error(this, ex);
throw;
}
}
@@ -240,10 +237,7 @@ namespace System.Net.Http
}
catch (Exception ex)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Http, this, nameof(CreateContentReadStreamAsync), ex);
- }
+ NetEventSource.Error(this, ex);
throw;
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs b/src/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs
new file mode 100644
index 0000000000..2f3c59bdbc
--- /dev/null
+++ b/src/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs
@@ -0,0 +1,67 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using System.Net.Http;
+
+namespace System.Net
+{
+ //TODO: If localization resources are not found, logging does not work. Issue #5126.
+ [EventSource(Name = "Microsoft-System-Net-Http", LocalizationResources = "FxResources.System.Net.Http.SR")]
+ internal sealed partial class NetEventSource : EventSource
+ {
+ private const int UriBaseAddressId = NextAvailableEventId;
+ private const int ContentNullId = UriBaseAddressId + 1;
+ private const int ClientSendCompletedId = ContentNullId + 1;
+ private const int HeadersInvalidValueId = ClientSendCompletedId + 1;
+ private const int HandlerMessageId = HeadersInvalidValueId + 1;
+
+ [NonEvent]
+ public static void UriBaseAddress(object obj, Uri baseAddress)
+ {
+ if (IsEnabled)
+ {
+ Log.UriBaseAddress(baseAddress?.ToString(), IdOf(obj), GetHashCode(obj));
+ }
+ }
+
+ [Event(UriBaseAddressId, Keywords = Keywords.Debug, Level = EventLevel.Informational)]
+ private unsafe void UriBaseAddress(string uriBaseAddress, string objName, int objHash) =>
+ WriteEvent(UriBaseAddressId, uriBaseAddress, objName, objHash);
+
+ [NonEvent]
+ public static void ContentNull(object obj)
+ {
+ if (IsEnabled)
+ {
+ Log.ContentNull(IdOf(obj), GetHashCode(obj));
+ }
+ }
+
+ [Event(ContentNullId, Keywords = Keywords.Debug, Level = EventLevel.Informational)]
+ private void ContentNull(string objName, int objHash) =>
+ WriteEvent(ContentNullId, objName, objHash);
+
+ [NonEvent]
+ public static void ClientSendCompleted(HttpClient httpClient, HttpResponseMessage response, HttpRequestMessage request)
+ {
+ if (IsEnabled)
+ {
+ Log.ClientSendCompleted(response?.ToString(), GetHashCode(request), GetHashCode(response), GetHashCode(httpClient));
+ }
+ }
+
+ [Event(ClientSendCompletedId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)]
+ private void ClientSendCompleted(string responseString, int httpRequestMessageHash, int httpResponseMessageHash, int httpClientHash) =>
+ WriteEvent(ClientSendCompletedId, responseString, httpRequestMessageHash, httpResponseMessageHash, httpClientHash);
+
+ [Event(HeadersInvalidValueId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)]
+ public void HeadersInvalidValue(string name, string rawValue) =>
+ WriteEvent(HeadersInvalidValueId, name, rawValue);
+
+ [Event(HandlerMessageId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)]
+ public void HandlerMessage(int workerId, int requestId, string memberName, string message) =>
+ WriteEvent(HandlerMessageId, workerId, requestId, memberName, message);
+ }
+}
diff --git a/src/System.Net.Http/src/System/Net/Http/StreamContent.cs b/src/System.Net.Http/src/System/Net/Http/StreamContent.cs
index 5c0cfd631a..4fad662d34 100644
--- a/src/System.Net.Http/src/System/Net/Http/StreamContent.cs
+++ b/src/System.Net.Http/src/System/Net/Http/StreamContent.cs
@@ -52,7 +52,7 @@ namespace System.Net.Http
{
_start = content.Position;
}
- if (HttpEventSource.Log.IsEnabled()) HttpEventSource.Associate(this, content);
+ NetEventSource.Associate(this, content);
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
diff --git a/src/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs b/src/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs
index 6a8477ca7a..e1ebe5b321 100644
--- a/src/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs
+++ b/src/System.Net.Http/src/System/Net/Http/StreamToStreamCopy.cs
@@ -274,10 +274,7 @@ namespace System.Net.Http
catch (Exception e)
{
// Dispose() should never throw, but since we're on an async codepath, make sure to catch the exception.
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Http, null, nameof(CopyAsync), e);
- }
+ NetEventSource.Error(null, e);
}
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.EasyRequest.cs b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.EasyRequest.cs
index dfb39cdbe5..8128551374 100644
--- a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.EasyRequest.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.EasyRequest.cs
@@ -702,7 +702,7 @@ namespace System.Net.Http
ref _callbackHandle);
}
- if (EventSourceTracingEnabled)
+ if (NetEventSource.IsEnabled)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
CURLcode curlResult = Interop.Http.RegisterDebugCallback(
diff --git a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs
index f782c235e1..ab827dc92a 100644
--- a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs
@@ -167,7 +167,7 @@ namespace System.Net.Http
s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0;
s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing();
- if (HttpEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}");
}
@@ -680,18 +680,16 @@ namespace System.Net.Http
string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal);
}
- private static bool EventSourceTracingEnabled { get { return HttpEventSource.Log.IsEnabled(); } }
-
// PERF NOTE:
// These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler
// nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking
- // EventSourceTracingEnabled. Do not remove these without fixing the call sites accordingly.
+ // NetEventSource.IsEnabled. Do not remove these without fixing the call sites accordingly.
private static void EventSourceTrace<TArg0>(
string formatMessage, TArg0 arg0,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
- if (EventSourceTracingEnabled)
+ if (NetEventSource.IsEnabled)
{
EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName);
}
@@ -701,7 +699,7 @@ namespace System.Net.Http
(string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
- if (EventSourceTracingEnabled)
+ if (NetEventSource.IsEnabled)
{
EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName);
}
@@ -711,7 +709,7 @@ namespace System.Net.Http
string message,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
- if (EventSourceTracingEnabled)
+ if (NetEventSource.IsEnabled)
{
EventSourceTraceCore(message, agent, easy, memberName);
}
@@ -725,7 +723,7 @@ namespace System.Net.Http
agent = easy._associatedMultiAgent;
}
- HttpEventSource.Log.HandlerMessage(
+ NetEventSource.Log.HandlerMessage(
(agent?.RunningWorkerId).GetValueOrDefault(),
easy != null ? easy.Task.Id : 0,
memberName,
diff --git a/src/System.Net.Http/src/netcore50/System/Net/cookie.cs b/src/System.Net.Http/src/netcore50/System/Net/cookie.cs
index 360c528658..bf75fa13aa 100644
--- a/src/System.Net.Http/src/netcore50/System/Net/cookie.cs
+++ b/src/System.Net.Http/src/netcore50/System/Net/cookie.cs
@@ -752,7 +752,7 @@ namespace System.Net
{
// only set by HttpListenerRequest::Cookies_get()
#if !NETNative_SystemNetHttp
- GlobalLog.Assert(value == CookieVariant.Rfc2965, "Cookie#{0}::set_Variant()|value:{1}", Logging.HashString(this), value);
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"value:{value}");
#endif
m_cookieVariant = value;
}
@@ -961,7 +961,7 @@ namespace System.Net
internal void Dump()
{
#if !NETNative_SystemNetHttp
- GlobalLog.Print("Cookie: " + ToString() + "->\n"
+ NetEventSource.Info(this, "Cookie: " + ToString() + "->\n"
+ "\tComment = " + Comment + "\n"
+ "\tCommentUri = " + CommentUri + "\n"
+ "\tDiscard = " + Discard + "\n"
diff --git a/src/System.Net.Http/tests/FunctionalTests/LoggingTest.cs b/src/System.Net.Http/tests/FunctionalTests/LoggingTest.cs
new file mode 100644
index 0000000000..0c84e79fdb
--- /dev/null
+++ b/src/System.Net.Http/tests/FunctionalTests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.Http.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(HttpClient).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-Http", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("bdd9a83e-1929-5482-0d73-2fe5e1c0e16d"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj b/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj
index bdca3f0e97..ae1f17e259 100644
--- a/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj
+++ b/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj
@@ -107,6 +107,9 @@
<Compile Include="SyncBlockingContent.cs" />
<Compile Include="TestHelper.cs" />
</ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' == ''">
+ <Compile Include="LoggingTest.cs" />
+ </ItemGroup>
<ItemGroup Condition=" '$(TargetsWindows)' == 'true' ">
<Compile Include="DefaultCredentialsTest.cs" />
</ItemGroup>
diff --git a/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj b/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj
index a8df130591..3abef02cf2 100644
--- a/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj
+++ b/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj
@@ -44,14 +44,8 @@
<Compile Include="$(CommonPath)\System\Net\HttpVersion.cs">
<Link>ProductionCode\Common\System\Net\HttpVersion.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>ProductionCode\Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\HttpEventSource.cs">
- <Link>ProductionCode\Common\System\Net\Logging\HttpEventSource.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>ProductionCode\Common\System\Net\Logging\NetEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>ProductionCode\Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\ShouldNotBeInvokedException.cs">
<Link>Common\System\ShouldNotBeInvokedException.cs</Link>
@@ -269,6 +263,9 @@
<Compile Include="..\..\src\System\Net\Http\MultipartFormDataContent.cs">
<Link>ProductionCode\System\Net\Http\MultipartFormDataContent.cs</Link>
</Compile>
+ <Compile Include="..\..\src\System\Net\Http\NetEventSource.Http.cs">
+ <Link>ProductionCode\System\Net\Http\NetEventSource.Http.cs</Link>
+ </Compile>
<Compile Include="..\..\src\System\Net\Http\StreamContent.cs">
<Link>ProductionCode\System\Net\Http\StreamContent.cs</Link>
</Compile>
diff --git a/src/System.Net.Mail/src/System.Net.Mail.csproj b/src/System.Net.Mail/src/System.Net.Mail.csproj
index 40ab7c2646..2b3e946b9c 100644
--- a/src/System.Net.Mail/src/System.Net.Mail.csproj
+++ b/src/System.Net.Mail/src/System.Net.Mail.csproj
@@ -52,6 +52,7 @@
<Compile Include="System\Net\Mail\LinkedResourceCollection.cs" />
<Compile Include="System\Net\Mail\MailAddress.cs" />
<Compile Include="System\Net\Mail\MailAddressCollection.cs" />
+ <Compile Include="System\Net\Mail\NetEventSource.Mail.cs" />
<Compile Include="System\Net\Mail\MailMessage.cs" />
<Compile Include="System\Net\Mail\MailPriority.cs" />
<Compile Include="System\Net\Mail\MailWriter.cs" />
@@ -88,14 +89,8 @@
<Compile Include="$(CommonPath)\System\Net\Mail\MailBnfHelper.cs">
<Link>Common\System\Net\Mail\MailBnfHelper.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Mail\DotAtomReader.cs">
<Link>Common\System\Net\Mail\DotAtomReader.cs</Link>
@@ -115,12 +110,6 @@
<Compile Include="$(CommonPath)\System\Net\Mail\DomainLiteralReader.cs">
<Link>Common\System\Net\Mail\DomainLiteralReader.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\MailEventSource.cs">
- <Link>Common\System\Net\Logging\MailEventSource.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\System\Net\SecurityProtocol.cs">
<Link>Common\System\Net\SecurityProtocol.cs</Link>
</Compile>
diff --git a/src/System.Net.Mail/src/System/Net/Mail/MailMessage.cs b/src/System.Net.Mail/src/System/Net/Mail/MailMessage.cs
index cbf01aedfa..af2d2b33bc 100644
--- a/src/System.Net.Mail/src/System/Net/Mail/MailMessage.cs
+++ b/src/System.Net.Mail/src/System/Net/Mail/MailMessage.cs
@@ -32,7 +32,7 @@ namespace System.Net.Mail
public MailMessage()
{
_message = new Message();
- if (MailEventSource.Log.IsEnabled()) MailEventSource.Log.Associate(this, _message);
+ NetEventSource.Associate(this, _message);
}
public MailMessage(string from, string to)
@@ -50,7 +50,7 @@ namespace System.Net.Mail
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(to)), nameof(to));
_message = new Message(from, to);
- if (MailEventSource.Log.IsEnabled()) MailEventSource.Log.Associate(this, _message);
+ NetEventSource.Associate(this, _message);
}
diff --git a/src/System.Net.Mail/src/System/Net/Mail/MailPriority.cs b/src/System.Net.Mail/src/System/Net/Mail/MailPriority.cs
index 51faf6252d..8b7c211be5 100644
--- a/src/System.Net.Mail/src/System/Net/Mail/MailPriority.cs
+++ b/src/System.Net.Mail/src/System/Net/Mail/MailPriority.cs
@@ -235,7 +235,7 @@ namespace System.Net.Mail
if (_headers == null)
{
_headers = new HeaderCollection();
- if (MailEventSource.Log.IsEnabled()) MailEventSource.Log.Associate(this, _headers);
+ NetEventSource.Associate(this, _headers);
}
return _headers;
@@ -261,7 +261,7 @@ namespace System.Net.Mail
if (_envelopeHeaders == null)
{
_envelopeHeaders = new HeaderCollection();
- if (MailEventSource.Log.IsEnabled()) MailEventSource.Log.Associate(this, _envelopeHeaders);
+ NetEventSource.Associate(this, _envelopeHeaders);
}
return _envelopeHeaders;
diff --git a/src/System.Net.Mail/src/System/Net/Mail/NetEventSource.Mail.cs b/src/System.Net.Mail/src/System/Net/Mail/NetEventSource.Mail.cs
new file mode 100644
index 0000000000..909d7ee8c3
--- /dev/null
+++ b/src/System.Net.Mail/src/System/Net/Mail/NetEventSource.Mail.cs
@@ -0,0 +1,13 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using System.Net.Mail;
+using System.Runtime.CompilerServices;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-Mail", LocalizationResources = "FxResources.System.Net.Mail.SR")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
index b5f6649efc..8658bbd328 100644
--- a/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
+++ b/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
@@ -64,30 +64,20 @@ namespace System.Net.Mail
public SmtpClient()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Web, nameof(SmtpClient), ".ctor", "");
- }
-
+ NetEventSource.Enter(this);
try
{
Initialize();
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Web, nameof(SmtpClient), ".ctor", this);
- }
+ NetEventSource.Exit(this);
}
}
public SmtpClient(string host)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Web, nameof(SmtpClient), ".ctor", "host=" + host);
- }
+ NetEventSource.Enter(this, host);
try
{
_host = host;
@@ -95,25 +85,18 @@ namespace System.Net.Mail
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Web, nameof(SmtpClient), ".ctor", this);
- }
+ NetEventSource.Exit(this);
}
}
public SmtpClient(string host, int port)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Web, nameof(SmtpClient), ".ctor", "host=" + host + ", port=" + port);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host, port);
try
{
if (port < 0)
{
- throw new ArgumentOutOfRangeException("port");
+ throw new ArgumentOutOfRangeException(nameof(port));
}
_host = host;
@@ -122,10 +105,7 @@ namespace System.Net.Mail
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Web, nameof(SmtpClient), ".ctor", this);
- }
+ NetEventSource.Exit(this);
}
}
@@ -141,7 +121,7 @@ namespace System.Net.Mail
}
_transport = new SmtpTransport(this);
- if (MailEventSource.Log.IsEnabled()) MailEventSource.Log.Associate(this, _transport);
+ NetEventSource.Associate(this, _transport);
_onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback);
if (_host != null && _host.Length != 0)
@@ -423,10 +403,7 @@ namespace System.Net.Mail
internal MailWriter GetFileMailWriter(string pickupDirectory)
{
- if (MailEventSource.Log.IsEnabled())
- {
- MailEventSource.Log.Send(nameof(pickupDirectory), pickupDirectory);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"pickupDirectornameof={pickupDirectory}");
if (!Path.IsPathRooted(pickupDirectory))
throw new SmtpException(SR.SmtpNeedAbsolutePickupDirectory);
@@ -467,10 +444,7 @@ namespace System.Net.Mail
public void Send(MailMessage message)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, nameof(Send), message);
- }
+ NetEventSource.Enter(this, message);
if (_disposed)
{
@@ -478,11 +452,8 @@ namespace System.Net.Mail
}
try
{
- if (MailEventSource.Log.IsEnabled())
- {
- MailEventSource.Log.Send(nameof(DeliveryMethod), DeliveryMethod.ToString());
- MailEventSource.Log.Associate(this, message);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
+ NetEventSource.Associate(this, message);
SmtpFailedRecipientException recipientException = null;
@@ -583,14 +554,13 @@ namespace System.Net.Mail
}
catch (Exception e)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "Send", e);
+ NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
throw;
}
-
Abort();
if (_timedOut)
{
@@ -617,7 +587,7 @@ namespace System.Net.Mail
}
finally
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "Send", null);
+ NetEventSource.Exit(this);
}
}
@@ -639,15 +609,7 @@ namespace System.Net.Mail
throw new ObjectDisposedException(GetType().FullName);
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "SendAsync", "DeliveryMethod=" + DeliveryMethod.ToString());
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsync Transport#" + LoggingHash.HashString(_transport));
- }
+ NetEventSource.Enter(this, message, userToken, _transport);
try
{
@@ -743,11 +705,7 @@ namespace System.Net.Mail
_operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
lock (_operationCompletedResult.StartPostingAsyncOp())
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsync calling BeginConnect. Transport#" + LoggingHash.HashString(_transport));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
_transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
_operationCompletedResult.FinishPostingAsyncOp();
}
@@ -758,7 +716,7 @@ namespace System.Net.Mail
{
InCall = false;
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "Send", e);
+ NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
@@ -783,15 +741,7 @@ namespace System.Net.Mail
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "SendAsync", null);
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsync");
- }
+ NetEventSource.Exit(this);
}
}
@@ -801,15 +751,8 @@ namespace System.Net.Mail
{
throw new ObjectDisposedException(GetType().FullName);
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "SendAsyncCancel", null);
- }
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsyncCancel");
- }
+ NetEventSource.Enter(this);
try
{
@@ -823,14 +766,7 @@ namespace System.Net.Mail
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "SendAsyncCancel", null);
- }
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsyncCancel");
- }
+ NetEventSource.Exit(this);
}
}
@@ -923,10 +859,7 @@ namespace System.Net.Mail
private void Complete(Exception exception, IAsyncResult result)
{
ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpClient#" + LoggingHash.HashString(this) + "::Complete");
- }
+ NetEventSource.Enter(this);
try
{
if (_cancelled)
@@ -938,10 +871,7 @@ namespace System.Net.Mail
// An individual failed recipient exception is benign, only abort here if ALL the recipients failed.
else if (exception != null && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SmtpClient#" + LoggingHash.HashString(this) + "::Complete Exception: " + exception.ToString());
- }
+ NetEventSource.Error(this, exception);
Abort();
if (!(exception is SmtpException))
@@ -971,10 +901,7 @@ namespace System.Net.Mail
operationCompletedResult.InvokeCallback(exception);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::Complete");
- }
+ NetEventSource.Info(this, "Complete");
}
private static void ContextSafeCompleteCallback(IAsyncResult ar)
@@ -991,10 +918,7 @@ namespace System.Net.Mail
private void SendMessageCallback(IAsyncResult result)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpClient#" + LoggingHash.HashString(this) + "::SendMessageCallback");
- }
+ NetEventSource.Enter(this);
try
{
_message.EndSend(result);
@@ -1005,19 +929,16 @@ namespace System.Net.Mail
{
Complete(e, result);
}
- if (GlobalLog.IsEnabled)
+ finally
{
- GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::SendMessageCallback");
+ NetEventSource.Exit(this);
}
}
private void SendMailCallback(IAsyncResult result)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpClient#" + LoggingHash.HashString(this) + "::SendMailCallback");
- }
+ NetEventSource.Enter(this);
try
{
_writer = _transport.EndSendMail(result);
@@ -1031,12 +952,10 @@ namespace System.Net.Mail
catch (Exception e)
{
Complete(e, result);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::SendMailCallback");
- }
+ NetEventSource.Exit(this);
return;
}
+
try
{
if (_cancelled)
@@ -1053,20 +972,15 @@ namespace System.Net.Mail
{
Complete(e, result);
}
-
- if (GlobalLog.IsEnabled)
+ finally
{
- GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::SendMailCallback");
+ NetEventSource.Exit(this);
}
}
-
private void ConnectCallback(IAsyncResult result)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpClient#" + LoggingHash.HashString(this) + "::ConnectCallback");
- }
+ NetEventSource.Enter(this);
try
{
_transport.EndGetConnection(result);
@@ -1088,10 +1002,9 @@ namespace System.Net.Mail
{
Complete(e, result);
}
-
- if (GlobalLog.IsEnabled)
+ finally
{
- GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::ConnectCallback");
+ NetEventSource.Exit(this);
}
}
diff --git a/src/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs b/src/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs
index 1dccd7f30f..50c3cf7402 100644
--- a/src/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs
+++ b/src/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs
@@ -311,12 +311,7 @@ namespace System.Net.Mail
#if DEBUG
if (context != null && !context.IdentityRequested)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("SmtpConnection#{0}::SetContextAndTryAuthenticate|Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)", LoggingHash.HashString(this));
- }
-
- Debug.Fail("SmtpConnection#" + LoggingHash.HashString(this) + "::SetContextAndTryAuthenticate|Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)");
+ NetEventSource.Fail(this, "Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)");
}
#endif
@@ -421,10 +416,7 @@ namespace System.Net.Mail
private static void ConnectionCreatedCallback(object request, object state)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("ConnectAndHandshakeAsyncResult#" + LoggingHash.HashString(request) + "::ConnectionCreatedCallback");
- }
+ NetEventSource.Enter(null, request);
ConnectAndHandshakeAsyncResult ConnectAndHandshakeAsyncResult = (ConnectAndHandshakeAsyncResult)request;
if (state is Exception)
{
@@ -440,10 +432,7 @@ namespace System.Net.Mail
if (ConnectAndHandshakeAsyncResult._connection._isClosed)
{
ConnectAndHandshakeAsyncResult._connection.ReleaseConnection();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ConnectAndHandshakeAsyncResult#" + LoggingHash.HashString(request) + "::ConnectionCreatedCallback Connect was aborted ");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect was aborted: {request}");
ConnectAndHandshakeAsyncResult.InvokeCallback(null);
return;
}
@@ -456,10 +445,7 @@ namespace System.Net.Mail
ConnectAndHandshakeAsyncResult.InvokeCallback(e);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("ConnectAndHandshakeAsyncResult#" + LoggingHash.HashString(request) + "::ConnectionCreatedCallback");
- }
+ NetEventSource.Exit(null, request);
}
@@ -475,10 +461,7 @@ namespace System.Net.Mail
internal void GetConnection()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("ConnectAndHandshakeAsyncResult#" + LoggingHash.HashString(this) + "::Connect:");
- }
+ NetEventSource.Enter(this);
if (_connection._isConnected)
{
throw new InvalidOperationException(SR.SmtpAlreadyConnected);
@@ -493,10 +476,7 @@ namespace System.Net.Mail
if (result.CompletedSynchronously)
{
_connection.EndInitializeConnection(result);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ConnectAndHandshakeAsyncResult#" + LoggingHash.HashString(this) + "::Connect returned" + LoggingHash.HashString(this));
- }
+ NetEventSource.Info(this, "Connect returned");
try
{
@@ -515,10 +495,7 @@ namespace System.Net.Mail
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
thisPtr._connection.EndInitializeConnection(result);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("ConnectAndHandshakeAsyncResult#" + LoggingHash.HashString(thisPtr) + "::Connect returned" + LoggingHash.HashString(thisPtr));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect returned {thisPtr}");
try
{
diff --git a/src/System.Net.Mail/src/System/Net/Mail/SmtpLoginAuthenticationModule.cs b/src/System.Net.Mail/src/System/Net/Mail/SmtpLoginAuthenticationModule.cs
index ebf82ffa9c..57e314cce9 100644
--- a/src/System.Net.Mail/src/System/Net/Mail/SmtpLoginAuthenticationModule.cs
+++ b/src/System.Net.Mail/src/System/Net/Mail/SmtpLoginAuthenticationModule.cs
@@ -21,7 +21,7 @@ namespace System.Net.Mail
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Web, this, nameof(Authenticate), null);
+ NetEventSource.Enter(this);
try
{
lock (_sessions)
@@ -56,7 +56,7 @@ namespace System.Net.Mail
}
finally
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "Authenticate", null);
+ NetEventSource.Exit(this);
}
}
diff --git a/src/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs b/src/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs
index c1622b5019..98311c0dc0 100644
--- a/src/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs
+++ b/src/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs
@@ -125,7 +125,7 @@ namespace System.Net.Mail
{
_connection = new SmtpConnection(this, _client, _credentials, _authenticationModules);
_connection.Timeout = _timeout;
- if (MailEventSource.Log.IsEnabled()) MailEventSource.Log.Associate(this, _connection);
+ NetEventSource.Associate(this, _connection);
if (EnableSsl)
{
@@ -140,19 +140,13 @@ namespace System.Net.Mail
internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpTransport#" + LoggingHash.HashString(this) + "::BeginConnect");
- }
+ NetEventSource.Enter(this);
IAsyncResult result = null;
try
{
_connection = new SmtpConnection(this, _client, _credentials, _authenticationModules);
_connection.Timeout = _timeout;
- if (MailEventSource.Log.IsEnabled())
- {
- MailEventSource.Log.Associate(this, _connection);
- }
+ NetEventSource.Associate(this, _connection);
if (EnableSsl)
{
_connection.EnableSsl = true;
@@ -166,29 +160,21 @@ namespace System.Net.Mail
throw new SmtpException(SR.MailHostNotFound, innerException);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SmtpTransport#" + LoggingHash.HashString(this) + "::BeginConnect Sync Completion");
- }
+ NetEventSource.Info(this, "Sync completion");
+ NetEventSource.Exit(this);
return result;
}
internal void EndGetConnection(IAsyncResult result)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SmtpTransport#" + LoggingHash.HashString(this) + "::EndGetConnection");
- }
+ NetEventSource.Enter(this);
try
{
_connection.EndGetConnection(result);
}
finally
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SmtpTransport#" + LoggingHash.HashString(this) + "::EndConnect");
- }
+ NetEventSource.Exit(this);
}
}
diff --git a/src/System.Net.Mail/tests/Functional/LoggingTest.cs b/src/System.Net.Mail/tests/Functional/LoggingTest.cs
new file mode 100644
index 0000000000..67e2e45849
--- /dev/null
+++ b/src/System.Net.Mail/tests/Functional/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.Mail.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(SmtpClient).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-Mail", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("42c8027b-f048-58d2-537d-a4a9d5ee7038"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj b/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj
index 3c69c7de37..ff1823ca12 100644
--- a/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj
+++ b/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj
@@ -17,6 +17,7 @@
<Compile Include="ContentTypeTest.cs" />
<Compile Include="LinkedResourceCollectionTest.cs" />
<Compile Include="LinkedResourceTest.cs" />
+ <Compile Include="LoggingTest.cs" />
<Compile Include="MailAddressCollectionTest.cs" />
<Compile Include="MailAddressTest.cs" />
<Compile Include="MailMessageTest.cs" />
diff --git a/src/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj b/src/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj
index bc8d71a63c..61c0436d9c 100644
--- a/src/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj
+++ b/src/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj
@@ -43,6 +43,9 @@
<Compile Include="..\..\src\System\Net\Mail\MailAddress.cs">
<Link>ProductionCode\MailAddress.cs</Link>
</Compile>
+ <Compile Include="..\..\src\System\Net\Mail\NetEventSource.Mail.cs">
+ <Link>ProductionCode\NetEventSource.Mail.cs</Link>
+ </Compile>
<Compile Include="..\..\src\System\Net\Mail\SmtpConnection.Auth.cs">
<Link>ProductionCode\SmtpConnection.Auth.cs</Link>
</Compile>
@@ -142,20 +145,8 @@
<Compile Include="$(CommonPath)\System\Net\Mail\MailBnfHelper.cs">
<Link>ProductionCode\Common\System\Net\Mail\MailBnfHelper.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>ProductionCode\Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>ProductionCode\Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\MailEventSource.cs">
- <Link>ProductionCode\Common\System\Net\Logging\MailEventSource.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>ProductionCode\Common\System\Net\Logging\NetEventSource.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>ProductionCode\Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>ProductionCode\Common\System\Net\Logging\NetEventSource.Common..cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Mail\DomainLiteralReader.cs">
<Link>ProductionCode\Common\System\Net\Mail\DomainLiteralReader.cs</Link>
diff --git a/src/System.Net.NameResolution/src/System.Net.NameResolution.csproj b/src/System.Net.NameResolution/src/System.Net.NameResolution.csproj
index 93bf8756a2..65e45579be 100644
--- a/src/System.Net.NameResolution/src/System.Net.NameResolution.csproj
+++ b/src/System.Net.NameResolution/src/System.Net.NameResolution.csproj
@@ -32,18 +32,13 @@
<Compile Include="System\Net\DNS.cs" />
<Compile Include="System\Net\IPHostEntry.cs" />
<Compile Include="System\Net\NameResolutionUtilities.cs" />
+ <Compile Include="System\Net\NetEventSource.NameResolution.cs" />
<!-- Logging -->
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\DebugThreadTracking.cs">
+ <Link>Common\System\Net\Logging\DebugThreadTracking.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.NameResolution/src/System/Net/DNS.cs b/src/System.Net.NameResolution/src/System/Net/DNS.cs
index 0d41eb258a..5b48c4d2dc 100644
--- a/src/System.Net.NameResolution/src/System/Net/DNS.cs
+++ b/src/System.Net.NameResolution/src/System/Net/DNS.cs
@@ -42,14 +42,9 @@ namespace System.Net
private static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", hostName);
+ NetEventSource.Enter(null, hostName);
IPHostEntry ipHostEntry = null;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Dns.GetHostByName: " + hostName);
- }
-
if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot.
|| hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.')
{
@@ -90,15 +85,14 @@ namespace System.Net
ipHostEntry = NameResolutionPal.GetHostByName(hostName);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByName
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(string address)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostByAddress", address);
-
+ NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
@@ -106,21 +100,16 @@ namespace System.Net
throw new ArgumentNullException(nameof(address));
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Dns.GetHostByAddress: " + address);
- }
-
IPHostEntry ipHostEntry = InternalGetHostByAddress(IPAddress.Parse(address), false);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByAddress", ipHostEntry);
+
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(IPAddress address)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostByAddress", "");
-
+ NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
@@ -129,17 +118,15 @@ namespace System.Net
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address, false);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByAddress", ipHostEntry);
+
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
// Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods).
private static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString());
- }
+ NetEventSource.Info(null, address);
//
// IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions
@@ -168,14 +155,7 @@ namespace System.Net
return hostEntry;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(
- NetEventSource.ComponentType.Socket,
- "DNS",
- "InternalGetHostByAddress",
- SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode));
// One of two things happened:
// 1. There was a ptr record in dns, but not a corollary A/AAA record.
@@ -227,10 +207,7 @@ namespace System.Net
/// </devdoc>
public static string GetHostName()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Dns.GetHostName");
- }
+ NetEventSource.Info(null, null);
NameResolutionPal.EnsureSocketsAreInitialized();
@@ -240,7 +217,7 @@ namespace System.Net
[Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry Resolve(string hostName)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "Resolve", hostName);
+ NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
@@ -261,8 +238,7 @@ namespace System.Net
}
catch (SocketException ex)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Socket, "DNS", "DNS.Resolve", ex.Message);
-
+ NetEventSource.Error(null, ex);
ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
}
}
@@ -271,7 +247,7 @@ namespace System.Net
ipHostEntry = InternalGetHostByName(hostName, false);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "Resolve", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
@@ -335,10 +311,7 @@ namespace System.Net
throw new ArgumentNullException(nameof(hostName));
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Dns.HostResolutionBeginHelper: " + hostName);
- }
+ NetEventSource.Info(null, hostName);
// See if it's an IP Address.
IPAddress address;
@@ -394,10 +367,7 @@ namespace System.Net
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Dns.HostResolutionBeginHelper: " + address);
- }
+ NetEventSource.Info(null, address);
// Set up the context, possibly flow.
ResolveAsyncResult asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback);
@@ -438,10 +408,7 @@ namespace System.Net
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndResolve)));
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Dns.HostResolutionEndHelper");
- }
+ NetEventSource.Info(null);
castedResult.InternalWaitForCompletion();
castedResult.EndCalled = true;
@@ -458,33 +425,31 @@ namespace System.Net
[Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostByName", hostName);
+ NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, true, true, false, requestCallback, stateObject);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostByName", asyncResult);
+ NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginGetHostByName
[Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostByName", asyncResult);
-
+ NetEventSource.Enter(null, asyncResult);
NameResolutionPal.EnsureSocketsAreInitialized();
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostByName", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndGetHostByName()
public static IPHostEntry GetHostEntry(string hostNameOrAddress)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostEntry", hostNameOrAddress);
-
+ NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress == null)
@@ -509,15 +474,14 @@ namespace System.Net
ipHostEntry = InternalGetHostByName(hostNameOrAddress, true);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostEntry", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
public static IPHostEntry GetHostEntry(IPAddress address)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostEntry", "");
-
+ NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
@@ -531,14 +495,14 @@ namespace System.Net
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address, true);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostEntry", ipHostEntry);
+
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostEntry
public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostAddresses", hostNameOrAddress);
-
+ NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress == null)
@@ -564,74 +528,72 @@ namespace System.Net
addresses = InternalGetHostByName(hostNameOrAddress, true).AddressList;
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostAddresses", addresses);
+ NetEventSource.Exit(null, addresses);
return addresses;
}
public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", hostNameOrAddress);
-
+ NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, true, true, requestCallback, stateObject);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult);
+ NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", address);
+ NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, true, requestCallback, stateObject);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult);
+ NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", asyncResult);
+ NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndResolve()
public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", hostNameOrAddress);
-
+ NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, true, true, requestCallback, state);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", asyncResult);
+ NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", asyncResult);
+ NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry.AddressList;
} // EndResolveToAddresses
[Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginResolve(string hostName, AsyncCallback requestCallback, object stateObject)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginResolve", hostName);
+ NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, false, false, false, requestCallback, stateObject);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginResolve", asyncResult);
+ NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
@@ -639,8 +601,7 @@ namespace System.Net
[Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndResolve(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndResolve", asyncResult);
-
+ NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry;
try
@@ -653,12 +614,11 @@ namespace System.Net
if (address == null)
throw; // BeginResolve was called with a HostName, not an IPAddress
- if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Socket, "DNS", "DNS.EndResolve", ex.Message);
-
+ NetEventSource.Error(null, ex);
ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
}
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndResolve", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndResolve()
diff --git a/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs b/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs
index b7dd063ee0..16deab654e 100644
--- a/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs
+++ b/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Windows.cs
@@ -52,10 +52,7 @@ namespace System.Net
if (Host.h_name != IntPtr.Zero)
{
HostEntry.HostName = Marshal.PtrToStringAnsi(Host.h_name);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("HostEntry.HostName: " + HostEntry.HostName);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"HostEntry.HostName: {HostEntry.HostName}");
}
// decode h_addr_list to ArrayList of IP addresses.
@@ -92,10 +89,7 @@ namespace System.Net
((uint)IPAddressToAdd >> 24));
#endif
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("currentArrayElement: " + currentArrayElement.ToString() + " nativePointer: " + nativePointer.ToString() + " IPAddressToAdd:" + IPAddressToAdd.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"currentArrayElement:{currentArrayElement} nativePointer:{nativePointer} IPAddressToAdd:{IPAddressToAdd}");
//
// ...and add it to the list
@@ -122,10 +116,7 @@ namespace System.Net
while (nativePointer != IntPtr.Zero)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("currentArrayElement: " + ((long)currentArrayElement).ToString() + "nativePointer: " + ((long)nativePointer).ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"currentArrayElement:{currentArrayElement} nativePointer:{nativePointer}");
//
// if it's not null it points to an Alias,
@@ -168,7 +159,7 @@ namespace System.Net
if (IPAddress.TryParse(hostName, out address))
{
IPHostEntry ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
- if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", ipHostEntry);
+ NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
diff --git a/src/System.Net.NameResolution/src/System/Net/NetEventSource.NameResolution.cs b/src/System.Net.NameResolution/src/System/Net/NetEventSource.NameResolution.cs
new file mode 100644
index 0000000000..bf0ba71f39
--- /dev/null
+++ b/src/System.Net.NameResolution/src/System/Net/NetEventSource.NameResolution.cs
@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-NameResolution")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs b/src/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs
new file mode 100644
index 0000000000..fd8a51bd10
--- /dev/null
+++ b/src/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using System.Reflection;
+using Xunit;
+
+namespace System.Net.NameResolution.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(Dns).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-NameResolution", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("5f302add-3825-520e-8fa0-627b206e2e7e"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.NameResolution/tests/FunctionalTests/System.Net.NameResolution.Functional.Tests.csproj b/src/System.Net.NameResolution/tests/FunctionalTests/System.Net.NameResolution.Functional.Tests.csproj
index 9b9ecd90fd..f81d122a8e 100644
--- a/src/System.Net.NameResolution/tests/FunctionalTests/System.Net.NameResolution.Functional.Tests.csproj
+++ b/src/System.Net.NameResolution/tests/FunctionalTests/System.Net.NameResolution.Functional.Tests.csproj
@@ -18,6 +18,7 @@
<Compile Include="GetHostNameTest.cs" />
<Compile Include="GetHostEntryTest.cs" />
<Compile Include="GetHostAddressesTest.cs" />
+ <Compile Include="LoggingTest.cs" />
<Compile Include="TestSettings.cs" />
</ItemGroup>
<ItemGroup>
diff --git a/src/System.Net.NameResolution/tests/PalTests/Fakes/GlobalLog.cs b/src/System.Net.NameResolution/tests/PalTests/Fakes/DebugThreadTracking.cs
index 86907f6dbc..ebe478f65f 100644
--- a/src/System.Net.NameResolution/tests/PalTests/Fakes/GlobalLog.cs
+++ b/src/System.Net.NameResolution/tests/PalTests/Fakes/DebugThreadTracking.cs
@@ -4,21 +4,11 @@
namespace System.Net
{
- public static class GlobalLog
+ public static class DebugThreadTracking
{
- public static void Assert(string message)
- {
- }
-
- public static void Print(string message)
- {
- }
-
internal static void SetThreadSource(ThreadKinds source)
{
}
-
- public static bool IsEnabled { get { return false; } }
}
[Flags]
diff --git a/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj b/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj
index e87413b9aa..b1957b5727 100644
--- a/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj
+++ b/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj
@@ -21,12 +21,9 @@
<ItemGroup>
<Compile Include="NameResolutionPalTests.cs" />
- <Compile Include="Fakes\GlobalLog.cs" />
+ <Compile Include="Fakes\DebugThreadTracking.cs" />
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
<Link>Common\System\Net\Logging\NetEventSource.cs</Link>
</Compile>
diff --git a/src/System.Net.NameResolution/tests/UnitTests/System.Net.NameResolution.Unit.Tests.csproj b/src/System.Net.NameResolution/tests/UnitTests/System.Net.NameResolution.Unit.Tests.csproj
index ebac5b39db..c2f7001730 100644
--- a/src/System.Net.NameResolution/tests/UnitTests/System.Net.NameResolution.Unit.Tests.csproj
+++ b/src/System.Net.NameResolution/tests/UnitTests/System.Net.NameResolution.Unit.Tests.csproj
@@ -40,17 +40,8 @@
<Compile Include="$(CommonPath)\System\Net\Internals\SocketExceptionFactory.cs">
<Link>ProductionCode\Common\System\Net\Internals\SocketExceptionFactory.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj b/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj
index 43ad4569a6..59c30ce878 100644
--- a/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj
+++ b/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj
@@ -48,6 +48,7 @@
<Compile Include="System\Net\NetworkInformation\MulticastIPAddressInformation.cs" />
<Compile Include="System\Net\NetworkInformation\MulticastIPAddressInformationCollection.cs" />
<Compile Include="System\Net\NetworkInformation\NetBiosNodeType.cs" />
+ <Compile Include="System\Net\NetworkInformation\NetEventSource.NetworkInformation.cs" />
<Compile Include="System\Net\NetworkInformation\NetworkAvailabilityEventArgs.cs" />
<Compile Include="System\Net\NetworkInformation\NetworkChangeDelegates.cs" />
<Compile Include="System\Net\NetworkInformation\NetworkInterface.cs" />
@@ -80,17 +81,11 @@
<Compile Include="$(CommonPath)\System\Net\Shims\TraceSource.cs">
<Link>Common\System\Net\Shims\TraceSource.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\DebugThreadTracking.cs">
+ <Link>Common\System\Net\Logging\DebugThreadTracking.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs
new file mode 100644
index 0000000000..a69373a034
--- /dev/null
+++ b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs
@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-NetworkInformation")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs
index ec98de3bd1..3542779438 100644
--- a/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs
+++ b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs
@@ -162,10 +162,7 @@ namespace System.Net.NetworkInformation
}
catch (NetworkInformationException nie)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.NetworkInformation, "AddressChangeListener", "AddressChangedCallback", nie);
- }
+ NetEventSource.Error(null, nie);
}
foreach (var handler in copy.Keys)
diff --git a/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs
index f6aff20e58..ec8928d36e 100644
--- a/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs
+++ b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs
@@ -73,10 +73,7 @@ namespace System.Net.NetworkInformation
}
catch (NetworkInformationException nie)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.NetworkInformation, "SystemNetworkInterface", "InternalGetIsNetworkAvailable", nie);
- }
+ NetEventSource.Error(null, nie);
}
return false;
diff --git a/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs
index f859a7d14f..4150829011 100644
--- a/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs
+++ b/src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/TeredoHelper.cs
@@ -57,11 +57,7 @@ namespace System.Net.NetworkInformation
{
if (callback == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("UnsafeNotifyStableUnicastIpAddressTable called without specifying callback!");
- }
- Debug.Fail("UnsafeNotifyStableUnicastIpAddressTable called without specifying callback!");
+ NetEventSource.Fail(null, "UnsafeNotifyStableUnicastIpAddressTable called without specifying callback!");
}
TeredoHelper helper = new TeredoHelper(callback, state);
@@ -91,11 +87,7 @@ namespace System.Net.NetworkInformation
{
if (helper._cancelHandle.IsInvalid)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("CancelHandle invalid despite returning ERROR_IO_PENDING");
- }
- Debug.Fail("CancelHandle invalid despite returning ERROR_IO_PENDING");
+ NetEventSource.Fail(null, "CancelHandle invalid despite returning ERROR_IO_PENDING");
}
// Async completion: add us to the s_pendingNotifications list so we'll be canceled in the
@@ -117,11 +109,7 @@ namespace System.Net.NetworkInformation
{
if (!_runCallbackCalled)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("RunCallback called without setting runCallbackCalled!");
- }
- Debug.Fail("RunCallback called without setting runCallbackCalled!");
+ NetEventSource.Fail(null, "RunCallback called without setting runCallbackCalled!");
}
// If OnAppDomainUnload beats us to the lock, do nothing: the AppDomain is going down soon anyways.
@@ -137,11 +125,7 @@ namespace System.Net.NetworkInformation
bool successfullyRemoved = s_pendingNotifications.Remove(this);
if (!successfullyRemoved)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("RunCallback for a TeredoHelper which is not in s_pendingNotifications!");
- }
- Debug.Fail("RunCallback for a TeredoHelper which is not in s_pendingNotifications!");
+ NetEventSource.Fail(null, "RunCallback for a TeredoHelper which is not in s_pendingNotifications!");
}
#else
s_pendingNotifications.Remove(this);
@@ -149,11 +133,7 @@ namespace System.Net.NetworkInformation
if ((_cancelHandle == null || _cancelHandle.IsInvalid))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("Invalid cancelHandle in RunCallback");
- }
- Debug.Fail("Invalid cancelHandle in RunCallback");
+ NetEventSource.Fail(null, "Invalid cancelHandle in RunCallback");
}
_cancelHandle.Dispose();
diff --git a/src/System.Net.NetworkInformation/tests/FunctionalTests/LoggingTest.cs b/src/System.Net.NetworkInformation/tests/FunctionalTests/LoggingTest.cs
new file mode 100644
index 0000000000..14d1513d4a
--- /dev/null
+++ b/src/System.Net.NetworkInformation/tests/FunctionalTests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.NetworkInformation
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(NetworkChange).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-NetworkInformation", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("b8e42167-0eb2-5e39-97b5-acaca593d3a2"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.NetworkInformation/tests/FunctionalTests/System.Net.NetworkInformation.Functional.Tests.csproj b/src/System.Net.NetworkInformation/tests/FunctionalTests/System.Net.NetworkInformation.Functional.Tests.csproj
index cf135df349..c43075c853 100644
--- a/src/System.Net.NetworkInformation/tests/FunctionalTests/System.Net.NetworkInformation.Functional.Tests.csproj
+++ b/src/System.Net.NetworkInformation/tests/FunctionalTests/System.Net.NetworkInformation.Functional.Tests.csproj
@@ -78,6 +78,7 @@
</Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == ''">
+ <Compile Include="LoggingTest.cs" />
<Compile Include="NetworkAvailabilityChangedTests.cs" />
<Compile Include="NetworkInterfaceIPv4Statistics.cs" />
</ItemGroup>
diff --git a/src/System.Net.NetworkInformation/tests/UnitTests/System.Net.NetworkInformation.WinRT.Unit.Tests.csproj b/src/System.Net.NetworkInformation/tests/UnitTests/System.Net.NetworkInformation.WinRT.Unit.Tests.csproj
index 3b6bbfbc75..cd22ada831 100644
--- a/src/System.Net.NetworkInformation/tests/UnitTests/System.Net.NetworkInformation.WinRT.Unit.Tests.csproj
+++ b/src/System.Net.NetworkInformation/tests/UnitTests/System.Net.NetworkInformation.WinRT.Unit.Tests.csproj
@@ -6,6 +6,7 @@
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2194D6A2-1A35-46B5-8233-AEEBCBD31EF9}</ProjectGuid>
<OutputType>Library</OutputType>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath>
<NugetTargetMoniker Condition="'$(TargetGroup)' == ''">.NETStandard,Version=v1.7</NugetTargetMoniker>
</PropertyGroup>
@@ -56,11 +57,8 @@
<Compile Include="$(CommonPath)\System\Net\Shims\TraceSource.cs">
<Link>ProductionCode\Common\System\Net\Shims\TraceSource.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>ProductionCode\Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>ProductionCode\Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>ProductionCode\Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>ProductionCode\Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.Ping/src/System.Net.Ping.csproj b/src/System.Net.Ping/src/System.Net.Ping.csproj
index 6d84b000df..f31e71dabe 100644
--- a/src/System.Net.Ping/src/System.Net.Ping.csproj
+++ b/src/System.Net.Ping/src/System.Net.Ping.csproj
@@ -22,6 +22,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'net46_Release|AnyCPU'" />
<ItemGroup Condition="'$(TargetGroup)' != 'net463'">
<Compile Include="System\Net\NetworkInformation\IPStatus.cs" />
+ <Compile Include="System\Net\NetworkInformation\NetEventSource.Ping.cs" />
<Compile Include="System\Net\NetworkInformation\Ping.cs" />
<Compile Include="System\Net\NetworkInformation\PingCompletedEventArgs.cs" />
<Compile Include="System\Net\NetworkInformation\PingException.cs" />
@@ -48,11 +49,8 @@
<Compile Include="$(CommonPath)\System\Net\Shims\TraceSource.cs">
<Link>Common\System\Net\Shims\TraceSource.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.cs b/src/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.cs
new file mode 100644
index 0000000000..85327cf2e2
--- /dev/null
+++ b/src/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.cs
@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-Ping")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.Ping/tests/FunctionalTests/LoggingTest.cs b/src/System.Net.Ping/tests/FunctionalTests/LoggingTest.cs
new file mode 100644
index 0000000000..7353be093d
--- /dev/null
+++ b/src/System.Net.Ping/tests/FunctionalTests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.NetworkInformation.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(Ping).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-Ping", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("a771ec4a-7260-59ce-0475-db257437ed8c"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj b/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj
index 58a3c81a24..276c6a26d3 100644
--- a/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj
+++ b/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj
@@ -18,6 +18,7 @@
<!-- Test APIs introduced after 1.0 -->
<ItemGroup Condition="'$(TargetGroup)'==''">
<Compile Include="PingTest.cs" />
+ <Compile Include="LoggingTest.cs" />
</ItemGroup>
<ItemGroup>
diff --git a/src/System.Net.Primitives/src/System.Net.Primitives.csproj b/src/System.Net.Primitives/src/System.Net.Primitives.csproj
index 68dc73c986..97777ccb48 100644
--- a/src/System.Net.Primitives/src/System.Net.Primitives.csproj
+++ b/src/System.Net.Primitives/src/System.Net.Primitives.csproj
@@ -50,6 +50,7 @@
<Compile Include="System\Net\IPAddressParser.cs" />
<Compile Include="System\Net\IPEndPoint.cs" />
<Compile Include="System\Net\IWebProxy.cs" />
+ <Compile Include="System\Net\NetEventSource.Primitives.cs" />
<Compile Include="System\Net\NetworkCredential.cs" />
<Compile Include="System\Net\TransportContext.cs" />
<Compile Include="System\Net\SocketException.cs" />
@@ -95,14 +96,8 @@
<Compile Include="$(CommonPath)\System\Net\Shims\TraceSource.cs">
<Link>Common\System\Net\Shims\TraceSource.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.Primitives/src/System/Net/Cookie.cs b/src/System.Net.Primitives/src/System/Net/Cookie.cs
index f652ef615f..c1739d2e49 100644
--- a/src/System.Net.Primitives/src/System/Net/Cookie.cs
+++ b/src/System.Net.Primitives/src/System/Net/Cookie.cs
@@ -685,11 +685,7 @@ namespace System.Net
#if !NETNative_SystemNetHttp
if (value != CookieVariant.Rfc2965)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("Cookie#{0}::set_Variant()|value:{1}", LoggingHash.HashString(this), value);
- }
- Debug.Fail("Cookie#" + LoggingHash.HashString(this) + "::set_Variant()|value:" + value);
+ NetEventSource.Fail(this, $"value != Rfc2965:{value}");
}
#endif
_cookieVariant = value;
@@ -857,9 +853,10 @@ namespace System.Net
internal void Dump()
{
#if !NETNative_SystemNetHttp
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("Cookie: " + ToString() + "->\n"
+ NetEventSource.Info(this,
+ "Cookie: " + ToString() + "->\n"
+ "\tComment = " + Comment + "\n"
+ "\tCommentUri = " + CommentUri + "\n"
+ "\tDiscard = " + Discard + "\n"
diff --git a/src/System.Net.Primitives/src/System/Net/CookieCollection.cs b/src/System.Net.Primitives/src/System/Net/CookieCollection.cs
index c530dcc25b..1958c69823 100644
--- a/src/System.Net.Primitives/src/System/Net/CookieCollection.cs
+++ b/src/System.Net.Primitives/src/System/Net/CookieCollection.cs
@@ -226,9 +226,9 @@ namespace System.Net
#if DEBUG
internal void Dump()
{
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("CookieCollection:");
+ NetEventSource.Enter(this);
foreach (Cookie cookie in this)
{
cookie.Dump();
diff --git a/src/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/System.Net.Primitives/src/System/Net/CookieContainer.cs
index e73a3ed836..a2e2fe3d49 100644
--- a/src/System.Net.Primitives/src/System/Net/CookieContainer.cs
+++ b/src/System.Net.Primitives/src/System/Net/CookieContainer.cs
@@ -637,9 +637,9 @@ namespace System.Net
internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow)
{
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("CookieContainer#" + LoggingHash.HashString(this) + "::CookieCutter() uri:" + uri + " headerName:" + headerName + " setCookieHeader:" + setCookieHeader + " isThrow:" + isThrow);
+ NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}");
}
CookieCollection cookies = new CookieCollection();
@@ -666,10 +666,7 @@ namespace System.Net
do
{
Cookie cookie = parser.Get();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CookieContainer#" + LoggingHash.HashString(this) + "::CookieCutter() CookieParser returned cookie:" + LoggingHash.ObjectToString(cookie));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CookieParser returned cookie:{cookie}");
if (cookie == null)
{
diff --git a/src/System.Net.Primitives/src/System/Net/CredentialCache.cs b/src/System.Net.Primitives/src/System/Net/CredentialCache.cs
index ea3159f6c9..3bea52bbfb 100644
--- a/src/System.Net.Primitives/src/System/Net/CredentialCache.cs
+++ b/src/System.Net.Primitives/src/System/Net/CredentialCache.cs
@@ -36,10 +36,7 @@ namespace System.Net
var key = new CredentialKey(uriPrefix, authType);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + cred.Domain + "],[" + cred.UserName + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{cred.Domain}],[{cred.UserName}]");
if (_cache == null)
{
@@ -75,10 +72,7 @@ namespace System.Net
var key = new CredentialHostKey(host, port, authenticationType);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{credential.Domain}],[{credential.UserName}]");
if (_cacheForHosts == null)
{
@@ -99,11 +93,7 @@ namespace System.Net
if (_cache == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::Remove() Short-circuiting because the dictionary is null.");
- }
-
+ NetEventSource.Info(this, "Short-circuiting because the dictionary is null.");
return;
}
@@ -111,10 +101,7 @@ namespace System.Net
var key = new CredentialKey(uriPrefix, authType);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Removing key:[{key}]");
_cache.Remove(key);
}
@@ -135,11 +122,7 @@ namespace System.Net
if (_cacheForHosts == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::Remove() Short-circuiting because the dictionary is null.");
- }
-
+ NetEventSource.Info(this, "Short-circuiting because the dictionary is null.");
return;
}
@@ -147,10 +130,7 @@ namespace System.Net
var key = new CredentialHostKey(host, port, authenticationType);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Removing key:[{key}]");
_cacheForHosts.Remove(key);
}
@@ -166,18 +146,11 @@ namespace System.Net
throw new ArgumentNullException(nameof(authType));
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authType + "\")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, uriPrefix, authType);
if (_cache == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::GetCredential short-circuiting because the dictionary is null.");
- }
-
+ NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
return null;
}
@@ -204,10 +177,7 @@ namespace System.Net
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch == null) ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returning {(mostSpecificMatch == null ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")}");
return mostSpecificMatch;
}
@@ -231,18 +201,11 @@ namespace System.Net
throw new ArgumentOutOfRangeException(nameof(port));
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() + "\", authenticationType=\"" + authenticationType + "\")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host, port, authenticationType);
if (_cacheForHosts == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::GetCredential short-circuiting because the dictionary is null.");
- }
-
+ NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
return null;
}
@@ -251,10 +214,7 @@ namespace System.Net
NetworkCredential match = null;
_cacheForHosts.TryGetValue(key, out match);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialCache::GetCredential returning " + ((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returning {((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}");
return match;
}
@@ -469,10 +429,7 @@ namespace System.Net
string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase) &&
Port == other.Port;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialHostKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Equals({this},{other}) returns {equals}");
return equals;
}
@@ -481,7 +438,7 @@ namespace System.Net
obj is CredentialHostKey && Equals((CredentialHostKey)obj);
public override string ToString() =>
- Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + LoggingHash.ObjectToString(AuthenticationType);
+ Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + AuthenticationType;
}
internal sealed class CredentialKey : IEquatable<CredentialKey>
@@ -513,10 +470,7 @@ namespace System.Net
return false;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Match({UriPrefix} & {uri})");
return IsPrefix(uri, UriPrefix);
}
@@ -567,16 +521,14 @@ namespace System.Net
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
UriPrefix.Equals(other.UriPrefix);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Equals({this},{other}) returns {equals}");
+
return equals;
}
public override bool Equals(object obj) => Equals(obj as CredentialKey);
public override string ToString() =>
- "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + LoggingHash.ObjectToString(UriPrefix) + ":" + LoggingHash.ObjectToString(AuthenticationType);
+ "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + UriPrefix + ":" + AuthenticationType;
}
}
diff --git a/src/System.Net.Primitives/src/System/Net/NetEventSource.Primitives.cs b/src/System.Net.Primitives/src/System/Net/NetEventSource.Primitives.cs
new file mode 100644
index 0000000000..3cab207ee6
--- /dev/null
+++ b/src/System.Net.Primitives/src/System/Net/NetEventSource.Primitives.cs
@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-Primitives")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.Primitives/src/System/Net/SocketException.Unix.cs b/src/System.Net.Primitives/src/System/Net/SocketException.Unix.cs
index 5e24ba6acd..312ff46e5b 100644
--- a/src/System.Net.Primitives/src/System/Net/SocketException.Unix.cs
+++ b/src/System.Net.Primitives/src/System/Net/SocketException.Unix.cs
@@ -15,12 +15,8 @@ namespace System.Net.Sockets
internal SocketException(SocketError errorCode, uint platformError) : base((int)platformError)
{
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, errorCode, platformError);
_errorCode = errorCode;
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print($"SocketException::.ctor(SocketError={errorCode}, uint={platformError}):{Message}");
- }
}
private SocketException(Interop.ErrorInfo error) : this(SocketErrorPal.GetSocketErrorForNativeError(error.Error), (uint)error.RawErrno)
diff --git a/src/System.Net.Primitives/src/System/Net/SocketException.cs b/src/System.Net.Primitives/src/System/Net/SocketException.cs
index 6351f6f76a..ad9e1d8f91 100644
--- a/src/System.Net.Primitives/src/System/Net/SocketException.cs
+++ b/src/System.Net.Primitives/src/System/Net/SocketException.cs
@@ -31,12 +31,8 @@ namespace System.Net.Sockets
/// <summary>Creates a new instance of the <see cref='System.Net.Sockets.SocketException'/> class with the specified error code as SocketError.</summary>
internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))
{
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, socketError, Message);
_errorCode = socketError;
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print($"SocketException::.ctor(SocketError={socketError}):{Message}");
- }
}
public override string Message => base.Message;
diff --git a/src/System.Net.Primitives/src/System/Net/SocketException.netstandard17.cs b/src/System.Net.Primitives/src/System/Net/SocketException.netstandard17.cs
index 22f453a8ee..4b874175bc 100644
--- a/src/System.Net.Primitives/src/System/Net/SocketException.netstandard17.cs
+++ b/src/System.Net.Primitives/src/System/Net/SocketException.netstandard17.cs
@@ -13,10 +13,7 @@ namespace System.Net.Sockets
protected SocketException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SocketException::.ctor(serialized) " + NativeErrorCode.ToString() + ":" + Message);
- }
+ NetEventSource.Info(this, $"{NativeErrorCode}:{Message}");
}
public override int ErrorCode => base.NativeErrorCode;
diff --git a/src/System.Net.Primitives/tests/FunctionalTests/LoggingTest.cs b/src/System.Net.Primitives/tests/FunctionalTests/LoggingTest.cs
new file mode 100644
index 0000000000..f3ced29345
--- /dev/null
+++ b/src/System.Net.Primitives/tests/FunctionalTests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.Primitives.Functional.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(IPAddress).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-Primitives", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("a9f9e4e1-0cf5-5005-b530-3d37959d5e84"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj b/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj
index 40b8ef31c0..90d2bd57ad 100644
--- a/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj
+++ b/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj
@@ -37,6 +37,7 @@
<Compile Include="SocketAddressTest.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == ''">
+ <Compile Include="LoggingTest.cs" />
<Compile Include="SerializationTest.cs" />
<Compile Include="CookieContainerAddTest.cs" />
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
diff --git a/src/System.Net.Primitives/tests/PalTests/Fakes/GlobalLog.cs b/src/System.Net.Primitives/tests/PalTests/Fakes/GlobalLog.cs
deleted file mode 100644
index fc9d021566..0000000000
--- a/src/System.Net.Primitives/tests/PalTests/Fakes/GlobalLog.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Net
-{
- public static class GlobalLog
- {
- public static void Assert(string message)
- {
- }
-
- public static void Print(string message)
- {
- }
-
- public static bool IsEnabled { get { return false; } }
- }
-}
diff --git a/src/System.Net.Primitives/tests/PalTests/Fakes/NetEventSource.cs b/src/System.Net.Primitives/tests/PalTests/Fakes/NetEventSource.cs
new file mode 100644
index 0000000000..4a936d5048
--- /dev/null
+++ b/src/System.Net.Primitives/tests/PalTests/Fakes/NetEventSource.cs
@@ -0,0 +1,13 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Net
+{
+ public static class NetEventSource
+ {
+ public static void Enter(object thisOrContextObject, object arg1 = null, object arg2 = null, object arg3 = null) { }
+ public static void Fail(object thisOrContextObject, object arg) { }
+ public static bool IsEnabled => false;
+ }
+}
diff --git a/src/System.Net.Primitives/tests/PalTests/System.Net.Primitives.Pal.Tests.csproj b/src/System.Net.Primitives/tests/PalTests/System.Net.Primitives.Pal.Tests.csproj
index 085bae1f4b..f1373f233b 100644
--- a/src/System.Net.Primitives/tests/PalTests/System.Net.Primitives.Pal.Tests.csproj
+++ b/src/System.Net.Primitives/tests/PalTests/System.Net.Primitives.Pal.Tests.csproj
@@ -32,7 +32,7 @@
<Compile Include="HostInformationPalTest.cs" />
<Compile Include="SocketAddressPalTest.cs" />
- <Compile Include="Fakes\GlobalLog.cs" />
+ <Compile Include="Fakes\NetEventSource.cs" />
<Compile Include="Fakes\Serialization.cs" Condition="'$(TargetGroup)' != ''"/>
<Compile Include="..\..\src\System\Net\EndPoint.cs" >
diff --git a/src/System.Net.Primitives/tests/UnitTests/Fakes/GlobalLog.cs b/src/System.Net.Primitives/tests/UnitTests/Fakes/GlobalLog.cs
deleted file mode 100644
index 327d1d5dac..0000000000
--- a/src/System.Net.Primitives/tests/UnitTests/Fakes/GlobalLog.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Net
-{
- public static class GlobalLog
- {
- public static void Assert(string message)
- {
- }
-
- public static void AssertFormat(string messageFormat, params object[] data)
- {
- }
-
- public static void Print(string message)
- {
- }
-
- public static bool IsEnabled { get { return false; } }
- }
-}
diff --git a/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj b/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj
index 0d6e626df3..c3b3318894 100644
--- a/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj
+++ b/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj
@@ -28,7 +28,6 @@
<Compile Include="CookieCollectionTest.cs" />
<Compile Include="CookieContainerTest.cs" />
<Compile Include="CookieInternalTest.cs" />
- <Compile Include="Fakes\GlobalLog.cs" />
<Compile Include="Fakes\HostInformation.cs" />
<Compile Include="Fakes\IPAddressPal.cs" />
<Compile Include="Fakes\CookieException.cs" />
@@ -91,11 +90,8 @@
<Compile Include="$(CommonPath)\System\Net\Shims\TraceSource.cs">
<Link>ProductionCode\Common\System\Net\Shims\TraceSource.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>ProductionCode\Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>ProductionCode\Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>ProductionCode\Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>ProductionCode\Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.Requests/src/System.Net.Requests.csproj b/src/System.Net.Requests/src/System.Net.Requests.csproj
index 6410125901..bc1028bc65 100644
--- a/src/System.Net.Requests/src/System.Net.Requests.csproj
+++ b/src/System.Net.Requests/src/System.Net.Requests.csproj
@@ -59,17 +59,18 @@
<Compile Include="System\Net\Cache\HttpRequestCachePolicy.cs" />
<Compile Include="System\Net\HttpDateParse.cs" />
<Compile Include="System\Net\HttpVersion.cs" />
+ <Compile Include="System\Net\NetEventSource.Requests.cs" />
<Compile Include="$(CommonPath)\System\Net\Http\HttpHandlerDefaults.cs">
<Link>Common\System\Net\Http\HttpHandlerDefaults.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\DebugThreadTracking.cs">
+ <Link>Common\System\Net\Logging\DebugThreadTracking.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs">
<Link>Common\System\Net\HttpKnownHeaderNames.cs</Link>
@@ -92,12 +93,6 @@
<Compile Include="$(CommonPath)\System\Net\SecurityProtocol.cs">
<Link>Common\System\Net\SecurityProtocol.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\System\NotImplemented.cs">
<Link>Common\System\NotImplemented.cs</Link>
</Compile>
diff --git a/src/System.Net.Requests/src/System/Net/CommandStream.cs b/src/System.Net.Requests/src/System/Net/CommandStream.cs
index 70fe5e55c3..80cbda22fd 100644
--- a/src/System.Net.Requests/src/System/Net/CommandStream.cs
+++ b/src/System.Net.Requests/src/System/Net/CommandStream.cs
@@ -48,10 +48,7 @@ namespace System.Net
internal virtual void Abort(Exception e)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CommandStream" + LoggingHash.HashString(this) + "::Abort() - closing control Stream");
- }
+ NetEventSource.Info(this, "closing control Stream");
lock (this)
{
@@ -79,10 +76,7 @@ namespace System.Net
protected override void Dispose(bool disposing)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CommandStream" + LoggingHash.HashString(this) + "::Close()");
- }
+ NetEventSource.Info(this);
InvokeRequestCallback(null);
@@ -215,7 +209,7 @@ namespace System.Net
if (index != -1)
sendCommand = sendCommand.Substring(0, index) + " ********";
}
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, string.Format("Sending command {0}", sendCommand));
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Sending command {sendCommand}");
}
try
@@ -668,8 +662,7 @@ namespace System.Net
state.Resp.StatusDescription = responseString.Substring(0, completeLength);
// Set the StatusDescription to the complete part of the response. Note that the Buffer has already been taken care of above.
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, string.Format("Received response: {0}", responseString.Substring(0, completeLength - 2)));
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Received response: {responseString.Substring(0, completeLength - 2)}");
if (_isAsync)
{
diff --git a/src/System.Net.Requests/src/System/Net/FtpControlStream.cs b/src/System.Net.Requests/src/System/Net/FtpControlStream.cs
index ac20c5336c..262c9a2995 100644
--- a/src/System.Net.Requests/src/System/Net/FtpControlStream.cs
+++ b/src/System.Net.Requests/src/System/Net/FtpControlStream.cs
@@ -231,11 +231,7 @@ namespace System.Net
// This function controls the setting up of a data socket/connection, and of saving off the server responses.
protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpControlStream#" + LoggingHash.HashString(this) + ">" + (entry == null ? "null" : entry.Command));
- GlobalLog.Print("FtpControlStream#" + LoggingHash.HashString(this) + ">" + ((response == null) ? "null" : response.StatusDescription));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}");
// null response is not expected
if (response == null)
@@ -467,10 +463,7 @@ namespace System.Net
bool resetLoggedInState = false;
FtpWebRequest request = (FtpWebRequest)req;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpControlStream#" + LoggingHash.HashString(this) + "BuildCommandsList");
- }
+ NetEventSource.Info(this);
_responseUri = request.RequestUri;
ArrayList commandList = new ArrayList();
@@ -682,12 +675,7 @@ namespace System.Net
{
if (port == -1)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("FtpControlStream#{0}|'port' not set.", LoggingHash.HashString(this));
- }
-
- Debug.Fail(string.Format("FtpControlStream#{0}|'port' not set.", LoggingHash.HashString(this)));
+ NetEventSource.Fail(this, "'port' not set.");
}
try
@@ -711,10 +699,7 @@ namespace System.Net
{
IPEndPoint passiveEndPoint = _passiveEndPoint;
_passiveEndPoint = null;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpControlStream#" + LoggingHash.HashString(this) + "starting Connect()");
- }
+ NetEventSource.Info(this, "starting Connect()");
if (_isAsync)
{
_dataSocket.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this);
@@ -728,10 +713,7 @@ namespace System.Net
}
else
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpControlStream#" + LoggingHash.HashString(this) + "starting Accept()");
- }
+ NetEventSource.Info(this, "starting Accept()");
if (_isAsync)
{
@@ -1182,10 +1164,7 @@ namespace System.Net
protected override bool CheckValid(ResponseDescription response, ref int validThrough, ref int completeLength)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpControlStream#" + LoggingHash.HashString(this) + "CheckValid(" + response.StatusBuffer.ToString() + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CheckValid({response.StatusBuffer})");
// If the response is less than 4 bytes long, it is too short to tell, so return true, valid so far.
if (response.StatusBuffer.Length < 4)
diff --git a/src/System.Net.Requests/src/System/Net/FtpDataStream.cs b/src/System.Net.Requests/src/System/Net/FtpDataStream.cs
index 5a65dbc117..f0a0bbf818 100644
--- a/src/System.Net.Requests/src/System/Net/FtpDataStream.cs
+++ b/src/System.Net.Requests/src/System/Net/FtpDataStream.cs
@@ -25,10 +25,7 @@ namespace System.Net
internal FtpDataStream(NetworkStream networkStream, FtpWebRequest request, TriState writeOnly)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpDataStream#" + LoggingHash.HashString(this) + "::FtpDataStream");
- }
+ NetEventSource.Info(this);
_readable = true;
_writeable = true;
@@ -61,10 +58,7 @@ namespace System.Net
void ICloseEx.CloseEx(CloseExState closeState)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpDataStream#" + LoggingHash.HashString(this) + "::CloseEx, state = " + closeState.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state = {closeState}");
lock (this)
{
diff --git a/src/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/System.Net.Requests/src/System/Net/FtpWebRequest.cs
index 0f9886f343..0b2b62f670 100644
--- a/src/System.Net.Requests/src/System/Net/FtpWebRequest.cs
+++ b/src/System.Net.Requests/src/System/Net/FtpWebRequest.cs
@@ -513,8 +513,7 @@ namespace System.Net
internal FtpWebRequest(Uri uri)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, ".ctor", uri.ToString());
+ NetEventSource.Info(this, uri);
if ((object)uri.Scheme != (object)Uri.UriSchemeFtp)
throw new ArgumentOutOfRangeException("uri");
@@ -551,15 +550,10 @@ namespace System.Net
//
public override WebResponse GetResponse()
{
- if (NetEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "GetResponse", "");
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "GetResponse", string.Format("Method: {0}", _methodInfo.Method));
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::GetResponse");
+ NetEventSource.Enter(this);
+ NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
try
@@ -623,28 +617,14 @@ namespace System.Net
}
catch (Exception exception)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "GetResponse", exception);
- }
+ NetEventSource.Error(this, exception);
// if _exception == null, we are about to throw an exception to the user
// and we haven't saved the exception, which also means we haven't dealt
// with it. So just release the connection and log this for investigation.
if (_exception == null)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintWarning(NetEventSource.ComponentType.Web, "Unexpected exception in GetResponse()");
-
- if (!ExceptionCheck.IsFatal(exception))
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("Find out why we are getting an unexpected exception.");
- }
-
- Debug.Fail("Find out why we are getting an unexpected exception.");
- }
+ NetEventSource.Error(this, exception);
SetException(exception);
FinishRequestStage(RequestStage.CheckForError);
}
@@ -652,12 +632,7 @@ namespace System.Net
}
finally
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::GetResponse", "returns #" + LoggingHash.HashString(_ftpWebResponse));
- }
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "GetResponse", "");
+ NetEventSource.Exit(this, _ftpWebResponse);
}
return _ftpWebResponse;
}
@@ -667,14 +642,10 @@ namespace System.Net
/// </summary>
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
- if (NetEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "BeginGetResponse", "");
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "BeginGetResponse", string.Format("Method: {0}", _methodInfo.Method));
- }
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::BeginGetResponse");
+ NetEventSource.Enter(this);
+ NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
ContextAwareResult asyncResult;
@@ -738,19 +709,12 @@ namespace System.Net
}
catch (Exception exception)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "BeginGetResponse", exception);
+ NetEventSource.Error(this, exception);
throw;
}
finally
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::BeginGetResponse");
- }
-
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "BeginGetResponse", "");
+ NetEventSource.Exit(this);
}
return asyncResult;
@@ -761,14 +725,7 @@ namespace System.Net
/// </summary>
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "EndGetResponse", "");
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::EndGetResponse");
- }
-
+ NetEventSource.Enter(this);
try
{
// parameter validation
@@ -792,18 +749,12 @@ namespace System.Net
}
catch (Exception exception)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "EndGetResponse", exception);
+ NetEventSource.Error(this, exception);
throw;
}
finally
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::EndGetResponse");
- }
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "EndGetResponse", "");
+ NetEventSource.Exit(this);
}
return _ftpWebResponse;
@@ -814,16 +765,12 @@ namespace System.Net
/// </summary>
public override Stream GetRequestStream()
{
- if (NetEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "GetRequestStream", "");
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "GetRequestStream", string.Format("Method: {0}", _methodInfo.Method));
+ NetEventSource.Enter(this);
+ NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::GetRequestStream");
- }
try
{
if (_getRequestStreamStarted)
@@ -863,18 +810,12 @@ namespace System.Net
}
catch (Exception exception)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "GetRequestStream", exception);
+ NetEventSource.Error(this, exception);
throw;
}
finally
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::GetRequestStream");
- }
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "GetRequestStream", "");
+ NetEventSource.Exit(this);
}
return _stream;
}
@@ -884,14 +825,10 @@ namespace System.Net
/// </summary>
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", "");
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", string.Format("Method: {0}", _methodInfo.Method));
- }
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::BeginGetRequestStream");
+ NetEventSource.Enter(this);
+ NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
ContextAwareResult asyncResult = null;
@@ -920,18 +857,12 @@ namespace System.Net
}
catch (Exception exception)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", exception);
+ NetEventSource.Error(this, exception);
throw;
}
finally
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::BeginGetRequestStream");
- }
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", "");
+ NetEventSource.Exit(this);
}
return asyncResult;
@@ -939,14 +870,7 @@ namespace System.Net
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "EndGetRequestStream", "");
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::EndGetRequestStream");
- }
-
+ NetEventSource.Enter(this);
Stream requestStream = null;
try
{
@@ -981,18 +905,12 @@ namespace System.Net
}
catch (Exception exception)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "EndGetRequestStream", exception);
+ NetEventSource.Error(this, exception);
throw;
}
finally
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::EndGetRequestStream");
- }
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "EndGetRequestStream", "");
+ NetEventSource.Exit(this);
}
return requestStream;
}
@@ -1041,10 +959,7 @@ namespace System.Net
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Request being submitted" + LoggingHash.HashString(this));
- }
+ NetEventSource.Info(this, "Request being submitted");
connection.SetSocketTimeoutOption(RemainingTimeout);
@@ -1214,18 +1129,12 @@ namespace System.Net
/// </summary>
private void TimerCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpWebRequest#" + LoggingHash.HashString(this) + "::TimerCallback");
- }
+ NetEventSource.Info(this);
FtpControlStream connection = _connection;
if (connection != null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpWebRequest#" + LoggingHash.HashString(this) + "::TimerCallback aborting connection");
- }
+ NetEventSource.Info(this, "aborting connection");
connection.AbortConnect();
}
}
@@ -1264,8 +1173,7 @@ namespace System.Net
if (_connection != null)
{
_connection.CloseSocket();
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "", string.Format("Releasing connection: {0}", LoggingHash.HashString(_connection)));
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {_connection}");
_connection = null;
}
else
@@ -1281,10 +1189,7 @@ namespace System.Net
/// </summary>
private void SetException(Exception exception)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpWebRequest#" + LoggingHash.HashString(this) + "::SetException");
- }
+ NetEventSource.Info(this);
if (exception is OutOfMemoryException)
{
@@ -1343,10 +1248,7 @@ namespace System.Net
//
private void SyncRequestCallback(object obj)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::SyncRequestCallback", "#" + LoggingHash.HashString(obj));
- }
+ NetEventSource.Enter(this, obj);
RequestStage stageMode = RequestStage.CheckForError;
try
@@ -1354,10 +1256,7 @@ namespace System.Net
bool completedRequest = obj == null;
Exception exception = obj as Exception;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SyncRequestCallback() exp:" + LoggingHash.HashString(exception) + " completedRequest:" + LoggingHash.HashString(completedRequest));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"exp:{exception} completedRequest:{completedRequest}");
if (exception != null)
{
@@ -1390,10 +1289,7 @@ namespace System.Net
finally
{
FinishRequestStage(stageMode);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::SyncRequestCallback");
- }
+ NetEventSource.Exit(this);
CheckError(); //will throw on error
}
}
@@ -1403,10 +1299,7 @@ namespace System.Net
//
private void AsyncRequestCallback(object obj)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::AsyncRequestCallback", "#" + LoggingHash.HashString(obj));
- }
+ NetEventSource.Enter(this, obj);
RequestStage stageMode = RequestStage.CheckForError;
try
@@ -1418,10 +1311,7 @@ namespace System.Net
bool completedRequest = (obj == null);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("AsyncRequestCallback() stream:" + LoggingHash.HashString(stream) + " conn:" + LoggingHash.HashString(connection) + " exp:" + LoggingHash.HashString(exception) + " completedRequest:" + LoggingHash.HashString(completedRequest));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"stream:{stream} conn:{connection} exp:{exception} completedRequest:{completedRequest}");
while (true)
{
if (exception != null)
@@ -1447,14 +1337,12 @@ namespace System.Net
{
if (_aborted)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "", string.Format("Releasing connection: {0}", LoggingHash.HashString(connection)));
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connect:{connection}");
connection.CloseSocket();
break;
}
_connection = connection;
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Associate(NetEventSource.ComponentType.Web, this, _connection);
+ NetEventSource.Associate(this, _connection);
}
try
@@ -1514,10 +1402,7 @@ namespace System.Net
finally
{
FinishRequestStage(stageMode);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::AsyncRequestCallback");
- }
+ NetEventSource.Exit(this);
}
}
@@ -1535,10 +1420,8 @@ namespace System.Net
//
private RequestStage FinishRequestStage(RequestStage stage)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpWebRequest#" + LoggingHash.HashString(this) + "::FinishRequestStage : stage=" + stage);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state:{stage}");
+
if (_exception != null)
stage = RequestStage.ReleaseConnection;
@@ -1601,8 +1484,7 @@ namespace System.Net
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "", string.Format("Releasing connection: {0}", LoggingHash.HashString(connection)));
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {connection}");
connection.CloseSocket();
if (_async)
if (_requestCompleteAsyncResult != null)
@@ -1649,16 +1531,10 @@ namespace System.Net
if (_aborted)
return;
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "Abort", "");
+ NetEventSource.Enter(this);
try
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpWebRequest#" + LoggingHash.HashString(this) + "::Abort()");
- }
-
Stream stream;
FtpControlStream connection;
lock (_syncObject)
@@ -1675,12 +1551,7 @@ namespace System.Net
{
if (!(stream is ICloseEx))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("FtpWebRequest.Abort()|The _stream member is not CloseEx hence the risk of connection been orphaned.");
- }
-
- Debug.Fail("FtpWebRequest.Abort()|The _stream member is not CloseEx hence the risk of connection been orphaned.");
+ NetEventSource.Fail(this, "The _stream member is not CloseEx hence the risk of connection been orphaned.");
}
((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent);
@@ -1690,14 +1561,12 @@ namespace System.Net
}
catch (Exception exception)
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "Abort", exception);
+ NetEventSource.Error(this, exception);
throw;
}
finally
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "Abort", "");
+ NetEventSource.Exit(this);
}
}
@@ -1941,10 +1810,7 @@ namespace System.Net
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpWebRequest#" + LoggingHash.HashString(this) + "::EnsureFtpWebResponse returns #" + LoggingHash.HashString(_ftpWebResponse) + " with stream#" + LoggingHash.HashString(_ftpWebResponse._responseStream));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returns {_ftpWebResponse} with stream {_ftpWebResponse._responseStream}");
return;
}
diff --git a/src/System.Net.Requests/src/System/Net/FtpWebResponse.cs b/src/System.Net.Requests/src/System/Net/FtpWebResponse.cs
index b22622353f..b7273c3550 100644
--- a/src/System.Net.Requests/src/System/Net/FtpWebResponse.cs
+++ b/src/System.Net.Requests/src/System/Net/FtpWebResponse.cs
@@ -24,10 +24,7 @@ namespace System.Net
internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("FtpWebResponse#" + LoggingHash.HashString(this) + "::.ctor(" + contentLength.ToString() + "," + statusLine + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, contentLength, statusLine);
_responseStream = responseStream;
if (responseStream == null && contentLength < 0)
@@ -85,17 +82,9 @@ namespace System.Net
/// </summary>
public override void Close()
{
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "Close", "");
-
- Stream stream = _responseStream;
- if (stream != null)
- {
- stream.Close();
- }
-
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "Close", "");
+ NetEventSource.Enter(this);
+ _responseStream?.Close();
+ NetEventSource.Exit(this);
}
/// <summary>
diff --git a/src/System.Net.Requests/src/System/Net/HttpWebRequest.cs b/src/System.Net.Requests/src/System/Net/HttpWebRequest.cs
index 37383651b8..70606cd499 100644
--- a/src/System.Net.Requests/src/System/Net/HttpWebRequest.cs
+++ b/src/System.Net.Requests/src/System/Net/HttpWebRequest.cs
@@ -94,7 +94,7 @@ namespace System.Net
protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) {
#endif
_webHeaderCollection = (WebHeaderCollection)serializationInfo.GetValue("_HttpRequestHeaders", typeof(WebHeaderCollection));
Proxy = (IWebProxy)serializationInfo.GetValue("_Proxy", typeof(IWebProxy));
@@ -139,7 +139,7 @@ namespace System.Net
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) {
#endif
GetObjectData(serializationInfo, streamingContext);
#if DEBUG
@@ -150,7 +150,7 @@ namespace System.Net
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) {
#endif
serializationInfo.AddValue("_HttpRequestHeaders", _webHeaderCollection, typeof(WebHeaderCollection));
serializationInfo.AddValue("_Proxy", _proxy, typeof(IWebProxy));
@@ -363,7 +363,7 @@ namespace System.Net
set
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool fChunked;
//
@@ -528,7 +528,7 @@ namespace System.Net
set
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool fKeepAlive;
bool fClose;
@@ -587,7 +587,7 @@ namespace System.Net
set
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
// only remove everything other than 100-cont
bool fContinue100;
@@ -1431,7 +1431,7 @@ namespace System.Net
private DateTime GetDateHeaderHelper(string headerName)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
string headerValue = _webHeaderCollection[headerName];
@@ -1448,7 +1448,7 @@ namespace System.Net
private void SetDateHeaderHelper(string headerName, DateTime dateTime)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
if (dateTime == DateTime.MinValue)
SetSpecialHeaders(headerName, null); // remove header
diff --git a/src/System.Net.Requests/src/System/Net/NetEventSource.Requests.cs b/src/System.Net.Requests/src/System/Net/NetEventSource.Requests.cs
new file mode 100644
index 0000000000..6dc94110d5
--- /dev/null
+++ b/src/System.Net.Requests/src/System/Net/NetEventSource.Requests.cs
@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-Requests")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.Requests/src/System/Net/TimerThread.cs b/src/System.Net.Requests/src/System/Net/TimerThread.cs
index fb0808b525..1c72933fce 100644
--- a/src/System.Net.Requests/src/System/Net/TimerThread.cs
+++ b/src/System.Net.Requests/src/System/Net/TimerThread.cs
@@ -270,12 +270,7 @@ namespace System.Net
{
if (!(_timers.Prev.Next == _timers))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("TimerThread#{0}::CreateTimer()|Tail corruption.", Thread.CurrentThread.ManagedThreadId.ToString());
- }
-
- Debug.Fail(string.Format("TimerThread#{0}::CreateTimer()|Tail corruption.", Thread.CurrentThread.ManagedThreadId.ToString()));
+ NetEventSource.Fail(this, $"Tail corruption.");
}
// If this is the first timer in the list, we need to create a queue handle and prod the timer thread.
@@ -390,10 +385,7 @@ namespace System.Net
}
_timerState = TimerState.Ready;
_queueLock = queueLock;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThreadTimer#" + StartTime.ToString() + "::.ctor()");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}");
}
// A sentinel node - both the head and tail are one, which prevent the head and tail from ever having to be updated.
@@ -461,19 +453,13 @@ namespace System.Net
_timerState = TimerState.Cancelled;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThreadTimer#" + StartTime.ToString() + "::Cancel() (success)");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (success)");
return true;
}
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThreadTimer#" + StartTime.ToString() + "::Cancel() (failure)");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (failure)");
return false;
}
@@ -485,12 +471,7 @@ namespace System.Net
{
if (_timerState == TimerState.Sentinel)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("TimerThread#{0}::Fire()|TimerQueue tried to Fire a Sentinel.", Thread.CurrentThread.ManagedThreadId.ToString());
- }
-
- Debug.Fail(string.Format("TimerThread#{0}::Fire()|TimerQueue tried to Fire a Sentinel.", Thread.CurrentThread.ManagedThreadId.ToString()));
+ NetEventSource.Info(this, "TimerQueue tried to Fire a Sentinel.");
}
if (_timerState != TimerState.Ready)
@@ -503,10 +484,7 @@ namespace System.Net
int nowMilliseconds = Environment.TickCount;
if (IsTickBetween(StartTime, Expiration, nowMilliseconds))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() Not firing (" + StartTime + " <= " + nowMilliseconds + " < " + Expiration + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Not firing ({StartTime} <= {nowMilliseconds} < {Expiration})");
return false;
}
@@ -515,10 +493,7 @@ namespace System.Net
{
if (_timerState == TimerState.Ready)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() Firing (" + StartTime + " <= " + nowMilliseconds + " >= " + Expiration + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Firing ({StartTime} <= {nowMilliseconds} >= " + Expiration + ")");
_timerState = TimerState.Fired;
// Remove it from the list.
@@ -546,13 +521,7 @@ namespace System.Net
if (ExceptionCheck.IsFatal(exception))
throw;
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintError(NetEventSource.ComponentType.Web, "TimerThreadTimer#" + StartTime.ToString(NumberFormatInfo.InvariantInfo) + "::Fire() - exception in callback: " + exception);
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() exception in callback: " + exception);
- }
+ NetEventSource.Error(this, $"exception in callback: {exception}");
// This thread is not allowed to go into user code, so we should never get an exception here.
// So, in debug, throw it up, killing the AppDomain. In release, we'll just ignore it.
@@ -615,16 +584,12 @@ namespace System.Net
/// </summary>
private static void ThreadProc()
{
+ NetEventSource.Enter(null);
#if DEBUG
- GlobalLog.SetThreadSource(ThreadKinds.Timer);
- using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
+ DebugThreadTracking.SetThreadSource(ThreadKinds.Timer);
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Start");
- }
-
// Set this thread as a background thread. On AppDomain/Process shutdown, the thread will just be killed.
Thread.CurrentThread.IsBackground = true;
@@ -696,28 +661,19 @@ namespace System.Net
0) :
c_ThreadIdleTimeoutMilliseconds;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Waiting for " + waitDuration + "ms");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Waiting for {waitDuration}ms");
int waitResult = WaitHandle.WaitAny(s_ThreadEvents, waitDuration, false);
// 0 is s_ThreadShutdownEvent - die.
if (waitResult == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Awoke, cause: Shutdown");
- }
+ NetEventSource.Info(null, "Awoke, cause: Shutdown");
running = false;
break;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Awoke, cause: " + (waitResult == WaitHandle.WaitTimeout ? "Timeout" : "Prod"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Awoke, cause {(waitResult == WaitHandle.WaitTimeout ? "Timeout" : "Prod")}");
// If we timed out with nothing to do, shut down.
if (waitResult == WaitHandle.WaitTimeout && !haveNextTick)
@@ -743,13 +699,7 @@ namespace System.Net
if (ExceptionCheck.IsFatal(exception))
throw;
- if (NetEventSource.Log.IsEnabled())
- NetEventSource.PrintError(NetEventSource.ComponentType.Web, "TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString(NumberFormatInfo.InvariantInfo) + "::ThreadProc() - Exception:" + exception.ToString());
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() exception: " + exception);
- }
+ NetEventSource.Error(null, exception);
// The only options are to continue processing and likely enter an error-loop,
// shut down timers for this AppDomain, or shut down the AppDomain. Go with shutting
@@ -765,10 +715,7 @@ namespace System.Net
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Stop");
- }
+ NetEventSource.Info(null, "Stop");
#if DEBUG
}
#endif
diff --git a/src/System.Net.Requests/src/System/Net/WebRequest.cs b/src/System.Net.Requests/src/System/Net/WebRequest.cs
index a5c52bb22a..9b8b24fa65 100644
--- a/src/System.Net.Requests/src/System/Net/WebRequest.cs
+++ b/src/System.Net.Requests/src/System/Net/WebRequest.cs
@@ -59,10 +59,7 @@ namespace System.Net
// Newly created WebRequest.
private static WebRequest Create(Uri requestUri, bool useUriBase)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Requests, "WebRequest", "Create", requestUri.ToString());
- }
+ NetEventSource.Enter(null, requestUri);
string LookupUri;
WebRequestPrefixElement Current = null;
@@ -123,19 +120,12 @@ namespace System.Net
{
// We found a match, so just call the creator and return what it does.
webRequest = Current.Creator.Create(requestUri);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Requests, "WebRequest", "Create", webRequest);
- }
+ NetEventSource.Exit(null, webRequest);
return webRequest;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Requests, "WebRequest", "Create", null);
- }
-
// Otherwise no match, throw an exception.
+ NetEventSource.Exit(null);
throw new NotSupportedException(SR.net_unknown_prefix);
}
diff --git a/src/System.Net.Requests/tests/LoggingTest.cs b/src/System.Net.Requests/tests/LoggingTest.cs
new file mode 100644
index 0000000000..f6f42f0ee0
--- /dev/null
+++ b/src/System.Net.Requests/tests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(WebRequest).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-Requests", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("3763dc7e-7046-5576-9041-5616e21cc2cf"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj b/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj
index 1a109a7a53..b00d6cd30f 100644
--- a/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj
+++ b/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj
@@ -46,12 +46,13 @@
<ItemGroup Condition="'$(TargetGroup)'==''">
<Compile Include="AuthorizationTest.cs" />
<Compile Include="AuthenticationManagerTest.cs" />
- <Compile Include="FileWebRequestTest.cs" />
<Compile Include="GlobalProxySelectionTest.cs" />
+ <Compile Include="FileWebRequestTest.cs" />
+ <Compile Include="FtpWebRequestTest.cs" />
+ <Compile Include="LoggingTest.cs" />
<Compile Include="HttpRequestCachePolicyTest.cs" />
<Compile Include="HttpWebRequestHeaderTest.cs" />
<Compile Include="HttpWebResponseHeaderTest.cs" />
- <Compile Include="FtpWebRequestTest.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\pkg\System.Net.Requests.pkgproj">
diff --git a/src/System.Net.Security/src/System.Net.Security.csproj b/src/System.Net.Security/src/System.Net.Security.csproj
index 0be6d42585..5d035141b7 100644
--- a/src/System.Net.Security/src/System.Net.Security.csproj
+++ b/src/System.Net.Security/src/System.Net.Security.csproj
@@ -35,6 +35,7 @@
<Compile Include="System\Net\SecurityStatusPal.cs" />
<Compile Include="System\Net\SslStreamContext.cs" />
<Compile Include="System\Net\Security\AuthenticatedStream.cs" />
+ <Compile Include="System\Net\Security\NetEventSource.Security.cs" />
<Compile Include="System\Net\Security\SecurityBuffer.cs" />
<Compile Include="System\Net\Security\SecurityBufferType.cs" />
<Compile Include="System\Net\Security\SecureChannel.cs" />
@@ -64,23 +65,14 @@
<Compile Include="System\Security\Authentication\ExtendedProtection\ProtectionScenario.cs" />
<Compile Include="System\Security\Authentication\ExtendedProtection\ServiceNameCollection.cs" />
<!-- Logging -->
+ <Compile Include="$(CommonPath)\System\Net\Logging\DebugThreadTracking.cs">
+ <Link>Common\System\Net\Logging\DebugThreadTracking.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\System\Net\Shims\TraceSource.cs">
<Link>Common\System\Net\Shims\TraceSource.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LogginHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\SecurityEventSource.cs">
- <Link>Common\System\Net\Logging\SecurityEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
@@ -134,6 +126,7 @@
</ItemGroup>
<ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(TargetGroup)' != 'net463' ">
<Compile Include="System\Net\CertificateValidationPal.Windows.cs" />
+ <Compile Include="System\Net\Security\NetEventSource.Security.Windows.cs" />
<Compile Include="System\Net\SecurityStatusAdapterPal.Windows.cs" />
<Compile Include="System\Net\Security\SecurityContextTokenHandle.cs" />
<Compile Include="System\Net\Security\SslStreamPal.Windows.cs" />
@@ -194,9 +187,6 @@
<Compile Include="$(CommonPath)\System\Collections\Generic\BidirectionalDictionary.cs">
<Link>Common\System\Collections\Generic\BidirectionalDictionary.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\SecurityEventSource.Windows.cs">
- <Link>Common\System\Net\Logging\SecurityEventSource.Windows.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\sspicli\SecurityPackageInfo.cs">
<Link>Common\Interop\Windows\sspicli\SecurityPackageInfo.cs</Link>
</Compile>
diff --git a/src/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs b/src/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs
index e7057d6a13..e7641c7394 100644
--- a/src/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs
+++ b/src/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs
@@ -40,10 +40,7 @@ namespace System.Net
return null;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("CertificateValidationPal.Unix SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()");
- }
+ NetEventSource.Enter(securityContext);
X509Certificate2 result = null;
SafeFreeCertContext remoteContext = null;
@@ -93,15 +90,8 @@ namespace System.Net
}
}
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.RemoteCertificate(result == null ? "null" : result.ToString(true));
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("CertificateValidationPal.Unix SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()", (result == null ? "null" : result.Subject));
- }
+ NetEventSource.Log.RemoteCertificate(result);
+ NetEventSource.Exit(securityContext, result);
return result;
}
@@ -172,24 +162,11 @@ namespace System.Net
Volatile.Write(ref storeField, store);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "CertModule::EnsureStoreOpened() storeLocation:" + storeLocation +
- " returned store:" + store.GetHashCode().ToString("x"));
- }
+ NetEventSource.Info(null, $"storeLocation: {storeLocation} returned store {store}");
}
catch (CryptographicException e)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert(
- "CertModule::EnsureStoreOpened()",
- "Failed to open cert store, location:" + storeLocation + " exception:" + e);
- }
- Debug.Fail(
- "CertModule::EnsureStoreOpened()",
- "Failed to open cert store, location:" + storeLocation + " exception:" + e);
+ NetEventSource.Fail(null, $"Failed to open cert store, location: {storeLocation} exception {e}");
throw;
}
}
diff --git a/src/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs b/src/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs
index 3543a4fa9d..0eda6ca84d 100644
--- a/src/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs
+++ b/src/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs
@@ -95,10 +95,7 @@ namespace System.Net
return null;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("CertificateValidationPal.Windows SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()");
- }
+ NetEventSource.Enter(securityContext);
X509Certificate2 result = null;
SafeFreeCertContext remoteContext = null;
@@ -120,16 +117,8 @@ namespace System.Net
}
}
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.RemoteCertificate(result == null ? "null" : result.ToString(true));
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("CertificateValidationPal.Windows SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()", (result == null ? "null" : result.Subject));
- }
-
+ NetEventSource.Log.RemoteCertificate(result);
+ NetEventSource.Exit(null, result, securityContext);
return result;
}
@@ -160,14 +149,8 @@ namespace System.Net
Interop.SspiCli.CERT_CHAIN_ELEMENT* pIL2 = pIL + i;
if (pIL2->cbSize <= 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel::GetIssuers()", "Interop.SspiCli._CERT_CHAIN_ELEMENT size is not positive: " + pIL2->cbSize.ToString());
- }
-
- Debug.Fail("SecureChannel::GetIssuers()", "Interop.SspiCli._CERT_CHAIN_ELEMENT size is not positive: " + pIL2->cbSize.ToString());
+ NetEventSource.Fail(securityContext, $"Interop.SspiCli._CERT_CHAIN_ELEMENT size is not positive: {pIL2->cbSize}");
}
-
if (pIL2->cbSize > 0)
{
uint size = pIL2->cbSize;
@@ -180,10 +163,7 @@ namespace System.Net
X500DistinguishedName x500DistinguishedName = new X500DistinguishedName(x);
issuers[i] = x500DistinguishedName.Name;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetIssuers() IssuerListEx[" + i + "]:" + issuers[i]);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(securityContext, "IssuerListEx[{issuers[i]}]");
}
}
}
@@ -226,10 +206,7 @@ namespace System.Net
WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () =>
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel::EnsureStoreOpened() storeLocation:" + storeLocation + " returned store:" + store.GetHashCode().ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"storeLocation {storeLocation} returned store: {store}");
});
}
catch
@@ -252,20 +229,11 @@ namespace System.Net
{
if (exception is CryptographicException || exception is SecurityException)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel::EnsureStoreOpened()", "Failed to open cert store, location:" + storeLocation + " exception:" + exception);
- }
-
- Debug.Fail("SecureChannel::EnsureStoreOpened()", "Failed to open cert store, location:" + storeLocation + " exception:" + exception);
+ if (NetEventSource.IsEnabled) NetEventSource.Fail(null, $"Failed to open cert store, location: {storeLocation} exception: {exception}");
return null;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_open_store_failed, storeLocation, exception));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_open_store_failed, storeLocation, exception));
throw;
}
}
@@ -277,10 +245,7 @@ namespace System.Net
private static uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel::VerifyChainPolicy", "chainContext=" + chainContext + ", options=" + String.Format("0x{0:x}", cpp.dwFlags));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(chainContext, cpp.dwFlags);
var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS();
status.cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CHAIN_POLICY_STATUS>();
@@ -292,15 +257,7 @@ namespace System.Net
ref cpp,
ref status);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel::VerifyChainPolicy() CertVerifyCertificateChainPolicy returned: " + errorCode);
-#if TRACE_VERBOSE
- GlobalLog.Print("SecureChannel::VerifyChainPolicy() error code: " + status.dwError + String.Format(" [0x{0:x8}", status.dwError) + " " + Interop.MapSecurityStatus(status.dwError) + "]");
-#endif
- GlobalLog.Leave("SecureChannel::VerifyChainPolicy", status.dwError.ToString());
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(chainContext, $"CertVerifyCertificateChainPolicy returned: {errorCode}. Status: {status.dwError}");
return status.dwError;
}
}
diff --git a/src/System.Net.Security/src/System/Net/FixedSizeReader.cs b/src/System.Net.Security/src/System/Net/FixedSizeReader.cs
index 9d904edb42..85bae05d67 100644
--- a/src/System.Net.Security/src/System/Net/FixedSizeReader.cs
+++ b/src/System.Net.Security/src/System/Net/FixedSizeReader.cs
@@ -105,12 +105,7 @@ namespace System.Net
if (_totalRead + bytes > _request.Count)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("FixedSizeReader::CheckCompletion()|State got out of range. Total:{0} Count:{1}", _totalRead + bytes, _request.Count);
- }
-
- Debug.Fail("FixedSizeReader::CheckCompletion()|State got out of range. Total:" + (_totalRead + bytes) + " Count:" + _request.Count);
+ NetEventSource.Fail(this, $"State got out of range. Total:{_totalRead + bytes} Count:{_request.Count}");
}
if ((_totalRead += bytes) == _request.Count)
@@ -126,12 +121,7 @@ namespace System.Net
{
if (!(transportResult.AsyncState is FixedSizeReader))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("ReadCallback|State type is wrong, expected FixedSizeReader.");
- }
-
- Debug.Fail("ReadCallback|State type is wrong, expected FixedSizeReader.");
+ NetEventSource.Fail(null, "State type is wrong, expected FixedSizeReader.");
}
if (transportResult.CompletedSynchronously)
diff --git a/src/System.Net.Security/src/System/Net/HelperAsyncResults.cs b/src/System.Net.Security/src/System/Net/HelperAsyncResults.cs
index 2e1f7039fe..c6f090c90c 100644
--- a/src/System.Net.Security/src/System/Net/HelperAsyncResults.cs
+++ b/src/System.Net.Security/src/System/Net/HelperAsyncResults.cs
@@ -44,21 +44,11 @@ namespace System.Net
{
if (userAsyncResult == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("AsyncProtocolRequest()|userAsyncResult == null");
- }
-
- Debug.Fail("AsyncProtocolRequest()|userAsyncResult == null");
+ NetEventSource.Fail(this, "userAsyncResult == null");
}
if (userAsyncResult.InternalPeekCompleted)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("AsyncProtocolRequest()|userAsyncResult is already completed.");
- }
-
- Debug.Fail("AsyncProtocolRequest()|userAsyncResult is already completed.");
+ NetEventSource.Fail(this, "userAsyncResult is already completed.");
}
UserAsyncResult = userAsyncResult;
}
diff --git a/src/System.Net.Security/src/System/Net/NTAuthentication.cs b/src/System.Net.Security/src/System/Net/NTAuthentication.cs
index b4269f1b1b..98d3b214a3 100644
--- a/src/System.Net.Security/src/System/Net/NTAuthentication.cs
+++ b/src/System.Net.Security/src/System/Net/NTAuthentication.cs
@@ -61,10 +61,7 @@ namespace System.Net
}
string name = NegotiateStreamPal.QueryContextAssociatedName(_securityContext);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication: The context is associated with [" + name + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"NTAuthentication: The context is associated with [{name}]");
return name;
}
}
@@ -229,10 +226,7 @@ namespace System.Net
private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlagsPal requestedContextFlags, ChannelBinding channelBinding)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::.ctor() package:" + LoggingHash.ObjectToString(package) + " spn:" + LoggingHash.ObjectToString(spn) + " flags :" + requestedContextFlags.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, package, spn, requestedContextFlags);
_tokenSize = NegotiateStreamPal.QueryMaxTokenSize(package);
_isServer = isServer;
@@ -242,10 +236,7 @@ namespace System.Net
_package = package;
_channelBinding = channelBinding;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Peer SPN-> '" + _spn + "'");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Peer SPN-> '{_spn}'");
//
// Check if we're using DefaultCredentials.
@@ -254,11 +245,7 @@ namespace System.Net
Debug.Assert(CredentialCache.DefaultCredentials == CredentialCache.DefaultNetworkCredentials);
if (credential == CredentialCache.DefaultCredentials)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::.ctor(): using DefaultCredentials");
- }
-
+ NetEventSource.Info(this, "using DefaultCredentials");
_credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(package, _isServer);
}
else
@@ -272,22 +259,12 @@ namespace System.Net
status = new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
if (!(IsCompleted && IsValidContext))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("NTAuthentication#{0}::GetContextToken|Should be called only when completed with success, currently is not!", LoggingHash.HashString(this));
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::GetContextToken |Should be called only when completed with success, currently is not!");
+ NetEventSource.Fail(this, "Should be called only when completed with success, currently is not!");
}
if (!IsServer)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("NTAuthentication#{0}::GetContextToken|The method must not be called by the client side!", LoggingHash.HashString(this));
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::GetContextToken |The method must not be called by the client side!");
+ NetEventSource.Fail(this, "The method must not be called by the client side!");
}
if (!IsValidContext)
@@ -310,10 +287,7 @@ namespace System.Net
// Accepts an incoming binary security blob and returns an outgoing binary security blob.
internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out SecurityStatusPal statusCode)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", ((incomingBlob == null) ? "0" : incomingBlob.Length.ToString(NumberFormatInfo.InvariantInfo)) + " bytes");
- }
+ NetEventSource.Enter(this, incomingBlob);
var list = new List<SecurityBuffer>(2);
@@ -350,10 +324,7 @@ namespace System.Net
outSecurityBuffer,
ref _contextFlags);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.InitializeSecurityContext() returns statusCode:0x" + ((int)statusCode.ErrorCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SSPIWrapper.InitializeSecurityContext() returns statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode})");
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded)
{
@@ -362,11 +333,8 @@ namespace System.Net
statusCode = NegotiateStreamPal.CompleteAuthToken(ref _securityContext, inSecurityBuffers);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.CompleteAuthToken() returns statusCode:0x" + ((int)statusCode.ErrorCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SSPIWrapper.CompleteAuthToken() returns statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode})");
+
outSecurityBuffer.token = null;
}
}
@@ -381,10 +349,7 @@ namespace System.Net
outSecurityBuffer,
ref _contextFlags);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.AcceptSecurityContext() returns statusCode:0x" + ((int)statusCode.ErrorCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SSPIWrapper.AcceptSecurityContext() returns statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode})");
}
}
finally
@@ -409,17 +374,11 @@ namespace System.Net
if (throwOnError)
{
Exception exception = NegotiateStreamPal.CreateExceptionFromError(statusCode);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", "Win32Exception:" + exception);
- }
+ NetEventSource.Exit(this, exception);
throw exception;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", "null statusCode:0x" + ((int)statusCode.ErrorCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"null statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode})");
return null;
}
else if (firstTime && _credentialsHandle != null)
@@ -434,15 +393,15 @@ namespace System.Net
// Success.
_isCompleted = true;
}
- else if (GlobalLog.IsEnabled)
+ else if (NetEventSource.IsEnabled)
{
// We need to continue.
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob() need continue statusCode:[0x" + ((int)statusCode.ErrorCode).ToString("x8", NumberFormatInfo.InvariantInfo) + "] (" + statusCode.ToString() + ") m_SecurityContext#" + LoggingHash.HashString(_securityContext) + "::Handle:" + LoggingHash.ObjectToString(_securityContext) + "]");
+ NetEventSource.Info(this, $"need continue statusCode:0x{((int)statusCode.ErrorCode):x8} ({statusCode}) _securityContext:{_securityContext}");
}
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Leave("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", "IsCompleted:" + IsCompleted.ToString());
+ NetEventSource.Exit(this, $"IsCompleted: {IsCompleted}");
}
return outSecurityBuffer.token;
@@ -470,20 +429,13 @@ namespace System.Net
{
if (!(IsValidContext && IsCompleted))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NTAuthentication: Trying to get the client SPN before handshaking is done!");
- }
-
- Debug.Fail("NTAuthentication: Trying to get the client SPN before handshaking is done!");
+ NetEventSource.Fail(this, "Trying to get the client SPN before handshaking is done!");
}
string spn = NegotiateStreamPal.QueryContextClientSpecifiedSpn(_securityContext);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication: The client specified SPN is [" + spn + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"The client specified SPN is [{spn}]");
+
return spn;
}
}
diff --git a/src/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs b/src/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs
index a233b337ec..4193c27182 100644
--- a/src/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs
+++ b/src/System.Net.Security/src/System/Net/Security/AuthenticatedStream.cs
@@ -47,7 +47,7 @@ namespace System.Net.Security
protected override void Dispose(bool disposing)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
try
diff --git a/src/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs b/src/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs
index 7217d46245..26f756e998 100644
--- a/src/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs
+++ b/src/System.Net.Security/src/System/Net/Security/InternalNegotiateStream.cs
@@ -292,12 +292,7 @@ namespace System.Net.Security
if (!(readBytes == _ReadHeader.Length))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("NegoStream::ProcessHeader()|Frame size must be 4 but received {0} bytes.", readBytes);
- }
-
- Debug.Fail("NegoStream::ProcessHeader()|Frame size must be 4 but received " + readBytes + " bytes.");
+ NetEventSource.Fail(this, $"Frame size must be 4 but received {readBytes} bytes.");
}
// Replace readBytes with the body size recovered from the header content.
@@ -390,12 +385,7 @@ namespace System.Net.Security
if (!(transportResult.AsyncState is AsyncProtocolRequest))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NegotiateSteam::WriteCallback|State type is wrong, expected AsyncProtocolRequest.");
- }
-
- Debug.Fail("NegotiateSteam::WriteCallback|State type is wrong, expected AsyncProtocolRequest.");
+ NetEventSource.Fail(transportResult, "State type is wrong, expected AsyncProtocolRequest.");
}
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
diff --git a/src/System.Net.Security/src/System/Net/Security/NegoState.cs b/src/System.Net.Security/src/System/Net/Security/NegoState.cs
index 97984176c2..71b5bcd8be 100644
--- a/src/System.Net.Security/src/System/Net/Security/NegoState.cs
+++ b/src/System.Net.Security/src/System/Net/Security/NegoState.cs
@@ -696,12 +696,7 @@ namespace System.Net.Security
{
if (!(transportResult.AsyncState is LazyAsyncResult))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("WriteCallback|State type is wrong, expected LazyAsyncResult.");
- }
-
- Debug.Fail("WriteCallback|State type is wrong, expected LazyAsyncResult.");
+ NetEventSource.Fail(transportResult, "State type is wrong, expected LazyAsyncResult.");
}
if (transportResult.CompletedSynchronously)
@@ -742,12 +737,7 @@ namespace System.Net.Security
{
if (!(transportResult.AsyncState is LazyAsyncResult))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("ReadCallback|State type is wrong, expected LazyAsyncResult.");
- }
-
- Debug.Fail("ReadCallback|State type is wrong, expected LazyAsyncResult.");
+ NetEventSource.Fail(transportResult, "State type is wrong, expected LazyAsyncResult.");
}
if (transportResult.CompletedSynchronously)
diff --git a/src/System.Net.Security/src/System/Net/Security/NegotiateStream.cs b/src/System.Net.Security/src/System/Net/Security/NegotiateStream.cs
index 0ee3b6c3c3..9684f87613 100644
--- a/src/System.Net.Security/src/System/Net/Security/NegotiateStream.cs
+++ b/src/System.Net.Security/src/System/Net/Security/NegotiateStream.cs
@@ -37,7 +37,7 @@ namespace System.Net.Security
public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState = new NegoState(innerStream, leaveInnerStreamOpen);
@@ -92,7 +92,7 @@ namespace System.Net.Security
object asyncState)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
@@ -109,7 +109,7 @@ namespace System.Net.Security
public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.EndProcessAuthentication(asyncResult);
@@ -136,7 +136,7 @@ namespace System.Net.Security
public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
@@ -175,7 +175,7 @@ namespace System.Net.Security
object asyncState)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
@@ -192,7 +192,7 @@ namespace System.Net.Security
public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.EndProcessAuthentication(asyncResult);
@@ -226,7 +226,7 @@ namespace System.Net.Security
NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
@@ -295,7 +295,7 @@ namespace System.Net.Security
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsAuthenticated;
@@ -310,7 +310,7 @@ namespace System.Net.Security
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsMutuallyAuthenticated;
@@ -325,7 +325,7 @@ namespace System.Net.Security
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsEncrypted;
@@ -340,7 +340,7 @@ namespace System.Net.Security
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsSigned;
@@ -355,7 +355,7 @@ namespace System.Net.Security
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.IsServer;
@@ -370,7 +370,7 @@ namespace System.Net.Security
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
return _negoState.AllowedImpersonation;
@@ -385,7 +385,7 @@ namespace System.Net.Security
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
@@ -493,7 +493,7 @@ namespace System.Net.Security
public override void Flush()
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
InnerStream.Flush();
@@ -505,7 +505,7 @@ namespace System.Net.Security
protected override void Dispose(bool disposing)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
try
@@ -524,7 +524,7 @@ namespace System.Net.Security
public override int Read(byte[] buffer, int offset, int count)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.CheckThrow(true);
@@ -543,7 +543,7 @@ namespace System.Net.Security
public override void Write(byte[] buffer, int offset, int count)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
_negoState.CheckThrow(true);
@@ -563,7 +563,7 @@ namespace System.Net.Security
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.CheckThrow(true);
@@ -585,7 +585,7 @@ namespace System.Net.Security
public override int EndRead(IAsyncResult asyncResult)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.CheckThrow(true);
@@ -635,7 +635,7 @@ namespace System.Net.Security
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
_negoState.CheckThrow(true);
@@ -658,7 +658,7 @@ namespace System.Net.Security
public override void EndWrite(IAsyncResult asyncResult)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
_negoState.CheckThrow(true);
diff --git a/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs b/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs
index 92b2e2e00a..5d32406d74 100644
--- a/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs
+++ b/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs
@@ -321,25 +321,13 @@ namespace System.Net.Security
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'offset' out of range.");
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'offset' out of range.");
-
+ NetEventSource.Fail(securityContext, "Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'count' out of range.");
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'count' out of range.");
-
+ NetEventSource.Fail(securityContext, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
@@ -408,11 +396,7 @@ namespace System.Net.Security
}
catch(Exception ex)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Exception Caught. - " + ex);
- }
-
+ NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
diff --git a/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs
index 04f69382f6..d95f6efb85 100644
--- a/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs
+++ b/src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs
@@ -116,16 +116,7 @@ namespace System.Net.Security
if (result != Interop.SECURITY_STATUS.OK)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.PrintError(
- NetEventSource.ComponentType.Security,
- SR.Format(
- SR.net_log_operation_failed_with_error,
- "SspiEncodeStringsAsAuthIdentity()",
- String.Format(CultureInfo.CurrentCulture, "0x{0:X}", (int)result)));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}"));
throw new Win32Exception((int)result);
}
@@ -240,18 +231,9 @@ namespace System.Net.Security
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.net_io_out_range, maxCount));
}
}
- catch (Exception e)
+ catch (Exception e) when (!ExceptionCheck.IsFatal(e))
{
- if (!ExceptionCheck.IsFatal(e))
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
- }
-
+ NetEventSource.Fail(null, "Arguments out of range.");
throw;
}
@@ -287,11 +269,9 @@ namespace System.Net.Security
if (errorCode != 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Encrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
- }
- throw new Win32Exception(errorCode);
+ Exception e = new Win32Exception(errorCode);
+ NetEventSource.Error(null, e);
+ throw e;
}
// Compacting the result.
@@ -333,25 +313,13 @@ namespace System.Net.Security
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'offset' out of range.");
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'offset' out of range.");
-
+ NetEventSource.Fail(null, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'count' out of range.");
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'count' out of range.");
-
+ NetEventSource.Fail(null, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
@@ -379,11 +347,9 @@ namespace System.Net.Security
if (errorCode != 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#"+ "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
- }
- throw new Win32Exception(errorCode);
+ Exception e = new Win32Exception(errorCode);
+ NetEventSource.Error(null, e);
+ throw e;
}
if (securityBuffer[1].type != SecurityBufferType.SECBUFFER_DATA)
@@ -408,13 +374,7 @@ namespace System.Net.Security
// For the most part the arguments are verified in Decrypt().
if (count < ntlmSignatureLength)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::DecryptNtlm", "Argument 'count' out of range.");
- }
-
- Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::DecryptNtlm", "Argument 'count' out of range.");
-
+ NetEventSource.Fail(null, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
@@ -438,10 +398,8 @@ namespace System.Net.Security
if (errorCode != 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
- }
+ Exception e = new Win32Exception(errorCode);
+ NetEventSource.Error(null, e);
throw new Win32Exception(errorCode);
}
diff --git a/src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs b/src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs
new file mode 100644
index 0000000000..6e9f24fd01
--- /dev/null
+++ b/src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs
@@ -0,0 +1,90 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using System.Net.Security;
+
+namespace System.Net
+{
+ internal sealed partial class NetEventSource
+ {
+ [Event(AcquireDefaultCredentialId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void AcquireDefaultCredential(string packageName, Interop.SspiCli.CredentialUse intent)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(AcquireDefaultCredentialId, packageName, intent);
+ }
+ }
+
+ [NonEvent]
+ public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, object authdata)
+ {
+ if (IsEnabled())
+ {
+ AcquireCredentialsHandle(packageName, intent, IdOf(authdata));
+ }
+ }
+
+ [Event(AcquireCredentialsHandleId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, string authdata)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(AcquireCredentialsHandleId, packageName, (int)intent, authdata);
+ }
+ }
+
+ [NonEvent]
+ public void InitializeSecurityContext(SafeFreeCredentials credential, SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags)
+ {
+ if (IsEnabled())
+ {
+ InitializeSecurityContext(IdOf(credential), IdOf(context), targetName, inFlags);
+ }
+ }
+ [Event(InitializeSecurityContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void InitializeSecurityContext(string credential, string context, string targetName, Interop.SspiCli.ContextFlags inFlags) =>
+ WriteEvent(InitializeSecurityContextId, credential, context, targetName, (int)inFlags);
+
+ [Event(AcceptSecuritContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void AcceptSecurityContext(SafeFreeCredentials credential, SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags)
+ {
+ if (IsEnabled())
+ {
+ AcceptSecurityContext(IdOf(credential), IdOf(context), inFlags);
+ }
+ }
+ [Event(AcceptSecuritContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void AcceptSecurityContext(string credential, string context, Interop.SspiCli.ContextFlags inFlags) =>
+ WriteEvent(AcceptSecuritContextId, credential, context, (int)inFlags);
+
+ [Event(OperationReturnedSomethingId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void OperationReturnedSomething(string operation, Interop.SECURITY_STATUS errorCode)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(OperationReturnedSomethingId, operation, errorCode);
+ }
+ }
+
+ [Event(SecurityContextInputBufferId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void SecurityContextInputBuffer(string context, int inputBufferSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(SecurityContextInputBufferId, context, inputBufferSize, outputBufferSize, (int)errorCode);
+ }
+ }
+
+ [Event(SecurityContextInputBuffersId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void SecurityContextInputBuffers(string context, int inputBuffersSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(SecurityContextInputBuffersId, context, inputBuffersSize, outputBufferSize, (int)errorCode);
+ }
+ }
+ }
+}
diff --git a/src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs b/src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs
new file mode 100644
index 0000000000..c94d0d4651
--- /dev/null
+++ b/src/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs
@@ -0,0 +1,334 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using System.Globalization;
+using System.Net.Security;
+using System.Security.Authentication;
+using System.Security.Cryptography.X509Certificates;
+
+namespace System.Net
+{
+ //TODO: If localization resources are not found, logging does not work. Issue #5126.
+ [EventSource(Name = "Microsoft-System-Net-Security", LocalizationResources = "FxResources.System.Net.Security.SR")]
+ internal sealed partial class NetEventSource
+ {
+ private const int EnumerateSecurityPackagesId = NextAvailableEventId;
+ private const int SspiPackageNotFoundId = EnumerateSecurityPackagesId + 1;
+ private const int AcquireDefaultCredentialId = SspiPackageNotFoundId + 1;
+ private const int AcquireCredentialsHandleId = AcquireDefaultCredentialId + 1;
+ private const int SecureChannelCtorId = AcquireCredentialsHandleId + 1;
+ private const int LocatingPrivateKeyId = SecureChannelCtorId + 1;
+ private const int CertIsType2Id = LocatingPrivateKeyId + 1;
+ private const int FoundCertInStoreId = CertIsType2Id + 1;
+ private const int NotFoundCertInStoreId = FoundCertInStoreId + 1;
+ private const int InitializeSecurityContextId = NotFoundCertInStoreId + 1;
+ private const int SecurityContextInputBufferId = InitializeSecurityContextId + 1;
+ private const int SecurityContextInputBuffersId = SecurityContextInputBufferId + 1;
+ private const int AcceptSecuritContextId = SecurityContextInputBuffersId + 1;
+ private const int OperationReturnedSomethingId = AcceptSecuritContextId + 1;
+ private const int RemoteCertificateId = OperationReturnedSomethingId + 1;
+ private const int CertificateFromDelegateId = RemoteCertificateId + 1;
+ private const int NoDelegateNoClientCertId = CertificateFromDelegateId + 1;
+ private const int NoDelegateButClientCertId = NoDelegateNoClientCertId + 1;
+ private const int AttemptingRestartUsingCertId = NoDelegateButClientCertId + 1;
+ private const int NoIssuersTryAllCertsId = AttemptingRestartUsingCertId + 1;
+ private const int LookForMatchingCertsId = NoIssuersTryAllCertsId + 1;
+ private const int SelectedCertId = LookForMatchingCertsId + 1;
+ private const int CertsAfterFilteringId = SelectedCertId + 1;
+ private const int FindingMatchingCertsId = CertsAfterFilteringId + 1;
+ private const int UsingCachedCredentialId = FindingMatchingCertsId + 1;
+ private const int SspiSelectedCipherSuitId = UsingCachedCredentialId + 1;
+ private const int RemoteCertificateErrorId = SspiSelectedCipherSuitId + 1;
+ private const int RemoteVertificateValidId = RemoteCertificateErrorId + 1;
+ private const int RemoteCertificateSuccesId = RemoteVertificateValidId + 1;
+ private const int RemoteCertificateInvalidId = RemoteCertificateSuccesId + 1;
+
+ [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void EnumerateSecurityPackages(string securityPackage)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(EnumerateSecurityPackagesId, securityPackage ?? "");
+ }
+ }
+
+ [Event(SspiPackageNotFoundId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void SspiPackageNotFound(string packageName)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(SspiPackageNotFoundId, packageName ?? "");
+ }
+ }
+
+ [NonEvent]
+ public void SecureChannelCtor(SecureChannel secureChannel, string hostname, X509CertificateCollection clientCertificates, EncryptionPolicy encryptionPolicy)
+ {
+ if (IsEnabled())
+ {
+ SecureChannelCtor(hostname, GetHashCode(secureChannel), clientCertificates?.Count ?? 0, encryptionPolicy);
+ }
+ }
+ [Event(SecureChannelCtorId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private unsafe void SecureChannelCtor(string hostname, int secureChannelHash, int clientCertificatesCount, EncryptionPolicy encryptionPolicy) =>
+ WriteEvent(SecureChannelCtorId, hostname, secureChannelHash, clientCertificatesCount, (int)encryptionPolicy);
+
+ [NonEvent]
+ public void LocatingPrivateKey(X509Certificate x509Certificate, SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ LocatingPrivateKey(x509Certificate.ToString(true), GetHashCode(secureChannel));
+ }
+ }
+ [Event(LocatingPrivateKeyId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void LocatingPrivateKey(string x509Certificate, int secureChannelHash) =>
+ WriteEvent(LocatingPrivateKeyId, x509Certificate, secureChannelHash);
+
+ [NonEvent]
+ public void CertIsType2(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ CertIsType2(GetHashCode(secureChannel));
+ }
+ }
+ [Event(CertIsType2Id, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void CertIsType2(int secureChannelHash) =>
+ WriteEvent(CertIsType2Id, secureChannelHash);
+
+ [NonEvent]
+ public void FoundCertInStore(bool serverMode, SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ FoundCertInStore(serverMode ? "LocalMachine" : "CurrentUser", GetHashCode(secureChannel));
+ }
+ }
+ [Event(FoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void FoundCertInStore(string store, int secureChannelHash) =>
+ WriteEvent(FoundCertInStoreId, store, secureChannelHash);
+
+ [NonEvent]
+ public void NotFoundCertInStore(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ NotFoundCertInStore(GetHashCode(secureChannel));
+ }
+ }
+ [Event(NotFoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void NotFoundCertInStore(int secureChannelHash) =>
+ WriteEvent(NotFoundCertInStoreId, secureChannelHash);
+
+ [NonEvent]
+ public void RemoteCertificate(X509Certificate remoteCertificate)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(RemoteCertificateId, remoteCertificate?.ToString(true));
+ }
+ }
+ [Event(RemoteCertificateId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void RemoteCertificate(string remoteCertificate) =>
+ WriteEvent(RemoteCertificateId, remoteCertificate);
+
+ [NonEvent]
+ public void CertificateFromDelegate(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ CertificateFromDelegate(GetHashCode(secureChannel));
+ }
+ }
+ [Event(CertificateFromDelegateId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void CertificateFromDelegate(int secureChannelHash) =>
+ WriteEvent(CertificateFromDelegateId, secureChannelHash);
+
+ [NonEvent]
+ public void NoDelegateNoClientCert(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ NoDelegateNoClientCert(GetHashCode(secureChannel));
+ }
+ }
+ [Event(NoDelegateNoClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void NoDelegateNoClientCert(int secureChannelHash) =>
+ WriteEvent(NoDelegateNoClientCertId, secureChannelHash);
+
+ [NonEvent]
+ public void NoDelegateButClientCert(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ NoDelegateButClientCert(GetHashCode(secureChannel));
+ }
+ }
+ [Event(NoDelegateButClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void NoDelegateButClientCert(int secureChannelHash) =>
+ WriteEvent(NoDelegateButClientCertId, secureChannelHash);
+
+ [Event(AttemptingRestartUsingCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public void AttemptingRestartUsingCert(X509Certificate clientCertificate, SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ AttemptingRestartUsingCert(clientCertificate?.ToString(true), GetHashCode(secureChannel));
+ }
+ }
+ [Event(AttemptingRestartUsingCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void AttemptingRestartUsingCert(string clientCertificate, int secureChannelHash) =>
+ WriteEvent(AttemptingRestartUsingCertId, clientCertificate, secureChannelHash);
+
+ [NonEvent]
+ public void NoIssuersTryAllCerts(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ NoIssuersTryAllCerts(GetHashCode(secureChannel));
+ }
+ }
+ [Event(NoIssuersTryAllCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void NoIssuersTryAllCerts(int secureChannelHash) =>
+ WriteEvent(NoIssuersTryAllCertsId, secureChannelHash);
+
+ [NonEvent]
+ public void LookForMatchingCerts(int issuersCount, SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ LookForMatchingCerts(issuersCount, GetHashCode(secureChannel));
+ }
+ }
+ [Event(LookForMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void LookForMatchingCerts(int issuersCount, int secureChannelHash) =>
+ WriteEvent(LookForMatchingCertsId, issuersCount, secureChannelHash);
+
+ [NonEvent]
+ public void SelectedCert(X509Certificate clientCertificate, SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ SelectedCert(clientCertificate?.ToString(true), GetHashCode(secureChannel));
+ }
+ }
+ [Event(SelectedCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void SelectedCert(string clientCertificate, int secureChannelHash) =>
+ WriteEvent(SelectedCertId, clientCertificate, secureChannelHash);
+
+ [NonEvent]
+ public void CertsAfterFiltering(int filteredCertsCount, SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ CertsAfterFiltering(filteredCertsCount, GetHashCode(secureChannel));
+ }
+ }
+ [Event(CertsAfterFilteringId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void CertsAfterFiltering(int filteredCertsCount, int secureChannelHash) =>
+ WriteEvent(CertsAfterFilteringId, filteredCertsCount, secureChannelHash);
+
+ [NonEvent]
+ public void FindingMatchingCerts(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ FindingMatchingCerts(GetHashCode(secureChannel));
+ }
+ }
+ [Event(FindingMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void FindingMatchingCerts(int secureChannelHash) =>
+ WriteEvent(FindingMatchingCertsId, secureChannelHash);
+
+ [NonEvent]
+ public void UsingCachedCredential(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(UsingCachedCredentialId, GetHashCode(secureChannel));
+ }
+ }
+ [Event(UsingCachedCredentialId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void UsingCachedCredential(int secureChannelHash) =>
+ WriteEvent(UsingCachedCredentialId, secureChannelHash);
+
+ [Event(SspiSelectedCipherSuitId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ public unsafe void SspiSelectedCipherSuite(
+ string process,
+ SslProtocols sslProtocol,
+ CipherAlgorithmType cipherAlgorithm,
+ int cipherStrength,
+ HashAlgorithmType hashAlgorithm,
+ int hashStrength,
+ ExchangeAlgorithmType keyExchangeAlgorithm,
+ int keyExchangeStrength)
+ {
+ if (IsEnabled())
+ {
+ WriteEvent(SspiSelectedCipherSuitId,
+ process, (int)sslProtocol, (int)cipherAlgorithm, cipherStrength,
+ (int)hashAlgorithm, hashStrength, (int)keyExchangeAlgorithm, keyExchangeStrength);
+ }
+ }
+
+ [NonEvent]
+ public void RemoteCertificateError(SecureChannel secureChannel, string message)
+ {
+ if (IsEnabled())
+ {
+ RemoteCertificateError(GetHashCode(secureChannel), message);
+ }
+ }
+ [Event(RemoteCertificateErrorId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
+ private void RemoteCertificateError(int secureChannelHash, string message) =>
+ WriteEvent(RemoteCertificateErrorId, secureChannelHash, message);
+
+ [NonEvent]
+ public void RemoteCertDeclaredValid(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ RemoteCertDeclaredValid(GetHashCode(secureChannel));
+ }
+ }
+ [Event(RemoteVertificateValidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
+ private void RemoteCertDeclaredValid(int secureChannelHash) =>
+ WriteEvent(RemoteVertificateValidId, secureChannelHash);
+
+ [NonEvent]
+ public void RemoteCertHasNoErrors(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ RemoteCertHasNoErrors(GetHashCode(secureChannel));
+ }
+ }
+ [Event(RemoteCertificateSuccesId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
+ private void RemoteCertHasNoErrors(int secureChannelHash) =>
+ WriteEvent(RemoteCertificateSuccesId, secureChannelHash);
+
+ [NonEvent]
+ public void RemoteCertUserDeclaredInvalid(SecureChannel secureChannel)
+ {
+ if (IsEnabled())
+ {
+ RemoteCertUserDeclaredInvalid(GetHashCode(secureChannel));
+ }
+ }
+ [Event(RemoteCertificateInvalidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
+ private void RemoteCertUserDeclaredInvalid(int secureChannelHash) =>
+ WriteEvent(RemoteCertificateInvalidId, secureChannelHash);
+
+ static partial void AdditionalCustomizedToString<T>(T value, ref string result)
+ {
+ X509Certificate cert = value as X509Certificate;
+ if (cert != null)
+ {
+ result = cert.ToString(fVerbose: true);
+ }
+ }
+ }
+}
diff --git a/src/System.Net.Security/src/System/Net/Security/SSPIHandleCache.cs b/src/System.Net.Security/src/System/Net/Security/SSPIHandleCache.cs
index c11947c1e1..69a4376d4c 100644
--- a/src/System.Net.Security/src/System/Net/Security/SSPIHandleCache.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SSPIHandleCache.cs
@@ -27,7 +27,7 @@ namespace System.Net.Security
{
return;
}
-
+
unchecked
{
int index = Interlocked.Increment(ref s_current) & c_MaxCacheSize;
@@ -43,12 +43,7 @@ namespace System.Net.Security
{
if (!ExceptionCheck.IsFatal(e))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SSPIHandlCache", "Attempted to throw: " + e.ToString());
- }
-
- Debug.Fail("SSPIHandlCache", "Attempted to throw: " + e.ToString());
+ NetEventSource.Fail(null, "Attempted to throw: {e}");
}
}
}
diff --git a/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs b/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs
index 1122c2645a..6e95e69463 100644
--- a/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs
@@ -50,14 +50,8 @@ namespace System.Net.Security
internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName,
bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
- }
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.SecureChannelCtor(this, hostname, clientCertificates, encryptionPolicy);
- }
+ NetEventSource.Enter(this, hostname, clientCertificates);
+ if (NetEventSource.IsEnabled) NetEventSource.Log.SecureChannelCtor(this, hostname, clientCertificates, encryptionPolicy);
SslStreamPal.VerifyPackageInfo();
@@ -65,12 +59,7 @@ namespace System.Net.Security
if (hostname == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("SecureChannel#{0}::.ctor()|hostname == null", LoggingHash.HashString(this));
- }
-
- Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor()|hostname == null");
+ NetEventSource.Fail(this, "hostname == null");
}
_hostName = hostname;
_serverMode = serverMode;
@@ -87,10 +76,7 @@ namespace System.Net.Security
_refreshCredentialNeeded = true;
_encryptionPolicy = encryptionPolicy;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor");
- }
+ NetEventSource.Exit(this);
}
//
@@ -128,10 +114,7 @@ namespace System.Net.Security
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::GetChannelBindingToken", kind.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, kind);
ChannelBinding result = null;
if (_securityContext != null)
@@ -139,10 +122,7 @@ namespace System.Net.Security
result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::GetChannelBindingToken", LoggingHash.HashString(result));
- }
+ NetEventSource.Exit(this, result);
return result;
}
@@ -239,10 +219,7 @@ namespace System.Net.Security
return null;
}
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.LocatingPrivateKey(certificate.ToString(true), LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.LocatingPrivateKey(certificate, this);
try
{
@@ -257,10 +234,7 @@ namespace System.Net.Security
{
if (certEx.HasPrivateKey)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.CertIsType2(LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.CertIsType2(this);
return certEx;
}
@@ -281,11 +255,7 @@ namespace System.Net.Security
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this));
- }
-
+ NetEventSource.Log.FoundCertInStore(_serverMode, this);
return collectionEx[0];
}
}
@@ -296,11 +266,7 @@ namespace System.Net.Security
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this));
- }
-
+ NetEventSource.Log.FoundCertInStore(_serverMode, this);
return collectionEx[0];
}
}
@@ -309,11 +275,7 @@ namespace System.Net.Security
{
}
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.NotFoundCertInStore(LoggingHash.HashInt(this));
- }
-
+ NetEventSource.Log.NotFoundCertInStore(this);
return null;
}
@@ -394,10 +356,7 @@ namespace System.Net.Security
private bool AcquireClientCredentials(ref byte[] thumbPrint)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials");
- }
+ NetEventSource.Enter(this);
// Acquire possible Client Certificate information and set it on the handle.
X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
@@ -410,10 +369,7 @@ namespace System.Net.Security
{
issuers = GetRequestCertificateAuthorities();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() calling CertificateSelectionCallback");
- }
+ NetEventSource.Info(this, "Calling CertificateSelectionCallback");
X509Certificate2 remoteCert = null;
try
@@ -439,28 +395,19 @@ namespace System.Net.Security
}
filteredCerts.Add(clientCertificate);
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.CertificateFromDelegate(LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.CertificateFromDelegate(this);
}
else
{
if (ClientCertificates.Count == 0)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.NoDelegateNoClientCert(LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.NoDelegateNoClientCert(this);
sessionRestartAttempt = true;
}
else
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.NoDelegateButClientCert(LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.NoDelegateButClientCert(this);
}
}
}
@@ -475,10 +422,7 @@ namespace System.Net.Security
filteredCerts.Add(clientCertificate);
}
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.AttemptingRestartUsingCert(clientCertificate == null ? "null" : clientCertificate.ToString(true), LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this);
}
else if (_clientCertificates != null && _clientCertificates.Count > 0)
{
@@ -487,15 +431,15 @@ namespace System.Net.Security
//
issuers = GetRequestCertificateAuthorities();
- if (SecurityEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
if (issuers == null || issuers.Length == 0)
{
- SecurityEventSource.Log.NoIssuersTryAllCerts(LoggingHash.HashInt(this));
+ NetEventSource.Log.NoIssuersTryAllCerts(this);
}
else
{
- SecurityEventSource.Log.LookForMatchingCerts(issuers.Length, LoggingHash.HashInt(this));
+ NetEventSource.Log.LookForMatchingCerts(issuers.Length, this);
}
}
@@ -517,10 +461,7 @@ namespace System.Net.Security
continue;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() root cert:" + certificateEx.Issuer);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Root cert: {certificateEx}");
chain = new X509Chain();
@@ -540,16 +481,10 @@ namespace System.Net.Security
found = Array.IndexOf(issuers, issuer) != -1;
if (found)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() matched:" + issuer);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Matched {issuer}");
break;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() no match:" + issuer);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"No match: {issuer}");
}
}
@@ -572,10 +507,7 @@ namespace System.Net.Security
}
}
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.SelectedCert(_clientCertificates[i].ToString(true), LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.SelectedCert(_clientCertificates[i], this);
filteredCerts.Add(_clientCertificates[i]);
}
@@ -586,12 +518,12 @@ namespace System.Net.Security
clientCertificate = null;
- if (SecurityEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
- SecurityEventSource.Log.CertsAfterFiltering(filteredCerts.Count, LoggingHash.HashInt(this));
+ NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this);
if (filteredCerts.Count != 0)
{
- SecurityEventSource.Log.FindingMatchingCerts(LoggingHash.HashInt(this));
+ NetEventSource.Log.FindingMatchingCerts(this);
}
}
@@ -616,18 +548,10 @@ namespace System.Net.Security
if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'.");
- }
-
- Debug.Fail("AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'.");
+ NetEventSource.Fail(this, "'selectedCert' does not match 'clientCertificate'.");
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() Selected Cert = " + (selectedCert == null ? "null" : selectedCert.Subject));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Selected cert = {selectedCert}");
try
{
@@ -646,10 +570,7 @@ namespace System.Net.Security
selectedCert != null &&
SslStreamPal.StartMutualAuthAsAnonymous)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() Reset to anonymous session.");
- }
+ NetEventSource.Info(this, "Reset to anonymous session.");
// IIS does not renegotiate a restarted session if client cert is needed.
// So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
@@ -667,10 +588,7 @@ namespace System.Net.Security
if (cachedCredentialHandle != null)
{
- if (SecurityEventSource.Log.IsEnabled())
- {
- SecurityEventSource.Log.UsingCachedCredential(LoggingHash.HashInt(this));
- }
+ NetEventSource.Log.UsingCachedCredential(this);
_credentialsHandle = cachedCredentialHandle;
_selectedClientCertificate = clientCertificate;
@@ -693,10 +611,7 @@ namespace System.Net.Security
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials, cachedCreds = " + cachedCred.ToString(), LoggingHash.ObjectToString(_credentialsHandle));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
@@ -706,10 +621,7 @@ namespace System.Net.Security
//
private bool AcquireServerCredentials(ref byte[] thumbPrint)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials");
- }
+ NetEventSource.Enter(this);
X509Certificate localCertificate = null;
bool cachedCred = false;
@@ -719,10 +631,7 @@ namespace System.Net.Security
X509CertificateCollection tempCollection = new X509CertificateCollection();
tempCollection.Add(_serverCertificate);
localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>());
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert");
- }
+ NetEventSource.Info(this, "Use delegate selected Cert");
}
else
{
@@ -746,12 +655,7 @@ namespace System.Net.Security
if (!localCertificate.Equals(selectedCert))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");
- }
-
- Debug.Fail("AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");
+ NetEventSource.Fail(this, "'selectedCert' does not match 'localCertificate'.");
}
//
@@ -784,40 +688,28 @@ namespace System.Net.Security
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), LoggingHash.ObjectToString(_credentialsHandle));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
//
internal ProtocolToken NextMessage(byte[] incoming, int offset, int count)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage");
- }
+ NetEventSource.Enter(this);
byte[] nextmsg = null;
SecurityStatusPal status = GenerateToken(incoming, offset, count, ref nextmsg);
if (!_serverMode && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage() returned SecurityStatusPal.CredentialsNeeded");
- }
+ NetEventSource.Info(this, "NextMessage() returned SecurityStatusPal.CredentialsNeeded");
SetRefreshCredentialNeeded();
status = GenerateToken(incoming, offset, count, ref nextmsg);
}
ProtocolToken token = new ProtocolToken(nextmsg, status);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage", token.ToString());
- }
+ NetEventSource.Exit(this, token);
return token;
}
@@ -839,31 +731,18 @@ namespace System.Net.Security
private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output)
{
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken, _refreshCredentialNeeded = " + _refreshCredentialNeeded);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}");
#endif
if (offset < 0 || offset > (input == null ? 0 : input.Length))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'offset' out of range.");
- }
-
- Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'offset' out of range.");
+ NetEventSource.Fail(this, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (input == null ? 0 : input.Length - offset))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'count' out of range.");
- }
-
- Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'count' out of range.");
+ NetEventSource.Fail(this, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
@@ -962,13 +841,7 @@ namespace System.Net.Security
}
output = outgoingSecurity.token;
-
-#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken()", Interop.MapSecurityStatus((uint)errorCode));
- }
-#endif
+
return status;
}
@@ -981,10 +854,7 @@ namespace System.Net.Security
--*/
internal void ProcessHandshakeSuccess()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess");
- }
+ NetEventSource.Enter(this);
StreamSizes streamSizes;
SslStreamPal.QueryContextStreamSizes(_securityContext, out streamSizes);
@@ -997,28 +867,16 @@ namespace System.Net.Security
_trailerSize = streamSizes.Trailer;
_maxDataSize = checked(streamSizes.MaximumMessage - (_headerSize + _trailerSize));
}
- catch (Exception e)
+ catch (Exception e) when (!ExceptionCheck.IsFatal(e))
{
- if (!ExceptionCheck.IsFatal(e))
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess", "StreamSizes out of range.");
- }
-
- Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess", "StreamSizes out of range.");
- }
-
+ NetEventSource.Fail(this, "StreamSizes out of range.");
throw;
}
}
SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess");
- }
+ NetEventSource.Exit(this);
}
/*++
@@ -1035,12 +893,10 @@ namespace System.Net.Security
--*/
internal SecurityStatusPal Encrypt(byte[] buffer, int offset, int size, ref byte[] output, out int resultSize)
{
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt");
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt() - offset: " + offset.ToString() + " size: " + size.ToString() + " buffersize: " + buffer.Length.ToString());
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt() buffer:");
- GlobalLog.Dump(buffer, Math.Min(buffer.Length, 128));
+ NetEventSource.Enter(this, buffer, offset, size);
+ NetEventSource.DumpArray(this, buffer, 0, Math.Min(buffer.Length, 128));
}
byte[] writeBuffer = output;
@@ -1059,18 +915,9 @@ namespace System.Net.Security
resultSize = 0;
}
- catch (Exception e)
+ catch (Exception e) when (!ExceptionCheck.IsFatal(e))
{
- if (!ExceptionCheck.IsFatal(e))
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range.");
- }
-
- Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range.");
- }
-
+ NetEventSource.Fail(this, "Arguments out of range.");
throw;
}
@@ -1086,18 +933,12 @@ namespace System.Net.Security
if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt ERROR", secStatus.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"ERROR {secStatus}");
}
else
{
output = writeBuffer;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt OK", "data size:" + resultSize.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"OK data size:{resultSize}");
}
return secStatus;
@@ -1105,30 +946,17 @@ namespace System.Net.Security
internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Decrypt() - offset: " + offset.ToString() + " size: " + count.ToString() + " buffersize: " + payload.Length.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, payload, offset, count);
if (offset < 0 || offset > (payload == null ? 0 : payload.Length))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'offset' out of range.");
- }
-
- Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'offset' out of range.");
+ NetEventSource.Fail(this, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (payload == null ? 0 : payload.Length - offset))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'count' out of range.");
- }
-
- Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'count' out of range.");
+ NetEventSource.Fail(this, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
@@ -1150,10 +978,7 @@ namespace System.Net.Security
//
internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback, ref ProtocolToken alertToken)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate");
- }
+ NetEventSource.Enter(this);
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
@@ -1170,10 +995,7 @@ namespace System.Net.Security
if (remoteCertificateEx == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate (no remote cert)", (!_remoteCertRequired).ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, "(no remote cert)", !_remoteCertRequired);
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
}
else
@@ -1210,14 +1032,10 @@ namespace System.Net.Security
}
}
- if (SecurityEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain);
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Cert Validation, remote cert = " + (remoteCertificateEx == null ? "<null>" : remoteCertificateEx.ToString(true)));
+ NetEventSource.Info(this, $"Cert validation, remote cert = {remoteCertificateEx}");
}
if (!success)
@@ -1240,20 +1058,14 @@ namespace System.Net.Security
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate", success.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, success);
return success;
}
public ProtocolToken CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::CreateFatalHandshakeAlertToken");
- }
+ NetEventSource.Enter(this);
TlsAlertMessage alertMessage;
@@ -1271,20 +1083,14 @@ namespace System.Net.Security
break;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::CreateFatalHandshakeAlertToken() alertMessage: " + alertMessage.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"alertMessage:{alertMessage}");
SecurityStatusPal status;
status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::ApplyAlertToken() returned " + status.ErrorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}");
if (status.Exception != null)
{
@@ -1295,31 +1101,20 @@ namespace System.Net.Security
}
ProtocolToken token = GenerateAlertToken();
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::CreateFatalHandshakeAlertToken", token.ToString());
- }
-
+ NetEventSource.Exit(this, token);
return token;
}
public ProtocolToken CreateShutdownToken()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::CreateShutdownToken");
- }
+ NetEventSource.Enter(this);
SecurityStatusPal status;
status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::ApplyAlertToken() returned " + status.ErrorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}");
if (status.Exception != null)
{
@@ -1330,12 +1125,7 @@ namespace System.Net.Security
}
ProtocolToken token = GenerateAlertToken();
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::CreateShutdownToken", token.ToString());
- }
-
+ NetEventSource.Exit(this, token);
return token;
}
@@ -1405,15 +1195,15 @@ namespace System.Net.Security
{
if (sslPolicyErrors != SslPolicyErrors.None)
{
- SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_has_errors);
+ NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_has_errors);
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
{
- SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_not_available);
+ NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_not_available);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
- SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_name_mismatch);
+ NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_name_mismatch);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
@@ -1423,7 +1213,7 @@ namespace System.Net.Security
{
chainStatusString += "\t" + chainStatus.StatusInformation;
}
- SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), chainStatusString);
+ NetEventSource.Log.RemoteCertificateError(this, chainStatusString);
}
}
@@ -1431,18 +1221,18 @@ namespace System.Net.Security
{
if (remoteCertValidationCallback != null)
{
- SecurityEventSource.Log.RemoteCertDeclaredValid(LoggingHash.HashInt(this));
+ NetEventSource.Log.RemoteCertDeclaredValid(this);
}
else
{
- SecurityEventSource.Log.RemoteCertHasNoErrors(LoggingHash.HashInt(this));
+ NetEventSource.Log.RemoteCertHasNoErrors(this);
}
}
else
{
if (remoteCertValidationCallback != null)
{
- SecurityEventSource.Log.RemoteCertUserDeclaredInvalid(LoggingHash.HashInt(this));
+ NetEventSource.Log.RemoteCertUserDeclaredInvalid(this);
}
}
}
diff --git a/src/System.Net.Security/src/System/Net/Security/SecurityBuffer.cs b/src/System.Net.Security/src/System/Net/Security/SecurityBuffer.cs
index bfb185a9b6..6980b991c0 100644
--- a/src/System.Net.Security/src/System/Net/Security/SecurityBuffer.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SecurityBuffer.cs
@@ -20,22 +20,12 @@ namespace System.Net.Security
{
if (offset < 0 || offset > (data == null ? 0 : data.Length))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecurityBuffer::.ctor", "'offset' out of range. [" + offset + "]");
- }
-
- Debug.Fail("SecurityBuffer::.ctor", "'offset' out of range. [" + offset + "]");
+ if (NetEventSource.IsEnabled) NetEventSource.Fail(this, $"'offset' out of range. [{offset}]");
}
if (size < 0 || size > (data == null ? 0 : data.Length - offset))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecurityBuffer::.ctor", "'size' out of range. [" + size + "]");
- }
-
- Debug.Fail("SecurityBuffer::.ctor", "'size' out of range. [" + size + "]");
+ if (NetEventSource.IsEnabled) NetEventSource.Fail(this, $"'size' out of range. [{size}]");
}
this.offset = data == null || offset < 0 ? 0 : Math.Min(offset, data.Length);
@@ -55,12 +45,7 @@ namespace System.Net.Security
{
if (size < 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SecurityBuffer::.ctor", "'size' out of range. [" + size + "]");
- }
-
- Debug.Fail("SecurityBuffer::.ctor", "'size' out of range. [" + size + "]");
+ if (NetEventSource.IsEnabled) NetEventSource.Fail(this, $"'size' out of range. [{size}]");
}
this.size = size;
diff --git a/src/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs b/src/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs
index 959f426f2b..f010c8f5bf 100644
--- a/src/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs
@@ -118,10 +118,7 @@ namespace System.Net.Security
{
if (s_cachedCreds.Count == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TryCachedCredential() Not found, Current Cache Count = " + s_cachedCreds.Count);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Not found, Current Cache Count = {s_cachedCreds.Count}");
return null;
}
@@ -130,17 +127,11 @@ namespace System.Net.Security
SafeCredentialReference cached;
if (!s_cachedCreds.TryGetValue(key, out cached) || cached.IsClosed || cached.Target.IsInvalid)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TryCachedCredential() Not found or invalid, Current Cache Count = " + s_cachedCreds.Count);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Not found or invalid, Current Cache Coun = {s_cachedCreds.Count}");
return null;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TryCachedCredential() Found a cached Handle = " + cached.Target.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Found a cached Handle = {cached.Target}");
return cached.Target;
}
@@ -154,21 +145,12 @@ namespace System.Net.Security
{
if (creds == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("CacheCredential|creds == null");
- }
-
- Debug.Fail("CacheCredential|creds == null");
+ NetEventSource.Fail(null, "creds == null");
}
if (creds.IsInvalid)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CacheCredential() Refused to cache an Invalid Handle = " + creds.ToString() + ", Current Cache Count = " + s_cachedCreds.Count);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Refused to cache an Invalid Handle {creds}, Current Cache Count = {s_cachedCreds.Count}");
return;
}
@@ -191,10 +173,7 @@ namespace System.Net.Security
}
s_cachedCreds[key] = cached;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("CacheCredential() Caching New Handle = " + creds.ToString() + ", Current Cache Count = " + s_cachedCreds.Count);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Caching New Handle = {creds}, Current Cache Count = {s_cachedCreds.Count}");
//
// A simplest way of preventing infinite cache grows.
@@ -229,21 +208,18 @@ namespace System.Net.Security
}
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Scavenged cache, New Cache Count = " + s_cachedCreds.Count);
- }
+ NetEventSource.Info(null, $"Scavenged cache, New Cache Count = {s_cachedCreds.Count}");
}
}
- else if (GlobalLog.IsEnabled)
+ else if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("CacheCredential() (locked retry) Found already cached Handle = " + cached.Target.ToString());
+ NetEventSource.Info(null, $"CacheCredential() (locked retry) Found already cached Handle = {cached.Target}");
}
}
}
- else if (GlobalLog.IsEnabled)
+ else if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("CacheCredential() Ignoring incoming handle = " + creds.ToString() + " since found already cached Handle = " + cached.Target.ToString());
+ NetEventSource.Info(null, $"CacheCredential() Ignoring incoming handle = {creds} since found already cached Handle = {cached.Target}");
}
}
}
diff --git a/src/System.Net.Security/src/System/Net/Security/SslState.cs b/src/System.Net.Security/src/System/Net/Security/SslState.cs
index 5425a0b194..b735feb9e8 100644
--- a/src/System.Net.Security/src/System/Net/Security/SslState.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SslState.cs
@@ -593,9 +593,9 @@ namespace System.Net.Security
ForceAuthentication(Context.IsServer, null, asyncRequest);
// Not aync so the connection is completed at this point.
- if (lazyResult == null && SecurityEventSource.Log.IsEnabled())
+ if (lazyResult == null && NetEventSource.IsEnabled)
{
- SecurityEventSource.Log.SspiSelectedCipherSuite("ProcessAuthentication",
+ NetEventSource.Log.SspiSelectedCipherSuite(nameof(ProcessAuthentication),
SslProtocol,
CipherAlgorithm,
CipherStrength,
@@ -727,9 +727,9 @@ namespace System.Net.Security
InternalEndProcessAuthentication(lazyResult);
// Connection is completed at this point.
- if (SecurityEventSource.Log.IsEnabled())
+ if (NetEventSource.IsEnabled)
{
- SecurityEventSource.Log.SspiSelectedCipherSuite("EndProcessAuthentication",
+ NetEventSource.Log.SspiSelectedCipherSuite(nameof(EndProcessAuthentication),
SslProtocol,
CipherAlgorithm,
CipherStrength,
@@ -1016,10 +1016,7 @@ namespace System.Net.Security
//
private bool CompleteHandshake(ref ProtocolToken alertToken)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("CompleteHandshake");
- }
+ NetEventSource.Enter(this);
Context.ProcessHandshakeSuccess();
@@ -1028,22 +1025,14 @@ namespace System.Net.Security
_handshakeCompleted = false;
_certValidationFailed = true;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("CompleteHandshake", false);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, false);
return false;
}
_certValidationFailed = false;
_handshakeCompleted = true;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("CompleteHandshake", true);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, true);
return true;
}
@@ -1065,18 +1054,9 @@ namespace System.Net.Security
sslState = (SslState)asyncRequest.AsyncObject;
#if DEBUG
}
- catch (Exception exception)
+ catch (Exception exception) when (!ExceptionCheck.IsFatal(exception))
{
- if (!ExceptionCheck.IsFatal(exception))
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslState::WriteCallback", "Exception while decoding context. type:" + exception.GetType().ToString() + " message:" + exception.Message);
- }
-
- Debug.Fail("SslState::WriteCallback", "Exception while decoding context. type:" + exception.GetType().ToString() + " message:" + exception.Message);
- }
-
+ NetEventSource.Fail(null, $"Exception while decoding context: {exception}");
throw;
}
#endif
@@ -1110,10 +1090,7 @@ namespace System.Net.Security
private static void PartialFrameCallback(AsyncProtocolRequest asyncRequest)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SslState::PartialFrameCallback()");
- }
+ NetEventSource.Enter(null);
// Async ONLY completion.
SslState sslState = (SslState)asyncRequest.AsyncObject;
@@ -1137,10 +1114,7 @@ namespace System.Net.Security
//
private static void ReadFrameCallback(AsyncProtocolRequest asyncRequest)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SslState::ReadFrameCallback()");
- }
+ NetEventSource.Enter(null);
// Async ONLY completion.
SslState sslState = (SslState)asyncRequest.AsyncObject;
@@ -1595,12 +1569,7 @@ namespace System.Net.Security
if ((bytes == null || bytes.Length <= 0))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslState::DetectFraming()|Header buffer is not allocated.");
- }
-
- Debug.Fail("SslState::DetectFraming()|Header buffer is not allocated.");
+ NetEventSource.Fail(this, "Header buffer is not allocated.");
}
// If the first byte is SSL3 HandShake, then check if we have a SSLv3 Type3 client hello.
@@ -1613,12 +1582,9 @@ namespace System.Net.Security
}
#if TRACE_VERBOSE
- if (bytes[1] != 3)
+ if (bytes[1] != 3 && NetEventSource.IsEnabled)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WARNING: SslState::DetectFraming() SSL protocol is > 3, trying SSL3 framing in retail = " + bytes[1].ToString("x", NumberFormatInfo.InvariantInfo));
- }
+ NetEventSource.Info(this, $"WARNING: SslState::DetectFraming() SSL protocol is > 3, trying SSL3 framing in retail = {bytes[i]:x}");
}
#endif
@@ -1635,10 +1601,10 @@ namespace System.Net.Security
}
#if TRACE_VERBOSE
- if ((bytes[0] & 0x80) == 0 && GlobalLog.IsEnabled)
+ if ((bytes[0] & 0x80) == 0 && NetEventSource.IsEnabled)
{
// We have a three-byte header format
- GlobalLog.Print("WARNING: SslState::DetectFraming() SSL v <=2 HELLO has no high bit set for 3 bytes header, we are broken, received byte = " + bytes[0].ToString("x", NumberFormatInfo.InvariantInfo));
+ NetEventSource.Info(this, $"WARNING: SslState::DetectFraming() SSL v <=2 HELLO has no high bit set for 3 bytes header, we are broken, received byte = {bytes[0]:x}");
}
#endif
@@ -1701,10 +1667,7 @@ namespace System.Net.Security
// This is called from SslStream class too.
internal int GetRemainingFrameSize(byte[] buffer, int dataSize)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("GetRemainingFrameSize", "dataSize = " + dataSize);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, buffer, dataSize);
int payloadSize = -1;
switch (_Framing)
@@ -1744,10 +1707,7 @@ namespace System.Net.Security
break;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("GetRemainingFrameSize", payloadSize);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, payloadSize);
return payloadSize;
}
@@ -1821,22 +1781,12 @@ namespace System.Net.Security
LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)result;
if (lazyAsyncResult == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslState::RehandshakeCompleteCallback()|result is null!");
- }
-
- Debug.Fail("SslState::RehandshakeCompleteCallback()|result is null!");
+ NetEventSource.Fail(this, "result is null!");
}
if (!lazyAsyncResult.InternalPeekCompleted)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslState::RehandshakeCompleteCallback()|result is not completed!");
- }
-
- Debug.Fail("SslState::RehandshakeCompleteCallback()|result is not completed!");
+ NetEventSource.Fail(this, "result is not completed!");
}
// If the rehandshake succeeded, FinishHandshake has already been called; if there was a SocketException
diff --git a/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs b/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs
index f3b229441d..118e5706b6 100644
--- a/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs
@@ -532,12 +532,7 @@ namespace System.Net.Security
if (InternalBufferCount != 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:{0}", InternalBufferCount);
- }
-
- Debug.Fail("SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:" + InternalBufferCount);
+ NetEventSource.Fail(this, $"Previous frame was not consumed. InternalBufferCount: {InternalBufferCount}");
}
do
@@ -715,11 +710,7 @@ namespace System.Net.Security
private int ProcessReadErrorCode(SecurityStatusPal status, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest, byte[] extraBuffer)
{
ProtocolToken message = new ProtocolToken(null, status);
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::***Processing an error Status = " + message.Status.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"***Processing an error Status = {message.Status}");
if (message.Renegotiate)
{
@@ -752,12 +743,7 @@ namespace System.Net.Security
if (!(transportResult.AsyncState is AsyncProtocolRequest))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslStream::WriteCallback | State type is wrong, expected AsyncProtocolRequest.");
- }
-
- Debug.Fail("SslStream::WriteCallback|State type is wrong, expected AsyncProtocolRequest.");
+ NetEventSource.Fail(transportResult, "State type is wrong, expected AsyncProtocolRequest.");
}
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
diff --git a/src/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs b/src/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs
index 598a88b170..a11b2e2cbf 100644
--- a/src/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs
@@ -141,11 +141,7 @@ namespace System.Net.Security
}
catch
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslStreamPal.Windows: SecureChannel#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
- }
- Debug.Fail("SslStreamPal.Windows: SecureChannel#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
+ NetEventSource.Fail(securityContext, "Arguments out of range");
throw;
}
if (output == null || output.Length < bufferSizeNeeded)
@@ -186,11 +182,7 @@ namespace System.Net.Security
if (errorCode != 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SslStreamPal.Windows: SecureChannel#" + LoggingHash.HashString(securityContext) + "::Encrypt ERROR" + errorCode.ToString("x"));
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(securityContext, $"Encrypt ERROR {errorCode:X}");
resultSize = 0;
return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
}
diff --git a/src/System.Net.Security/src/System/Net/SslStreamContext.cs b/src/System.Net.Security/src/System/Net/SslStreamContext.cs
index a39c03d8e7..1fa107f62f 100644
--- a/src/System.Net.Security/src/System/Net/SslStreamContext.cs
+++ b/src/System.Net.Security/src/System/Net/SslStreamContext.cs
@@ -14,12 +14,7 @@ namespace System.Net
{
if (sslStream == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SslStreamContext..ctor(): Not expecting a null sslStream!");
- }
-
- Debug.Fail("SslStreamContext..ctor(): Not expecting a null sslStream!");
+ NetEventSource.Fail(this, "Not expecting a null sslStream!");
}
_sslStream = sslStream;
diff --git a/src/System.Net.Security/src/System/Net/StreamFramer.cs b/src/System.Net.Security/src/System/Net/StreamFramer.cs
index 1349e59993..3aac3ef885 100644
--- a/src/System.Net.Security/src/System/Net/StreamFramer.cs
+++ b/src/System.Net.Security/src/System/Net/StreamFramer.cs
@@ -151,12 +151,7 @@ namespace System.Net
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
- }
-
- Debug.Fail("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
+ NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}.");
}
if (transportResult.CompletedSynchronously)
@@ -199,12 +194,7 @@ namespace System.Net
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
- }
-
- Debug.Fail("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
+ NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}.");
}
WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;
@@ -214,12 +204,7 @@ namespace System.Net
if (!(workerResult.Offset <= workerResult.End))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("StreamFramer::ReadFrameCallback|WRONG: offset - end = {0}", workerResult.Offset - workerResult.End);
- }
-
- Debug.Fail("StreamFramer::ReadFrameCallback|WRONG: offset - end = " + (workerResult.Offset - workerResult.End));
+ NetEventSource.Fail(this, $"WRONG: offset - end = {workerResult.Offset - workerResult.End}");
}
if (bytesRead <= 0)
@@ -391,12 +376,7 @@ namespace System.Net
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("StreamFramer::BeginWriteCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.AsyncState.GetType().FullName);
- }
-
- Debug.Fail("StreamFramer::BeginWriteCallback|The state expected to be WorkerAsyncResult, received:" + transportResult.AsyncState.GetType().FullName + ".");
+ NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}.");
}
if (transportResult.CompletedSynchronously)
diff --git a/src/System.Net.Security/tests/FunctionalTests/LoggingTest.cs b/src/System.Net.Security/tests/FunctionalTests/LoggingTest.cs
new file mode 100644
index 0000000000..3dcbd42693
--- /dev/null
+++ b/src/System.Net.Security/tests/FunctionalTests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.Security.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(SslStream).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-Security", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("066c0e27-a02d-5a98-9a4d-078cc3b1a896"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj b/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj
index cc5d252f55..12de0bb7a1 100644
--- a/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj
+++ b/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj
@@ -97,6 +97,9 @@
<Link>Common\System\Threading\Tasks\TaskTimeoutExtensions.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)'==''">
+ <Compile Include="LoggingTest.cs" />
+ </ItemGroup>
<ItemGroup Condition=" '$(TargetsWindows)' == 'true' ">
<Compile Include="IdentityValidator.Windows.cs" />
</ItemGroup>
diff --git a/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj b/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj
index a21804f437..547c9e68c2 100644
--- a/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj
+++ b/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj
@@ -9,6 +9,7 @@
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0D174EA9-9E61-4519-8D31-7BD2331A1982}</ProjectGuid>
<OutputType>Library</OutputType>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath>
<NugetTargetMoniker>.NETStandard,Version=v1.7</NugetTargetMoniker>
<!--
@@ -63,11 +64,8 @@
<Compile Include="$(CommonPath)\System\Net\Shims\TraceSource.cs">
<Link>ProductionCode\Common\System\Net\Shims\TraceSource.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>ProductionCode\Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>ProductionCode\Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>ProductionCode\Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>ProductionCode\Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.Sockets/src/System.Net.Sockets.csproj b/src/System.Net.Sockets/src/System.Net.Sockets.csproj
index 22082c5818..38375c7de9 100644
--- a/src/System.Net.Sockets/src/System.Net.Sockets.csproj
+++ b/src/System.Net.Sockets/src/System.Net.Sockets.csproj
@@ -49,6 +49,7 @@
<Compile Include="System\Net\Sockets\IPProtectionLevel.cs" />
<Compile Include="System\Net\Sockets\LingerOption.cs" />
<Compile Include="System\Net\Sockets\MulticastOption.cs" />
+ <Compile Include="System\Net\Sockets\NetEventSource.Sockets.cs" />
<Compile Include="System\Net\Sockets\NetworkStream.cs" />
<Compile Include="System\Net\Sockets\SelectMode.cs" />
<Compile Include="System\Net\Sockets\SendPacketsElement.cs" />
@@ -82,20 +83,11 @@
<Link>Common\System\IO\StreamHelpers.CopyValidation.cs</Link>
</Compile>
<!-- Logging -->
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\DebugThreadTracking.cs">
+ <Link>Common\System\Net\Logging\DebugThreadTracking.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\SocketsEventSource.cs">
- <Link>Common\System\Net\Logging\SocketsEventSource.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs b/src/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs
index 6ebd5addd4..7e3b9d7d13 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs
@@ -27,10 +27,7 @@ namespace System.Net.Sockets
if (errorCode == SocketError.Success)
{
_localBytesTransferred = numBytes;
- if (SocketsEventSource.Log.IsEnabled())
- {
- LogBuffer((long)numBytes);
- }
+ if (NetEventSource.IsEnabled) LogBuffer(numBytes);
// get the endpoint
remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint);
@@ -68,10 +65,7 @@ namespace System.Net.Sockets
errorCode = (SocketError)Marshal.GetLastWin32Error();
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("AcceptOverlappedAsyncResult#" + LoggingHash.HashString(this) + "::PostCallback() setsockopt handle:" + handle.ToString() + " AcceptSocket:" + LoggingHash.HashString(_acceptSocket) + " itsHandle:" + _acceptSocket.SafeHandle.DangerousGetHandle().ToString() + " returns:" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"setsockopt handle:{handle}, AcceptSocket:{_acceptSocket}, returns:{errorCode}");
}
catch (ObjectDisposedException)
{
@@ -107,25 +101,13 @@ namespace System.Net.Sockets
private void LogBuffer(long size)
{
- if (!SocketsEventSource.Log.IsEnabled())
+ if (size > -1)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("AcceptOverlappedAsyncResult#{0}::LogBuffer()|Logging is off!", LoggingHash.HashString(this));
- }
- Debug.Fail("AcceptOverlappedAsyncResult#" + LoggingHash.HashString(this) + "::LogBuffer()|Logging is off!");
+ NetEventSource.DumpArray(this, _buffer, 0, Math.Min((int)size, _buffer.Length));
}
- IntPtr pinnedBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, 0);
- if (pinnedBuffer != IntPtr.Zero)
+ else
{
- if (size > -1)
- {
- SocketsEventSource.Dump(pinnedBuffer, (int)Math.Min(size, (long)_buffer.Length));
- }
- else
- {
- SocketsEventSource.Dump(pinnedBuffer, (int)_buffer.Length);
- }
+ NetEventSource.DumpArray(this, _buffer);
}
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Unix.cs b/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Unix.cs
index e09e165698..67fda0847a 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Unix.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Unix.cs
@@ -20,12 +20,7 @@ namespace System.Net.Sockets
public BaseOverlappedAsyncResult(Socket socket, Object asyncState, AsyncCallback asyncCallback)
: base(socket, asyncState, asyncCallback)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "BaseOverlappedAsyncResult#" + LoggingHash.HashString(this) +
- "(Socket#" + LoggingHash.HashString(socket) + ")");
- }
+ NetEventSource.Info(this, socket);
}
public void CompletionCallback(int numBytes, SocketError errorCode)
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs b/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs
index 03f3d5f446..81c47caad1 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs
@@ -27,12 +27,7 @@ namespace System.Net.Sockets
: base(socket, asyncState, asyncCallback)
{
_cleanupCount = 1;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "BaseOverlappedAsyncResult#" + LoggingHash.HashString(this) +
- "(Socket#" + LoggingHash.HashString(socket) + ")");
- }
+ NetEventSource.Info(this, socket);
}
internal SafeNativeOverlapped NativeOverlapped
@@ -70,22 +65,15 @@ namespace System.Net.Sockets
{
NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(s_ioCallback, this, objectsToPin);
_nativeOverlapped = new SafeNativeOverlapped(s.SafeHandle, overlapped);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "BaseOverlappedAsyncResult#" + LoggingHash.HashString(this) +
- "::boundHandle#" + LoggingHash.HashString(boundHandle) +
- "::AllocateNativeOverlapped. Return=" +
- _nativeOverlapped.DangerousGetHandle().ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"{boundHandle}::AllocateNativeOverlapped. return={_nativeOverlapped}");
}
}
private unsafe static void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
#if DEBUG
- GlobalLog.SetThreadSource(ThreadKinds.CompletionPort);
- using (GlobalLog.SetThreadKind(ThreadKinds.System))
+ DebugThreadTracking.SetThreadSource(ThreadKinds.CompletionPort);
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.System))
{
#endif
BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
@@ -94,20 +82,9 @@ namespace System.Net.Sockets
if (asyncResult.InternalPeekCompleted)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|asyncResult.IsCompleted", LoggingHash.HashString(asyncResult));
- }
- Debug.Fail("BaseOverlappedAsyncResult#" + LoggingHash.HashString(asyncResult) + "::CompletionPortCallback()|asyncResult.IsCompleted");
- }
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "BaseOverlappedAsyncResult#" + LoggingHash.HashString(asyncResult) + "::CompletionPortCallback" +
- " errorCode:" + errorCode.ToString() +
- " numBytes:" + numBytes.ToString() +
- " pOverlapped:" + ((int)nativeOverlapped).ToString());
+ NetEventSource.Fail(null, $"asyncResult.IsCompleted: {asyncResult}");
}
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"errorCode:{errorCode} numBytes:{numBytes} nativeOverlapped:{(IntPtr)nativeOverlapped}");
// Complete the IO and invoke the user's callback.
SocketError socketError = (SocketError)errorCode;
@@ -147,21 +124,12 @@ namespace System.Net.Sockets
socketError = (SocketError)Marshal.GetLastWin32Error();
if (socketError == 0)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|socketError:0 numBytes:{1}", LoggingHash.HashString(asyncResult), numBytes);
- }
- Debug.Fail("BaseOverlappedAsyncResult#" + LoggingHash.HashString(asyncResult) + "::CompletionPortCallback()|socketError:0 numBytes:" + numBytes);
+ NetEventSource.Fail(asyncResult, $"socketError:0 numBytes:{numBytes}");
}
}
-
if (success)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|Unexpectedly succeeded. errorCode:{1} numBytes:{2}", LoggingHash.HashString(asyncResult), errorCode, numBytes);
- }
- Debug.Fail("BaseOverlappedAsyncResult#" + LoggingHash.HashString(asyncResult) + "::CompletionPortCallback()|Unexpectedly succeeded. errorCode:" + errorCode + " numBytes: " + numBytes);
+ NetEventSource.Fail(asyncResult, $"Unexpectedly succeeded. errorCode:{errorCode} numBytes:{numBytes}");
}
}
catch (ObjectDisposedException)
@@ -218,13 +186,7 @@ namespace System.Net.Sockets
protected virtual void ForceReleaseUnmanagedStructures()
{
// Free the unmanaged memory if allocated.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "BaseOverlappedAsyncResult#" + LoggingHash.HashString(this) +
- "::ForceReleaseUnmanagedStructures");
- }
-
+ NetEventSource.Enter(this);
_nativeOverlapped.Dispose();
_nativeOverlapped = null;
GC.SuppressFinalize(this);
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.cs b/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.cs
index d81a153f90..a225e6ecbb 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.cs
@@ -30,12 +30,7 @@ namespace System.Net.Sockets
// 3) failed.
internal unsafe SocketError CheckAsyncCallOverlappedResult(SocketError errorCode)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "BaseOverlappedAsyncResult#" + LoggingHash.HashString(this) +
- "::CheckAsyncCallOverlappedResult(" + errorCode.ToString() + ")");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, errorCode);
if (errorCode == SocketError.Success || errorCode == SocketError.IOPending)
{
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs b/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs
index 1bd6ef2f21..8b6fdbf42d 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs
@@ -54,11 +54,7 @@ namespace System.Net.Sockets
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.StartConnectAsync(): Unexpected endpoint address family - " + endPoint.AddressFamily.ToString());
- }
- Debug.Fail("MultipleConnectAsync.StartConnectAsync(): Unexpected endpoint address family - " + endPoint.AddressFamily.ToString());
+ NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
@@ -74,11 +70,7 @@ namespace System.Net.Sockets
if (_state != State.NotStarted)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
- }
- Debug.Fail("MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
+ NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
@@ -122,11 +114,7 @@ namespace System.Net.Sockets
if (_state != State.DnsQuery)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
- }
- Debug.Fail("MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
+ NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
}
try
@@ -134,11 +122,7 @@ namespace System.Net.Sockets
_addressList = DnsAPMExtensions.EndGetHostAddresses(result);
if (_addressList == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
- }
- Debug.Fail("MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
+ NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
@@ -266,19 +250,11 @@ namespace System.Net.Sockets
{
if (_state != State.UserConnectAttempt)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.InternalConnectCallback(): Unexpected object state");
- }
- Debug.Fail("MultipleConnectAsync.InternalConnectCallback(): Unexpected object state");
+ NetEventSource.Fail(this, "Unexpected object state");
}
if (!RequiresUserConnectAttempt)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.InternalConnectCallback(): State.UserConnectAttempt without RequiresUserConnectAttempt");
- }
- Debug.Fail("MultipleConnectAsync.InternalConnectCallback(): State.UserConnectAttempt without RequiresUserConnectAttempt");
+ NetEventSource.Fail(this, "State.UserConnectAttempt without RequiresUserConnectAttempt");
}
if (args.SocketError == SocketError.Success)
@@ -326,11 +302,7 @@ namespace System.Net.Sockets
if (attemptAddress == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.AttemptConnection: attemptAddress is null!");
- }
- Debug.Fail("MultipleConnectAsync.AttemptConnection: attemptAddress is null!");
+ NetEventSource.Fail(this, "attemptAddress is null!");
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
@@ -341,11 +313,7 @@ namespace System.Net.Sockets
{
if (e is ObjectDisposedException)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.AttemptConnection: unexpected ObjectDisposedException");
- }
- Debug.Fail("MultipleConnectAsync.AttemptConnection: unexpected ObjectDisposedException");
+ NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
@@ -369,11 +337,7 @@ namespace System.Net.Sockets
{
if (e is ObjectDisposedException)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.AttemptConnection: unexpected ObjectDisposedException");
- }
- Debug.Fail("MultipleConnectAsync.AttemptConnection: unexpected ObjectDisposedException");
+ NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
@@ -385,11 +349,7 @@ namespace System.Net.Sockets
{
if (attemptSocket == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.AttemptConnection: attemptSocket is null!");
- }
- Debug.Fail("MultipleConnectAsync.AttemptConnection: attemptSocket is null!");
+ NetEventSource.Fail(null, "attemptSocket is null!");
}
if (!attemptSocket.ConnectAsync(args))
@@ -523,11 +483,7 @@ namespace System.Net.Sockets
break;
default:
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("MultipleConnectAsync.Cancel(): Unexpected object state");
- }
- Debug.Fail("MultipleConnectAsync.Cancel(): Unexpected object state");
+ NetEventSource.Fail(this, "Unexpected object state");
break;
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs b/src/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs
new file mode 100644
index 0000000000..86c8a46afc
--- /dev/null
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs
@@ -0,0 +1,80 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using System.Net.Sockets;
+
+namespace System.Net
+{
+ //TODO: If localization resources are not found, logging does not work. Issue #5126.
+ [EventSource(Name = "Microsoft-System-Net-Sockets", Guid = "e03c0352-f9c9-56ff-0ea7-b94ba8cabc6b", LocalizationResources = "FxResources.System.Net.Sockets.SR")]
+ internal sealed partial class NetEventSource
+ {
+ private const int AcceptedId = NextAvailableEventId;
+ private const int ConnectedId = AcceptedId + 1;
+ private const int ConnectedAsyncDnsId = ConnectedId + 1;
+ private const int NotLoggedFileId = ConnectedAsyncDnsId + 1;
+ private const int DumpArrayId = NotLoggedFileId + 1;
+
+ [NonEvent]
+ public static void Accepted(Socket socket, object remoteEp, object localEp)
+ {
+ if (IsEnabled)
+ {
+ Log.Accepted(IdOf(remoteEp), IdOf(localEp), GetHashCode(socket));
+ }
+ }
+
+ [Event(AcceptedId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void Accepted(string remoteEp, string localEp, int socketHash)
+ {
+ WriteEvent(AcceptedId, remoteEp, localEp, socketHash);
+ }
+
+ [NonEvent]
+ public static void Connected(Socket socket, object localEp, object remoteEp)
+ {
+ if (IsEnabled)
+ {
+ Log.Connected(IdOf(localEp), IdOf(remoteEp), GetHashCode(socket));
+ }
+ }
+
+ [Event(ConnectedId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void Connected(string localEp, string remoteEp, int socketHash)
+ {
+ WriteEvent(ConnectedId, localEp, remoteEp, socketHash);
+ }
+
+ [NonEvent]
+ public static void ConnectedAsyncDns(Socket socket)
+ {
+ if (IsEnabled)
+ {
+ Log.ConnectedAsyncDns(GetHashCode(socket));
+ }
+ }
+
+ [Event(ConnectedAsyncDnsId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void ConnectedAsyncDns(int socketHash)
+ {
+ WriteEvent(ConnectedAsyncDnsId, socketHash);
+ }
+
+ [NonEvent]
+ public static void NotLoggedFile(string filePath, Socket socket, SocketAsyncOperation completedOperation)
+ {
+ if (IsEnabled)
+ {
+ Log.NotLoggedFile(filePath, GetHashCode(socket), completedOperation);
+ }
+ }
+
+ [Event(NotLoggedFileId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
+ private void NotLoggedFile(string filePath, int socketHash, SocketAsyncOperation completedOperation)
+ {
+ WriteEvent(NotLoggedFileId, filePath, socketHash, (int)completedOperation);
+ }
+ }
+}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs b/src/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs
index 76a029066f..acb47197d5 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs
@@ -51,7 +51,7 @@ namespace System.Net.Sockets
public NetworkStream(Socket socket, FileAccess access, bool ownsSocket)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
if (socket == null)
@@ -216,7 +216,7 @@ namespace System.Net.Sockets
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
@@ -232,7 +232,7 @@ namespace System.Net.Sockets
set
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (value <= 0 && value != System.Threading.Timeout.Infinite)
@@ -253,7 +253,7 @@ namespace System.Net.Sockets
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
@@ -269,7 +269,7 @@ namespace System.Net.Sockets
set
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (value <= 0 && value != System.Threading.Timeout.Infinite)
@@ -290,7 +290,7 @@ namespace System.Net.Sockets
get
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (_cleanedUp)
@@ -391,7 +391,7 @@ namespace System.Net.Sockets
public override int Read(byte[] buffer, int offset, int size)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
bool canRead = CanRead; // Prevent race with Dispose.
@@ -464,7 +464,7 @@ namespace System.Net.Sockets
public override void Write(byte[] buffer, int offset, int size)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
bool canWrite = CanWrite; // Prevent race with Dispose.
@@ -524,7 +524,7 @@ namespace System.Net.Sockets
public void Close(int timeout)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
if (timeout < -1)
@@ -541,7 +541,7 @@ namespace System.Net.Sockets
protected override void Dispose(bool disposing)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
// Mark this as disposed before changing anything else.
@@ -581,7 +581,7 @@ namespace System.Net.Sockets
~NetworkStream()
{
#if DEBUG
- GlobalLog.SetThreadSource(ThreadKinds.Finalization);
+ DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
#endif
Dispose(false);
}
@@ -623,7 +623,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool canRead = CanRead; // Prevent race with Dispose.
@@ -739,7 +739,7 @@ namespace System.Net.Sockets
public int EndRead(IAsyncResult asyncResult)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
if (_cleanedUp)
@@ -800,7 +800,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool canWrite = CanWrite; // Prevent race with Dispose.
@@ -866,7 +866,7 @@ namespace System.Net.Sockets
internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool canWrite = CanWrite; // Prevent race with Dispose.
@@ -926,7 +926,7 @@ namespace System.Net.Sockets
public void EndWrite(IAsyncResult asyncResult)
{
#if DEBUG
- using (GlobalLog.SetThreadKind(ThreadKinds.User))
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
if (_cleanedUp)
@@ -1105,11 +1105,8 @@ namespace System.Net.Sockets
private int _currentWriteTimeout = -1;
internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption() mode:" + mode + " silent:" + silent + " timeout:" + timeout + " m_CurrentReadTimeout:" + _currentReadTimeout + " m_CurrentWriteTimeout:" + _currentWriteTimeout);
- }
- GlobalLog.ThreadContract(ThreadKinds.Unknown, "NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption");
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, mode, timeout, silent);
+ DebugThreadTracking.ThreadContract(ThreadKinds.Unknown, $"NetworkStream#{NetEventSource.IdOf(this)}");
if (timeout < 0)
{
@@ -1144,11 +1141,7 @@ namespace System.Net.Sockets
{
if (_streamSocket != null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("_streamSocket:");
- }
-
+ NetEventSource.Info(this, _streamSocket);
_streamSocket.DebugMembers();
}
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs b/src/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs
index d342c7de0d..5773ad1154 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs
@@ -104,23 +104,19 @@ namespace System.Net.Sockets
// 3) failed.
internal override object PostCompletion(int numBytes)
{
- if (ErrorCode == 0 && SocketsEventSource.Log.IsEnabled())
+ if (ErrorCode == 0 && NetEventSource.IsEnabled)
{
LogBuffer(numBytes);
}
- return (int)numBytes;
+ return numBytes;
}
private void LogBuffer(int size)
{
- if (!SocketsEventSource.Log.IsEnabled())
+ if (!NetEventSource.IsEnabled)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("OverlappedAsyncResult#{0}::LogBuffer()|Logging is off!", LoggingHash.HashString(this));
- }
- Debug.Fail("OverlappedAsyncResult#" + LoggingHash.HashString(this) + "::LogBuffer()|Logging is off!");
+ return;
}
if (size > -1)
@@ -129,7 +125,7 @@ namespace System.Net.Sockets
{
foreach (WSABuffer wsaBuffer in _wsaBuffers)
{
- SocketsEventSource.Dump(wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
+ NetEventSource.DumpArray(this, wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <= 0)
{
break;
@@ -138,7 +134,7 @@ namespace System.Net.Sockets
}
else
{
- SocketsEventSource.Dump(_singleBuffer.Pointer, Math.Min(_singleBuffer.Length, size));
+ NetEventSource.DumpArray(this, _singleBuffer.Pointer, Math.Min(_singleBuffer.Length, size));
}
}
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs b/src/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs
index 2bb97c9607..6227e31b58 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs
@@ -152,7 +152,7 @@ namespace System.Net.Sockets
internal override object PostCompletion(int numBytes)
{
InitIPPacketInformation();
- if (ErrorCode == 0 && SocketsEventSource.Log.IsEnabled())
+ if (ErrorCode == 0 && NetEventSource.IsEnabled)
{
LogBuffer(numBytes);
}
@@ -162,15 +162,7 @@ namespace System.Net.Sockets
private void LogBuffer(int size)
{
- if (!SocketsEventSource.Log.IsEnabled())
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.AssertFormat("ReceiveMessageOverlappedAsyncResult#{0}::LogBuffer()|Logging is off!", LoggingHash.HashString(this));
- }
- Debug.Fail("ReceiveMessageOverlappedAsyncResult#" + LoggingHash.HashString(this) + "::LogBuffer()|Logging is off!");
- }
- SocketsEventSource.Dump(_wsaBuffer->Pointer, Math.Min(_wsaBuffer->Length, size));
+ if (NetEventSource.IsEnabled) NetEventSource.DumpArray(this, _wsaBuffer->Pointer, Math.Min(_wsaBuffer->Length, size));
}
}
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
index 3288823eb1..7664ad5e25 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
@@ -74,7 +74,6 @@ namespace System.Net.Sockets
private int _intCleanedUp; // 0 if not completed, > 0 otherwise.
internal static volatile bool s_initialized;
- private static volatile bool s_loggingEnabled;
internal static volatile bool s_perfCountersEnabled;
#region Constructors
@@ -87,11 +86,7 @@ namespace System.Net.Sockets
// Initializes a new instance of the Sockets.Socket class.
public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
- s_loggingEnabled = SocketsEventSource.Log.IsEnabled();
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Socket), addressFamily);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addressFamily);
InitializeSockets();
@@ -112,11 +107,7 @@ namespace System.Net.Sockets
// TODO: Investigate this problematic assertion: Issue #4500.
// Debug.Assert(addressFamily != AddressFamily.InterNetworkV6 || !DualMode);
-
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Socket), null);
- }
+ NetEventSource.Exit(this);
}
public Socket(SocketInformation socketInformation)
@@ -131,11 +122,7 @@ namespace System.Net.Sockets
// Called by the class to create a socket to accept an incoming request.
private Socket(SafeCloseSocket fd)
{
- s_loggingEnabled = NetEventSource.Log.IsEnabled();
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Socket), null);
- }
+ NetEventSource.Enter(this);
InitializeSockets();
// NOTE: if this ctor is re-publicized/protected, check
@@ -152,10 +139,7 @@ namespace System.Net.Sockets
_addressFamily = Sockets.AddressFamily.Unknown;
_socketType = Sockets.SocketType.Unknown;
_protocolType = Sockets.ProtocolType.Unknown;
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Socket), null);
- }
+ NetEventSource.Exit(this);
}
#endregion
@@ -202,10 +186,7 @@ namespace System.Net.Sockets
// This may throw ObjectDisposedException.
SocketError errorCode = SocketPal.GetAvailable(_handle, out argp);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Available_get() Interop.Winsock.ioctlsocket returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.ioctlsocket returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -213,10 +194,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Available), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -260,10 +238,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(LocalEndPoint), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -309,10 +284,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(RemoteEndPoint), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -360,10 +332,7 @@ namespace System.Net.Sockets
throw new ObjectDisposedException(this.GetType().FullName);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::set_Blocking() value:" + value.ToString() + " willBlock:" + _willBlock.ToString() + " willBlockInternal:" + _willBlockInternal.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"value:{value} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
bool current;
@@ -374,10 +343,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Blocking), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -412,10 +378,7 @@ namespace System.Net.Sockets
{
get
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Connected() _isConnected:" + _isConnected);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_isConnected:{_isConnected}");
if (_nonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
{
@@ -742,10 +705,7 @@ namespace System.Net.Sockets
// Associates a socket with an end point.
public void Bind(EndPoint localEP)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Bind), localEP);
- }
+ NetEventSource.Enter(this, localEP);
if (CleanedUp)
{
@@ -758,11 +718,7 @@ namespace System.Net.Sockets
throw new ArgumentNullException(nameof(localEP));
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Bind() localEP:" + localEP.ToString());
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"localEP:{localEP}");
EndPoint endPointSnapshot = localEP;
IPEndPoint ipSnapshot = localEP as IPEndPoint;
@@ -781,36 +737,23 @@ namespace System.Net.Sockets
// Ask the EndPoint to generate a SocketAddress that we can pass down to native code.
Internals.SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPointSnapshot);
DoBind(endPointSnapshot, socketAddress);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Bind), "");
- }
+ NetEventSource.Exit(this);
}
internal void InternalBind(EndPoint localEP)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(InternalBind), localEP);
- }
+ NetEventSource.Enter(this, localEP);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::InternalBind() localEP:" + localEP.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"localEP:{localEP}");
if (localEP is DnsEndPoint)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("Calling InternalBind with a DnsEndPoint, about to get NotImplementedException");
- }
- Debug.Fail("Calling InternalBind with a DnsEndPoint, about to get NotImplementedException");
+ NetEventSource.Fail(this, "Calling InternalBind with a DnsEndPoint, about to get NotImplementedException");
}
// Ask the EndPoint to generate a SocketAddress that we can pass down to native code.
@@ -818,10 +761,7 @@ namespace System.Net.Sockets
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
DoBind(endPointSnapshot, socketAddress);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(InternalBind), "");
- }
+ NetEventSource.Exit(this);
}
private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
@@ -832,10 +772,7 @@ namespace System.Net.Sockets
{
SocketException socketException = new SocketException((int)SocketError.InvalidArgument);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(DoBind), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -846,11 +783,11 @@ namespace System.Net.Sockets
socketAddress.Size);
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Bind() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " Interop.Winsock.bind returns errorCode:" + errorCode);
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} Interop.Winsock.bind returns errorCode:{errorCode}");
}
catch (ObjectDisposedException) { }
}
@@ -862,10 +799,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(DoBind), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -901,9 +835,9 @@ namespace System.Net.Sockets
}
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Connect() DST:" + LoggingHash.ObjectToString(remoteEP));
+ NetEventSource.Info(this, $"DST:{remoteEP}");
}
DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
@@ -933,10 +867,7 @@ namespace System.Net.Sockets
public void Connect(IPAddress address, int port)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), address);
- }
+ NetEventSource.Enter(this, address);
if (CleanedUp)
{
@@ -958,18 +889,12 @@ namespace System.Net.Sockets
IPEndPoint remoteEP = new IPEndPoint(address, port);
Connect(remoteEP);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), null);
- }
+ NetEventSource.Exit(this);
}
public void Connect(string host, int port)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), host);
- }
+ NetEventSource.Enter(this, host);
if (CleanedUp)
{
@@ -999,18 +924,12 @@ namespace System.Net.Sockets
Connect(addresses, port);
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), null);
- }
+ NetEventSource.Exit(this);
}
public void Connect(IPAddress[] addresses, int port)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), addresses);
- }
+ NetEventSource.Enter(this, addresses);
if (CleanedUp)
{
@@ -1067,37 +986,25 @@ namespace System.Net.Sockets
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), null);
- }
+ NetEventSource.Exit(this);
}
public void Close()
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Close), null);
- }
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Close() timeout = " + _closeTimeout);
+ NetEventSource.Enter(this);
+ NetEventSource.Info(this, $"timeout = {_closeTimeout}");
}
Dispose();
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Close), null);
- }
+ NetEventSource.Exit(this);
}
public void Close(int timeout)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Close), timeout);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, timeout);
if (timeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
@@ -1105,49 +1012,35 @@ namespace System.Net.Sockets
_closeTimeout = timeout;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Close() timeout = " + _closeTimeout);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
Dispose();
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Close), timeout);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, timeout);
}
// Places a socket in a listening state.
public void Listen(int backlog)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Listen), backlog);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, backlog);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Listen() backlog:" + backlog.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"backlog:{backlog}");
// No access permissions are necessary here because the verification is done for Bind.
// This may throw ObjectDisposedException.
- SocketError errorCode = SocketPal.Listen(
- _handle,
- backlog);
+ SocketError errorCode = SocketPal.Listen(_handle, backlog);
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Listen() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " Interop.Winsock.listen returns errorCode:" + errorCode);
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} Interop.Winsock.listen returns errorCode:{errorCode}");
}
catch (ObjectDisposedException) { }
}
@@ -1159,26 +1052,17 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Listen), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
_isListening = true;
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Listen), "");
- }
+ NetEventSource.Exit(this);
}
// Creates a new Sockets.Socket instance to handle an incoming connection.
public Socket Accept()
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Accept), "");
- }
+ NetEventSource.Enter(this);
// Validate input parameters.
@@ -1203,10 +1087,7 @@ namespace System.Net.Sockets
}
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Accept() SRC:" + LoggingHash.ObjectToString(LocalEndPoint));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint}");
Internals.SocketAddress socketAddress = IPEndPointExtensions.Serialize(_rightEndPoint);
@@ -1226,20 +1107,17 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Accept), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
Debug.Assert(!acceptedSocketHandle.IsInvalid);
Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- SocketsEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Accept), socket);
+ NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
+ NetEventSource.Exit(this, socket);
}
return socket;
}
@@ -1278,10 +1156,7 @@ namespace System.Net.Sockets
public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Send), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -1297,20 +1172,17 @@ namespace System.Net.Sockets
}
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Send() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint}");
int bytesTransferred;
errorCode = SocketPal.Send(_handle, buffers, socketFlags, out bytesTransferred);
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Send() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " Interop.Winsock.send returns errorCode:" + errorCode + " bytesTransferred:" + bytesTransferred);
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} Interop.Winsock.send returns errorCode:{errorCode} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
@@ -1320,10 +1192,10 @@ namespace System.Net.Sockets
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Send), new SocketException((int)errorCode));
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Send), 0);
+ NetEventSource.Error(this, new SocketException((int)errorCode));
+ NetEventSource.Exit(this, 0);
}
return 0;
}
@@ -1339,10 +1211,8 @@ namespace System.Net.Sockets
}
}
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Send), bytesTransferred);
- }
+
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
@@ -1360,10 +1230,7 @@ namespace System.Net.Sockets
public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Send), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
@@ -1386,10 +1253,7 @@ namespace System.Net.Sockets
errorCode = SocketError.Success;
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Send() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " size:" + size);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} size:{size}");
// This can throw ObjectDisposedException.
int bytesTransferred;
@@ -1400,10 +1264,10 @@ namespace System.Net.Sockets
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Send), new SocketException((int)errorCode));
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Send), 0);
+ NetEventSource.Error(this, new SocketException((int)errorCode));
+ NetEventSource.Exit(this, 0);
}
return 0;
}
@@ -1420,26 +1284,21 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Send() Interop.Winsock.send returns:" + bytesTransferred.ToString());
- GlobalLog.Dump(buffer, offset, bytesTransferred);
- }
- if (s_loggingEnabled)
- {
- SocketsEventSource.Dump(buffer, offset, size);
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Send), bytesTransferred);
+ NetEventSource.Info(this, $"Interop.Winsock.send returns:{bytesTransferred}");
+ NetEventSource.DumpArray(this, buffer, offset, bytesTransferred);
+ NetEventSource.Exit(this, bytesTransferred);
}
+
return bytesTransferred;
}
// Sends data to a specific end point, starting at the indicated location in the buffer.
public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(SendTo), "");
- }
+ NetEventSource.Enter(this);
+
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -1463,10 +1322,7 @@ namespace System.Net.Sockets
}
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SendTo() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " size:" + size + " remoteEP:" + LoggingHash.ObjectToString(remoteEP));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} size:{size} remoteEP:{remoteEP}");
// CheckCacheRemote will check ConnectPermission for remoteEP.
EndPoint endPointSnapshot = remoteEP;
@@ -1482,10 +1338,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(SendTo), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -1507,15 +1360,10 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SendTo() returning bytesTransferred:" + bytesTransferred.ToString());
- GlobalLog.Dump(buffer, offset, bytesTransferred);
- }
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- SocketsEventSource.Dump(buffer, offset, size);
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(SendTo), bytesTransferred);
+ NetEventSource.DumpArray(this, buffer, offset, size);
+ NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
}
@@ -1566,10 +1414,7 @@ namespace System.Net.Sockets
public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Receive), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -1590,10 +1435,7 @@ namespace System.Net.Sockets
}
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Receive() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " size:" + size);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} size:{size}");
int bytesTransferred;
errorCode = SocketPal.Receive(_handle, buffer, offset, size, socketFlags, out bytesTransferred);
@@ -1602,10 +1444,10 @@ namespace System.Net.Sockets
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Receive), new SocketException((int)errorCode));
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Receive), 0);
+ NetEventSource.Error(this, new SocketException((int)errorCode));
+ NetEventSource.Exit(this, 0);
}
return 0;
}
@@ -1624,24 +1466,17 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
#if TRACE_VERBOSE
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Receive() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " bytesTransferred:" + bytesTransferred);
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
#endif
- GlobalLog.Dump(buffer, offset, bytesTransferred);
- }
- if (s_loggingEnabled)
- {
- SocketsEventSource.Dump(buffer, offset, bytesTransferred);
- }
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Receive), bytesTransferred);
+ NetEventSource.DumpArray(this, buffer, offset, bytesTransferred);
+ NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
@@ -1665,10 +1500,8 @@ namespace System.Net.Sockets
public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Receive), "");
- }
+ NetEventSource.Enter(this);
+
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -1686,20 +1519,17 @@ namespace System.Net.Sockets
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Receive() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint}");
int bytesTransferred;
errorCode = SocketPal.Receive(_handle, buffers, ref socketFlags, out bytesTransferred);
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Receive() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " Interop.Winsock.send returns errorCode:" + errorCode + " bytesTransferred:" + bytesTransferred);
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} Interop.Winsock.send returns errorCode:{errorCode} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
@@ -1709,10 +1539,10 @@ namespace System.Net.Sockets
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Receive), new SocketException((int)errorCode));
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Receive), 0);
+ NetEventSource.Error(this, new SocketException((int)errorCode));
+ NetEventSource.Exit(this, 0);
}
return 0;
}
@@ -1732,20 +1562,17 @@ namespace System.Net.Sockets
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Receive() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " bytesTransferred:" + bytesTransferred);
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
#endif
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Receive), bytesTransferred);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
@@ -1754,11 +1581,7 @@ namespace System.Net.Sockets
// the end point.
public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(ReceiveMessageFrom), "");
- }
-
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -1812,10 +1635,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(ReceiveMessageFrom), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -1835,10 +1655,7 @@ namespace System.Net.Sockets
}
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(ReceiveMessageFrom), errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Error(this, errorCode);
return bytesTransferred;
}
@@ -1846,10 +1663,7 @@ namespace System.Net.Sockets
// the end point.
public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(ReceiveFrom), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -1885,10 +1699,7 @@ namespace System.Net.Sockets
SocketPal.CheckDualModeReceiveSupport(this);
ValidateBlockingMode();
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::ReceiveFrom() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " size:" + size + " remoteEP:" + remoteEP.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC{LocalEndPoint} size:{size} remoteEP:{remoteEP}");
// We don't do a CAS demand here because the contents of remoteEP aren't used by
// WSARecvFrom; all that matters is that we generate a unique-to-this-call SocketAddress
@@ -1907,10 +1718,7 @@ namespace System.Net.Sockets
{
socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(ReceiveFrom), socketException);
- }
+ NetEventSource.Error(this, socketException);
if (socketException.SocketErrorCode != SocketError.MessageSize)
{
@@ -1951,17 +1759,10 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Dump(buffer, offset, bytesTransferred);
- }
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- SocketsEventSource.Dump(buffer, offset, size);
- }
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(ReceiveFrom), bytesTransferred);
+ NetEventSource.DumpArray(this, buffer, offset, size);
+ NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
}
@@ -2000,10 +1801,7 @@ namespace System.Net.Sockets
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.WindowsIoctl(_handle, ioControlCode, optionInValue, optionOutValue, out realOptionLength);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::IOControl() Interop.Winsock.WSAIoctl returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSAIoctl returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -2011,10 +1809,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(IOControl), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -2034,10 +1829,7 @@ namespace System.Net.Sockets
throw new ObjectDisposedException(this.GetType().FullName);
}
CheckSetOptionPermissions(optionLevel, optionName);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetSocketOption(): optionLevel:" + optionLevel.ToString() + " optionName:" + optionName.ToString() + " optionValue:" + optionValue.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue}");
SetSocketOption(optionLevel, optionName, optionValue, false);
}
@@ -2051,18 +1843,12 @@ namespace System.Net.Sockets
CheckSetOptionPermissions(optionLevel, optionName);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetSocketOption(): optionLevel:" + optionLevel.ToString() + " optionName:" + optionName.ToString() + " optionValue:" + optionValue.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue}");
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.SetSockOpt(_handle, optionLevel, optionName, optionValue);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetSocketOption() Interop.Winsock.setsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -2070,10 +1856,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(SetSocketOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
}
@@ -2100,10 +1883,7 @@ namespace System.Net.Sockets
CheckSetOptionPermissions(optionLevel, optionName);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetSocketOption(): optionLevel:" + optionLevel.ToString() + " optionName:" + optionName.ToString() + " optionValue:" + optionValue.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue}");
if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
{
@@ -2173,21 +1953,15 @@ namespace System.Net.Sockets
optionName,
out optionValue);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::GetSocketOption() Interop.Winsock.getsockopt returns errorCode:" + errorCode);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
+
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(GetSocketOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -2211,10 +1985,7 @@ namespace System.Net.Sockets
optionValue,
ref optionLength);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::GetSocketOption() Interop.Winsock.getsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -2222,10 +1993,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(GetSocketOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
}
@@ -2248,10 +2016,7 @@ namespace System.Net.Sockets
optionValue,
ref realOptionLength);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::GetSocketOption() Interop.Winsock.getsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -2259,10 +2024,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(GetSocketOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -2307,10 +2069,7 @@ namespace System.Net.Sockets
bool status;
SocketError errorCode = SocketPal.Poll(_handle, microSeconds, mode, out status);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Poll() Interop.Winsock.select returns socketCount:" + (int)errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.select returns socketCount:{(int)errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -2318,10 +2077,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Poll), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -2380,11 +2136,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
{
// Validate input parameters.
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), remoteEP);
- }
-
+ NetEventSource.Enter(this, remoteEP);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2452,11 +2204,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), host);
- }
-
+ NetEventSource.Enter(this, host);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2484,10 +2232,7 @@ namespace System.Net.Sockets
if (IPAddress.TryParse(host, out parsedAddress))
{
IAsyncResult r = BeginConnect(parsedAddress, port, requestCallback, state);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), r);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, r);
return r;
}
@@ -2509,10 +2254,7 @@ namespace System.Net.Sockets
// Done posting.
result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), result);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
@@ -2526,10 +2268,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), address);
- }
+ NetEventSource.Enter(this, address);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2549,19 +2288,13 @@ namespace System.Net.Sockets
}
IAsyncResult result = BeginConnect(new IPEndPoint(address, port), requestCallback, state);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), result);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), addresses);
- }
+ NetEventSource.Enter(this, addresses);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2603,20 +2336,13 @@ namespace System.Net.Sockets
// Finished posting async op. Possibly will call callback.
result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), result);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginDisconnect), null);
- }
-
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2636,12 +2362,7 @@ namespace System.Net.Sockets
private void DoBeginDisconnect(bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginDisconnect() ");
- }
-
-
+ NetEventSource.Enter(this);
SocketError errorCode = SocketError.Success;
errorCode = SocketPal.DisconnectAsync(this, _handle, reuseSocket, asyncResult);
@@ -2652,10 +2373,7 @@ namespace System.Net.Sockets
_remoteEndPoint = null;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginDisconnect() UnsafeNclNativeMethods.OSSOCK.DisConnectEx returns:" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"UnsafeNclNativeMethods.OSSOCK.DisConnectEx returns:{errorCode}");
// if the asynchronous native call fails synchronously
// we'll throw a SocketException
@@ -2666,69 +2384,41 @@ namespace System.Net.Sockets
// update our internal state after this socket error and throw
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginDisconnect), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginDisconnect() returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginDisconnect), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
}
public void Disconnect(bool reuseSocket)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Disconnect), null);
- }
-
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Disconnect() ");
- }
-
SocketError errorCode = SocketError.Success;
// This can throw ObjectDisposedException (handle, and retrieving the delegate).
errorCode = SocketPal.Disconnect(this, _handle, reuseSocket);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Disconnect() UnsafeNclNativeMethods.OSSOCK.DisConnectEx returns:" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"UnsafeNclNativeMethods.OSSOCK.DisConnectEx returns:{errorCode}");
if (errorCode != SocketError.Success)
{
// update our internal state after this socket error and throw
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Disconnect), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
SetToDisconnected();
_remoteEndPoint = null;
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Disconnect), null);
- }
+ NetEventSource.Exit(this);
}
// Routine Description:
@@ -2745,10 +2435,7 @@ namespace System.Net.Sockets
// int - Return code from async Connect, 0 for success, SocketError.NotConnected otherwise
public void EndConnect(IAsyncResult asyncResult)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndConnect), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2803,17 +2490,11 @@ namespace System.Net.Sockets
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndConnect() asyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
if (castedAsyncResult.Result is Exception)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndConnect), (Exception)castedAsyncResult.Result);
- }
+ NetEventSource.Error(this, castedAsyncResult.Result);
throw (Exception)castedAsyncResult.Result;
}
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
@@ -2821,27 +2502,19 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = SocketExceptionFactory.CreateSocketException(castedAsyncResult.ErrorCode, remoteEndPoint);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndConnect), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- SocketsEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndConnect), "");
+ NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
+ NetEventSource.Exit(this, "");
}
}
public void EndDisconnect(IAsyncResult asyncResult)
{
-
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndDisconnect), asyncResult);
- }
-
+ NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2853,7 +2526,7 @@ namespace System.Net.Sockets
if (asyncResult == null)
{
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
}
@@ -2872,10 +2545,7 @@ namespace System.Net.Sockets
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndDisconnect()");
- }
+ NetEventSource.Info(this);
//
// if the asynchronous native call failed asynchronously
@@ -2888,18 +2558,11 @@ namespace System.Net.Sockets
//
SocketException socketException = new SocketException(castedAsyncResult.ErrorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndDisconnect), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndDisconnect), null);
- }
- return;
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Routine Description:
@@ -2932,11 +2595,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginSend), "");
- }
-
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -2974,20 +2633,13 @@ namespace System.Net.Sockets
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginSend), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
internal IAsyncResult UnsafeBeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(UnsafeBeginSend), "");
- }
-
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -3002,19 +2654,13 @@ namespace System.Net.Sockets
throw new SocketException((int)errorCode);
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(UnsafeBeginSend), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private SocketError DoBeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginSend() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " size:" + size.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} size:{size}");
// Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
// avoid a Socket leak in case of error.
@@ -3022,17 +2668,11 @@ namespace System.Net.Sockets
try
{
// Get the Send going.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("BeginSend: asyncResult:" + LoggingHash.HashString(asyncResult) + " size:" + size.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult} size:{size}");
errorCode = SocketPal.SendAsync(_handle, buffer, offset, size, socketFlags, asyncResult);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginSend() Interop.Winsock.WSASend returns:" + errorCode.ToString() + " size:" + size.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSASend returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
}
finally
{
@@ -3043,9 +2683,9 @@ namespace System.Net.Sockets
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginSend), new SocketException((int)errorCode));
+ NetEventSource.Error(this, new SocketException((int)errorCode));
}
}
return errorCode;
@@ -3064,11 +2704,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginSend), "");
- }
-
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -3101,36 +2737,24 @@ namespace System.Net.Sockets
asyncResult = null;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginSend), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private SocketError DoBeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginSend() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " buffers:" + buffers);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} buffers:{buffers}");
// Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
// avoid a Socket leak in case of error.
SocketError errorCode = SocketError.SocketError;
try
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("BeginSend: asyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
errorCode = SocketPal.SendAsync(_handle, buffers, socketFlags, asyncResult);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginSend() Interop.Winsock.WSASend returns:" + errorCode.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSASend returns:{errorCode} returning AsyncResult:{asyncResult}");
}
finally
{
@@ -3141,10 +2765,7 @@ namespace System.Net.Sockets
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginSend), new SocketException((int)errorCode));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Error(this, new SocketException((int)errorCode));
}
return errorCode;
}
@@ -3174,10 +2795,7 @@ namespace System.Net.Sockets
public int EndSend(IAsyncResult asyncResult, out SocketError errorCode)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndSend), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -3214,10 +2832,7 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndSend() bytesTransferred:" + bytesTransferred.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransffered:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
errorCode = (SocketError)castedAsyncResult.ErrorCode;
@@ -3225,17 +2840,15 @@ namespace System.Net.Sockets
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndSend), new SocketException((int)errorCode));
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndSend), 0);
+ NetEventSource.Error(this, new SocketException((int)errorCode));
+ NetEventSource.Exit(this, 0);
}
return 0;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndSend), bytesTransferred);
- }
+
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
@@ -3261,11 +2874,7 @@ namespace System.Net.Sockets
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginSendTo), "");
- }
-
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -3303,19 +2912,13 @@ namespace System.Net.Sockets
// Finish, possibly posting the callback. The callback won't be posted before this point is reached.
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginSendTo), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private void DoBeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginSendTo() size:" + size.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
EndPoint oldEndPoint = _rightEndPoint;
@@ -3331,10 +2934,7 @@ namespace System.Net.Sockets
errorCode = SocketPal.SendToAsync(_handle, buffer, offset, size, socketFlags, socketAddress, asyncResult);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginSendTo() Interop.Winsock.WSASend returns:" + errorCode.ToString() + " size:" + size + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSASend returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
}
catch (ObjectDisposedException)
{
@@ -3353,17 +2953,11 @@ namespace System.Net.Sockets
_rightEndPoint = oldEndPoint;
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginSendTo), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginSendTo() size:" + size.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
}
// Routine Description:
@@ -3380,10 +2974,8 @@ namespace System.Net.Sockets
// int - Number of bytes transferred
public int EndSendTo(IAsyncResult asyncResult)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndSendTo), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
+
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -3420,10 +3012,7 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndSendTo() bytesTransferred:" + bytesTransferred.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransferred:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
@@ -3431,16 +3020,11 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException(castedAsyncResult.ErrorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndSendTo), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndSendTo), bytesTransferred);
- }
+
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
@@ -3479,10 +3063,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginReceive), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
@@ -3521,19 +3102,13 @@ namespace System.Net.Sockets
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginReceive), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
internal IAsyncResult UnsafeBeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(UnsafeBeginReceive), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
@@ -3544,19 +3119,13 @@ namespace System.Net.Sockets
OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
DoBeginReceive(buffer, offset, size, socketFlags, asyncResult);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(UnsafeBeginReceive), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private SocketError DoBeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginReceive() size:" + size.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
#if DEBUG
IntPtr lastHandle = _handle.DangerousGetHandle();
@@ -3568,10 +3137,7 @@ namespace System.Net.Sockets
{
errorCode = SocketPal.ReceiveAsync(_handle, buffer, offset, size, socketFlags, asyncResult);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginReceive() Interop.Winsock.WSARecv returns:" + errorCode.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecv returns:{errorCode} returning AsyncResult:{asyncResult}");
}
finally
{
@@ -3582,17 +3148,12 @@ namespace System.Net.Sockets
if (errorCode != SocketError.Success)
{
// TODO: https://github.com/dotnet/corefx/issues/5426
- //if (GlobalLog.IsEnabled)
- //{
- // GlobalLog.AssertFormat("Socket#{0}::DoBeginReceive()|GetLastWin32Error() returned zero.", LoggingHash.HashString(this));
- //}
+ // NetEventSource.Fail(this, "GetLastWin32Error() returned zero.");
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginReceive), new SocketException((int)errorCode));
- }
+ var socketException = new SocketException((int)errorCode);
+ NetEventSource.Error(this, socketException);
asyncResult.InvokeCallback(new SocketException((int)errorCode));
}
#if DEBUG
@@ -3620,10 +3181,7 @@ namespace System.Net.Sockets
public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginReceive), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
@@ -3659,10 +3217,7 @@ namespace System.Net.Sockets
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginReceive), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
@@ -3677,11 +3232,7 @@ namespace System.Net.Sockets
try
{
errorCode = SocketPal.ReceiveAsync(_handle, buffers, socketFlags, asyncResult);
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginReceive() Interop.Winsock.WSARecv returns:" + errorCode.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecv returns:{errorCode} returning AsyncResult:{asyncResult}");
}
finally
{
@@ -3693,9 +3244,9 @@ namespace System.Net.Sockets
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginReceive), new SocketException((int)errorCode));
+ NetEventSource.Error(this, new SocketException((int)errorCode));
}
}
#if DEBUG
@@ -3742,10 +3293,8 @@ namespace System.Net.Sockets
public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndReceive), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
+
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -3783,11 +3332,11 @@ namespace System.Net.Sockets
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndReceive() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " bytesTransferred:" + bytesTransferred.ToString());
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
@@ -3799,30 +3348,23 @@ namespace System.Net.Sockets
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndReceive), new SocketException((int)errorCode));
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndReceive), 0);
+ NetEventSource.Error(this, new SocketException((int)errorCode));
+ NetEventSource.Exit(this, 0);
}
return 0;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndReceive), bytesTransferred);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginReceiveMessageFrom), "");
- }
-
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString());
+ NetEventSource.Enter(this);
+ NetEventSource.Info(this, $"size:{size}");
}
if (CleanedUp)
@@ -3893,20 +3435,12 @@ namespace System.Net.Sockets
// That same map is implemented here just in case.
if (errorCode == SocketError.MessageSize)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("Socket#" + LoggingHash.HashString(this) + "::BeginReceiveMessageFrom()|Returned WSAEMSGSIZE!");
- }
- Debug.Fail("Socket#" + LoggingHash.HashString(this) + "::BeginReceiveMessageFrom()|Returned WSAEMSGSIZE!");
-
+ NetEventSource.Fail(this, "Returned WSAEMSGSIZE!");
errorCode = SocketError.IOPending;
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginReceiveMessageFrom() Interop.Winsock.WSARecvMsg returns:" + errorCode.ToString() + " size:" + size.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecvMsg returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
}
catch (ObjectDisposedException)
{
@@ -3925,10 +3459,7 @@ namespace System.Net.Sockets
_rightEndPoint = oldEndPoint;
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginReceiveMessageFrom), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -3946,24 +3477,18 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
-
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginReceiveMessageFrom), asyncResult);
+ NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
+ NetEventSource.Exit(this, asyncResult);
}
return asyncResult;
}
public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndReceiveMessageFrom), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
+
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -4022,10 +3547,7 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndReceiveMessageFrom() bytesTransferred:" + bytesTransferred.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransferred:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success && (SocketError)castedAsyncResult.ErrorCode != SocketError.MessageSize)
@@ -4033,20 +3555,14 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException(castedAsyncResult.ErrorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndReceiveMessageFrom), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
socketFlags = castedAsyncResult.SocketFlags;
ipPacketInformation = castedAsyncResult.IPPacketInformation;
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndReceiveMessageFrom), bytesTransferred);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
@@ -4076,10 +3592,7 @@ namespace System.Net.Sockets
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginReceiveFrom), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
@@ -4140,11 +3653,7 @@ namespace System.Net.Sockets
}
}
-
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginReceiveFrom), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
@@ -4152,10 +3661,7 @@ namespace System.Net.Sockets
{
EndPoint oldEndPoint = _rightEndPoint;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginReceiveFrom() size:" + size.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
// Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
// avoid a Socket leak in case of error.
@@ -4172,10 +3678,7 @@ namespace System.Net.Sockets
errorCode = SocketPal.ReceiveFromAsync(_handle, buffer, offset, size, socketFlags, socketAddress, asyncResult);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginReceiveFrom() Interop.Winsock.WSARecvFrom returns:" + errorCode.ToString() + " size:" + size.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecvFrom returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
}
catch (ObjectDisposedException)
{
@@ -4194,17 +3697,11 @@ namespace System.Net.Sockets
_rightEndPoint = oldEndPoint;
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginReceiveFrom), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginReceiveFrom() size:" + size.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size} return AsyncResult:{asyncResult}");
}
// Routine Description:
@@ -4222,10 +3719,8 @@ namespace System.Net.Sockets
// int - Number of bytes transferred
public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndReceiveFrom), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
+
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -4286,10 +3781,7 @@ namespace System.Net.Sockets
}
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndReceiveFrom() bytesTransferred:" + bytesTransferred.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransferred:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
@@ -4297,16 +3789,10 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException(castedAsyncResult.ErrorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndReceiveFrom), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndReceiveFrom), bytesTransferred);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
@@ -4335,10 +3821,7 @@ namespace System.Net.Sockets
return BeginAccept(0, callback, state);
}
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginAccept), "");
- }
+ NetEventSource.Enter(this);
Debug.Assert(CleanedUp);
throw new ObjectDisposedException(this.GetType().FullName);
@@ -4352,10 +3835,7 @@ namespace System.Net.Sockets
// This is the truly async version that uses AcceptEx.
public IAsyncResult BeginAccept(Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginAccept), "");
- }
+ NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -4377,10 +3857,7 @@ namespace System.Net.Sockets
// Finish the flow capture, maybe complete here.
asyncResult.FinishPostingAsyncOp(ref Caches.AcceptClosureCache);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginAccept), asyncResult);
- }
+ NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
@@ -4399,30 +3876,21 @@ namespace System.Net.Sockets
SafeCloseSocket acceptHandle;
asyncResult.AcceptSocket = GetOrCreateAcceptSocket(acceptSocket, false, "acceptSocket", out acceptHandle);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginAccept() AcceptSocket:" + LoggingHash.HashString(acceptSocket));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"AcceptSocket:{acceptSocket}");
int socketAddressSize = _rightEndPoint.Serialize().Size;
SocketError errorCode = SocketPal.AcceptAsync(this, _handle, acceptHandle, receiveSize, socketAddressSize, asyncResult);
errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoBeginAccept() Interop.Winsock.AcceptEx returns:" + errorCode.ToString() + LoggingHash.HashString(asyncResult));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.AcceptEx returns:{errorCode} {asyncResult}");
// Throw an appropriate SocketException if the native call fails synchronously.
if (errorCode != SocketError.Success)
{
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginAccept), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
}
@@ -4460,10 +3928,7 @@ namespace System.Net.Sockets
internal Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndAccept), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -4504,28 +3969,24 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException(castedAsyncResult.ErrorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(EndAccept), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::EndAccept() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " acceptedSocket:" + LoggingHash.HashString(socket) + " acceptedSocket.SRC:" + LoggingHash.ObjectToString(socket.LocalEndPoint) + " acceptedSocket.DST:" + LoggingHash.ObjectToString(socket.RemoteEndPoint) + " bytesTransferred:" + bytesTransferred.ToString());
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} acceptedSocket:{socket} acceptedSocket.SRC:{socket.LocalEndPoint} acceptSocket.DST:{socket.RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
#endif
-
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- SocketsEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndAccept), socket);
+ NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
+ NetEventSource.Exit(this, socket);
}
return socket;
}
@@ -4533,27 +3994,18 @@ namespace System.Net.Sockets
// Disables sends and receives on a socket.
public void Shutdown(SocketShutdown how)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Shutdown), how);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, how);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Shutdown() how:" + how.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"how:{how}");
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.Shutdown(_handle, _isConnected, _isDisconnected, how);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Shutdown() Interop.Winsock.shutdown returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.shutdown returns errorCode:{errorCode}");
// Skip good cases: success, socket already closed.
if (errorCode != SocketError.Success && errorCode != SocketError.NotSocket)
@@ -4561,31 +4013,21 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Shutdown), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
SetToDisconnected();
InternalSetBlocking(_willBlockInternal);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Shutdown), "");
- }
+ NetEventSource.Exit(this);
}
#region Async methods
public bool AcceptAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(AcceptAsync), "");
- }
-
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
@@ -4643,22 +4085,15 @@ namespace System.Net.Sockets
retval = true;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(AcceptAsync), retval);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool ConnectAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(ConnectAsync), "");
- }
-
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
@@ -4687,10 +4122,7 @@ namespace System.Net.Sockets
if (dnsEP != null)
{
- if (s_loggingEnabled)
- {
- SocketsEventSource.Log.ConnectedAsyncDns(LoggingHash.HashInt(this));
- }
+ NetEventSource.ConnectedAsyncDns(this);
if (dnsEP.AddressFamily != AddressFamily.Unspecified && !CanTryAddressFamily(dnsEP.AddressFamily))
{
@@ -4768,22 +4200,15 @@ namespace System.Net.Sockets
}
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(ConnectAsync), retval);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(null);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, null, nameof(ConnectAsync), "");
- }
-
if (e == null)
{
throw new ArgumentNullException(nameof(e));
@@ -4836,10 +4261,7 @@ namespace System.Net.Sockets
retval = attemptSocket.ConnectAsync(e);
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, null, nameof(ConnectAsync), retval);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, retval);
return retval;
}
@@ -4854,14 +4276,9 @@ namespace System.Net.Sockets
public bool DisconnectAsync(SocketAsyncEventArgs e)
{
-
+ NetEventSource.Enter(this);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(DisconnectAsync), "");
- }
-
// Throw if socket disposed
if (CleanedUp)
{
@@ -4895,23 +4312,15 @@ namespace System.Net.Sockets
retval = true;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(DisconnectAsync), retval);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool ReceiveAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(ReceiveAsync), "");
- }
-
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
@@ -4954,22 +4363,15 @@ namespace System.Net.Sockets
retval = true;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(ReceiveAsync), retval);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool ReceiveFromAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(ReceiveFromAsync), "");
- }
-
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
@@ -5031,22 +4433,15 @@ namespace System.Net.Sockets
retval = true;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(ReceiveFromAsync), retval);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(ReceiveMessageFromAsync), "");
- }
-
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
@@ -5109,23 +4504,15 @@ namespace System.Net.Sockets
retval = true;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(ReceiveMessageFromAsync), retval);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool SendAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(SendAsync), "");
- }
-
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
@@ -5167,23 +4554,15 @@ namespace System.Net.Sockets
retval = true;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(SendAsync), retval);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool SendPacketsAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(SendPacketsAsync), "");
- }
-
// Throw if socket disposed
if (CleanedUp)
{
@@ -5243,23 +4622,15 @@ namespace System.Net.Sockets
retval = false;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(SendPacketsAsync), retval);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool SendToAsync(SocketAsyncEventArgs e)
{
+ NetEventSource.Enter(this, e);
bool retval;
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(SendToAsync), "");
- }
-
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
@@ -5271,7 +4642,7 @@ namespace System.Net.Sockets
}
if (e.RemoteEndPoint == null)
{
- throw new ArgumentNullException("RemoteEndPoint");
+ throw new ArgumentNullException(nameof(RemoteEndPoint));
}
// Check permissions for connect and prepare SocketAddress
@@ -5309,11 +4680,7 @@ namespace System.Net.Sockets
retval = true;
}
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(SendToAsync), retval);
- }
-
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
#endregion
@@ -5499,19 +4866,16 @@ namespace System.Net.Sockets
private void DoConnect(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), endPointSnapshot);
- }
+ NetEventSource.Enter(this, endPointSnapshot);
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.Connect(_handle, socketAddress.Buffer, socketAddress.Size);
#if TRACE_VERBOSE
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
try
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::InternalConnect() SRC:" + LoggingHash.ObjectToString(LocalEndPoint) + " DST:" + LoggingHash.ObjectToString(RemoteEndPoint) + " Interop.Winsock.WSAConnect returns errorCode:" + errorCode);
+ NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} Interop.Winsock.WSAConnect returns errorCode:{errorCode}");
}
catch (ObjectDisposedException) { }
}
@@ -5523,10 +4887,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = SocketExceptionFactory.CreateSocketException((int)errorCode, endPointSnapshot);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(Connect), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -5536,17 +4897,14 @@ namespace System.Net.Sockets
_rightEndPoint = endPointSnapshot;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::DoConnect() connection to:" + endPointSnapshot.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"connection to:{endPointSnapshot}");
// Update state and performance counters.
SetToConnected();
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- SocketsEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), "");
+ NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
+ NetEventSource.Exit(this);
}
}
@@ -5557,24 +4915,14 @@ namespace System.Net.Sockets
return;
}
- try
- {
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Dispose() disposing:true CleanedUp:" + CleanedUp.ToString());
- }
-
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Dispose), null);
- }
- }
- catch (Exception exception)
+ if (NetEventSource.IsEnabled)
{
- if (ExceptionCheck.IsFatal(exception))
+ try
{
- throw;
+ NetEventSource.Info(this, $"disposing:true CleanedUp:{CleanedUp}");
+ NetEventSource.Enter(this);
}
+ catch (Exception exception) when (!ExceptionCheck.IsFatal(exception)) { }
}
// Make sure we're the first call to Dispose and no SetAsyncEventSelect is in progress.
@@ -5587,20 +4935,7 @@ namespace System.Net.Sockets
if (last == 1)
{
- try
- {
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Dispose), null);
- }
- }
- catch (Exception exception)
- {
- if (ExceptionCheck.IsFatal(exception))
- {
- throw;
- }
- }
+ NetEventSource.Exit(this);
return;
}
@@ -5614,11 +4949,7 @@ namespace System.Net.Sockets
if (timeout == 0)
{
// Abortive.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Dispose() Calling _handle.Dispose()");
- }
-
+ NetEventSource.Info(this, "Calling _handle.Dispose()");
_handle.Dispose();
}
else
@@ -5630,30 +4961,20 @@ namespace System.Net.Sockets
{
bool willBlock;
errorCode = SocketPal.SetBlocking(_handle, false, out willBlock);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::Dispose(handle:" + _handle.DangerousGetHandle().ToString("x") + ") ioctlsocket(FIONBIO):" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} ioctlsocket(FIONBIO):{errorCode}");
}
if (timeout < 0)
{
// Close with existing user-specified linger option.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Dispose() Calling _handle.CloseAsIs()");
- }
-
+ NetEventSource.Info(this, "Calling _handle.CloseAsIs()");
_handle.CloseAsIs();
}
else
{
// Since our timeout is in ms and linger is in seconds, implement our own sortof linger here.
errorCode = SocketPal.Shutdown(_handle, _isConnected, _isDisconnected, SocketShutdown.Send);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::Dispose(handle:" + _handle.DangerousGetHandle().ToString("x") + ") shutdown():" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} shutdown():{errorCode}");
// This should give us a timeout in milliseconds.
errorCode = SocketPal.SetSockOpt(
@@ -5661,10 +4982,7 @@ namespace System.Net.Sockets
SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,
timeout);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::Dispose(handle:" + _handle.DangerousGetHandle().ToString("x") + ") setsockopt():" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} setsockopt():{errorCode}");
if (errorCode != SocketError.Success)
{
@@ -5674,10 +4992,7 @@ namespace System.Net.Sockets
{
int unused;
errorCode = SocketPal.Receive(_handle, null, 0, 0, SocketFlags.None, out unused);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::Dispose(handle:" + _handle.DangerousGetHandle().ToString("x") + ") recv():" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} recv():{errorCode}");
if (errorCode != (SocketError)0)
{
@@ -5689,10 +5004,7 @@ namespace System.Net.Sockets
// We got a FIN or data. Use ioctlsocket to find out which.
int dataAvailable = 0;
errorCode = SocketPal.GetAvailable(_handle, out dataAvailable);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("SafeCloseSocket::Dispose(handle:" + _handle.DangerousGetHandle().ToString("x") + ") ioctlsocket(FIONREAD):" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} ioctlsocket(FIONREAD):{errorCode}");
if (errorCode != SocketError.Success || dataAvailable != 0)
{
@@ -5713,31 +5025,20 @@ namespace System.Net.Sockets
}
catch (ObjectDisposedException)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SafeCloseSocket::Dispose(handle:" + _handle.DangerousGetHandle().ToString("x") + ")", "Closing the handle threw ObjectDisposedException.");
- }
- Debug.Fail("SafeCloseSocket::Dispose(handle:" + _handle.DangerousGetHandle().ToString("x") + ")", "Closing the handle threw ObjectDisposedException.");
+ NetEventSource.Fail(this, $"handle:{_handle}, Closing the handle threw ObjectDisposedException.");
}
}
public void Dispose()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::Dispose() timeout = " + _closeTimeout);
- }
-
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Dispose), null);
+ NetEventSource.Info(this, $"timeout = {_closeTimeout}");
+ NetEventSource.Enter(this);
}
Dispose(true);
GC.SuppressFinalize(this);
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Dispose), null);
- }
+ NetEventSource.Exit(this);
}
~Socket()
@@ -5748,10 +5049,7 @@ namespace System.Net.Sockets
// This version does not throw.
internal void InternalShutdown(SocketShutdown how)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::InternalShutdown() how:" + how.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"how:{how}");
if (CleanedUp || _handle.IsInvalid)
{
@@ -5798,28 +5096,18 @@ namespace System.Net.Sockets
internal unsafe void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue, bool silent)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetSocketOption() optionLevel:" + optionLevel + " optionName:" + optionName + " optionValue:" + optionValue + " silent:" + silent);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue} silent:{silent}");
if (silent && (CleanedUp || _handle.IsInvalid))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetSocketOption() skipping the call");
- }
+ NetEventSource.Info(this, "skipping the call");
return;
}
SocketError errorCode = SocketError.Success;
try
{
errorCode = SocketPal.SetSockOpt(_handle, optionLevel, optionName, optionValue);
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetSocketOption() Interop.Winsock.setsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
}
catch
{
@@ -5848,10 +5136,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(SetSocketOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
}
@@ -5860,10 +5145,7 @@ namespace System.Net.Sockets
{
SocketError errorCode = SocketPal.SetMulticastOption(_handle, optionName, MR);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetMulticastOption() Interop.Winsock.setsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -5871,10 +5153,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(SetMulticastOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
}
@@ -5884,10 +5163,7 @@ namespace System.Net.Sockets
{
SocketError errorCode = SocketPal.SetIPv6MulticastOption(_handle, optionName, MR);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetIPv6MulticastOption() Interop.Winsock.setsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -5895,10 +5171,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(SetIPv6MulticastOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
}
@@ -5907,10 +5180,7 @@ namespace System.Net.Sockets
{
SocketError errorCode = SocketPal.SetLingerOption(_handle, lref);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetLingerOption() Interop.Winsock.setsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -5918,10 +5188,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(SetLingerOption), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
}
@@ -5931,10 +5198,7 @@ namespace System.Net.Sockets
LingerOption lingerOption;
SocketError errorCode = SocketPal.GetLingerOption(_handle, out lingerOption);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::GetLingerOpt() Interop.Winsock.getsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -5942,10 +5206,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(GetLingerOpt), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -5957,10 +5218,7 @@ namespace System.Net.Sockets
MulticastOption multicastOption;
SocketError errorCode = SocketPal.GetMulticastOption(_handle, optionName, out multicastOption);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::GetMulticastOpt() Interop.Winsock.getsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -5968,10 +5226,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(GetMulticastOpt), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -5984,10 +5239,7 @@ namespace System.Net.Sockets
IPv6MulticastOption multicastOption;
SocketError errorCode = SocketPal.GetIPv6MulticastOption(_handle, optionName, out multicastOption);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::GetIPv6MulticastOpt() Interop.Winsock.getsockopt returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
@@ -5995,10 +5247,7 @@ namespace System.Net.Sockets
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(GetIPv6MulticastOpt), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -6009,18 +5258,11 @@ namespace System.Net.Sockets
// error code, and will update internal state on success.
private SocketError InternalSetBlocking(bool desired, out bool current)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter("Socket#" + LoggingHash.HashString(this) + "::InternalSetBlocking", "desired:" + desired.ToString() + " willBlock:" + _willBlock.ToString() + " willBlockInternal:" + _willBlockInternal.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"desired:{desired} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
if (CleanedUp)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("Socket#" + LoggingHash.HashString(this) + "::InternalSetBlocking", "ObjectDisposed");
- }
-
+ NetEventSource.Exit(this, "ObjectDisposed");
current = _willBlock;
return SocketError.Success;
}
@@ -6037,10 +5279,7 @@ namespace System.Net.Sockets
errorCode = SocketError.NotSocket;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::InternalSetBlocking() Interop.Winsock.ioctlsocket returns errorCode:" + errorCode);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.ioctlsocket returns errorCode:{errorCode}");
// We will update only internal state but only on successfull win32 call
// so if the native call fails, the state will remain the same.
@@ -6049,10 +5288,7 @@ namespace System.Net.Sockets
_willBlockInternal = willBlock;
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("Socket#" + LoggingHash.HashString(this) + "::InternalSetBlocking", "errorCode:" + errorCode.ToString() + " willBlock:" + _willBlock.ToString() + " willBlockInternal:" + _willBlockInternal.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"errorCode:{errorCode} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
current = _willBlockInternal;
return errorCode;
@@ -6069,10 +5305,7 @@ namespace System.Net.Sockets
// Since this is private, the unsafe mode is specified with a flag instead of an overload.
private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback callback, object state)
{
- if (s_loggingEnabled)
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnectEx), "");
- }
+ NetEventSource.Enter(this);
// This will check the permissions for connect.
EndPoint endPointSnapshot = remoteEP;
@@ -6128,10 +5361,7 @@ namespace System.Net.Sockets
SetToConnected();
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginConnectEx() Interop.Winsock.connect returns:" + errorCode.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.connect returns:{errorCode}");
errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
@@ -6142,10 +5372,7 @@ namespace System.Net.Sockets
_rightEndPoint = oldEndPoint;
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
- if (s_loggingEnabled)
- {
- NetEventSource.Exception(NetEventSource.ComponentType.Socket, this, nameof(BeginConnectEx), socketException);
- }
+ NetEventSource.Error(this, socketException);
throw socketException;
}
@@ -6153,14 +5380,10 @@ namespace System.Net.Sockets
// This is a nop if the context isn't being flowed.
asyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
- if (GlobalLog.IsEnabled)
+ if (NetEventSource.IsEnabled)
{
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::BeginConnectEx() to:" + endPointSnapshot.ToString() + " returning AsyncResult:" + LoggingHash.HashString(asyncResult));
- }
-
- if (s_loggingEnabled)
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnectEx), asyncResult);
+ NetEventSource.Info(this, $"{endPointSnapshot} returning AsyncResult:{asyncResult}");
+ NetEventSource.Exit(this, asyncResult);
}
return asyncResult;
}
@@ -6450,10 +5673,7 @@ namespace System.Net.Sockets
// some point in time update the perf counter as well.
_isConnected = true;
_isDisconnected = false;
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetToConnected() now connected.");
- }
+ NetEventSource.Info(this, "now connected");
if (s_perfCountersEnabled)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketConnectionsEstablished);
@@ -6462,10 +5682,7 @@ namespace System.Net.Sockets
internal void SetToDisconnected()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetToDisconnected()");
- }
+ NetEventSource.Enter(this);
if (!_isConnected)
{
@@ -6478,10 +5695,10 @@ namespace System.Net.Sockets
_isConnected = false;
_isDisconnected = true;
- if (!CleanedUp && GlobalLog.IsEnabled)
+ if (!CleanedUp)
{
// If socket is still alive cancel WSAEventSelect().
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::SetToDisconnected()");
+ NetEventSource.Info(this, "!CleanedUp");
}
}
@@ -6497,26 +5714,15 @@ namespace System.Net.Sockets
{
// If we already know the socket is disconnected
// we don't need to do anything else.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::UpdateStatusAfterSocketError(socketException)");
- }
-
- if (s_loggingEnabled)
- {
- NetEventSource.PrintError(NetEventSource.ComponentType.Socket, this, nameof(UpdateStatusAfterSocketError), errorCode.ToString());
- }
+ NetEventSource.Enter(this);
+ if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"errorCode:{errorCode}");
if (_isConnected && (_handle.IsInvalid || (errorCode != SocketError.WouldBlock &&
errorCode != SocketError.IOPending && errorCode != SocketError.NoBufferSpaceAvailable &&
errorCode != SocketError.TimedOut)))
{
// The socket is no longer a valid socket.
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::UpdateStatusAfterSocketError(socketException) Invalidating socket.");
- }
-
+ NetEventSource.Info(this, "Invalidating socket.");
SetToDisconnected();
}
}
@@ -6537,11 +5743,7 @@ namespace System.Net.Sockets
[System.Diagnostics.Conditional("TRACE_VERBOSE")]
internal void DebugMembers()
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("_handle:" + _handle.DangerousGetHandle().ToString("x"));
- GlobalLog.Print("_isConnected: " + _isConnected);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_handle:{_handle} _isConnected:{_isConnected}");
}
}
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs
index 3260501a85..ba00b3943a 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs
@@ -244,11 +244,11 @@ namespace System.Net.Sockets
{
if (_buffer != null)
{
- SocketsEventSource.Dump(_buffer, _offset, size);
+ NetEventSource.DumpArray(this, _buffer, _offset, size);
}
else if (_acceptBuffer != null)
{
- SocketsEventSource.Dump(_acceptBuffer, 0, size);
+ NetEventSource.DumpArray(this, _acceptBuffer, 0, size);
}
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
index 0482bd57f9..17179e6aa2 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
@@ -133,27 +133,12 @@ namespace System.Net.Sockets
if (_preAllocatedOverlapped != null)
{
overlapped = boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
- "::boundHandle#" + LoggingHash.HashString(boundHandle) +
- "::AllocateNativeOverlapped(m_PreAllocatedOverlapped=" +
- LoggingHash.HashString(_preAllocatedOverlapped) +
- "). Returned = " + ((IntPtr)overlapped).ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"boundHandle:{boundHandle}, PreAllocatedOverlapped:{_preAllocatedOverlapped}, Returned:{(IntPtr)overlapped}");
}
else
{
overlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, this, null);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
- "::boundHandle#" + LoggingHash.HashString(boundHandle) +
- "::AllocateNativeOverlapped(pinData=null)" +
- "). Returned = " + ((IntPtr)overlapped).ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"boundHandle:{boundHandle}, AllocateNativeOverlapped(pinData=null), Returned:{(IntPtr)overlapped}");
}
Debug.Assert(overlapped != null, "NativeOverlapped is null.");
@@ -904,13 +889,7 @@ namespace System.Net.Sockets
if (_buffer != null)
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _buffer);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
- "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer: " +
- LoggingHash.HashString(_preAllocatedOverlapped));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer:{_preAllocatedOverlapped}");
_pinnedSingleBuffer = _buffer;
_pinnedSingleBufferOffset = _offset;
@@ -924,13 +903,7 @@ namespace System.Net.Sockets
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, null);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
- "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: " +
- LoggingHash.HashString(_preAllocatedOverlapped));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: {_preAllocatedOverlapped}");
_pinnedSingleBuffer = null;
_pinnedSingleBufferOffset = 0;
@@ -945,13 +918,7 @@ namespace System.Net.Sockets
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _acceptBuffer);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
- "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=false: " +
- LoggingHash.HashString(_preAllocatedOverlapped));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped pinSingleBuffer=false:{_preAllocatedOverlapped}");
_pinnedAcceptBuffer = _acceptBuffer;
_ptrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_acceptBuffer, 0);
@@ -986,12 +953,7 @@ namespace System.Net.Sockets
// Pin buffers and fill in WSABuffer descriptor pointers and lengths.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedMultiple: new PreAllocatedOverlapped." +
- LoggingHash.HashString(_preAllocatedOverlapped));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped.{_preAllocatedOverlapped}");
for (int i = 0; i < tempList.Length; i++)
{
@@ -1033,12 +995,7 @@ namespace System.Net.Sockets
// Pin buffers.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print(
- "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSendPackets: new PreAllocatedOverlapped: " +
- LoggingHash.HashString(_preAllocatedOverlapped));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped:{_preAllocatedOverlapped}");
// Get pointer to native descriptor.
_ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0);
@@ -1079,17 +1036,17 @@ namespace System.Net.Sockets
switch (_pinState)
{
case PinState.SingleAcceptBuffer:
- SocketsEventSource.Dump(_acceptBuffer, 0, size);
+ NetEventSource.DumpArray(this, _acceptBuffer, 0, size);
break;
case PinState.SingleBuffer:
- SocketsEventSource.Dump(_buffer, _offset, size);
+ NetEventSource.DumpArray(this, _buffer, _offset, size);
break;
case PinState.MultipleBuffer:
foreach (WSABuffer wsaBuffer in _wsaBufferArray)
{
- SocketsEventSource.Dump(wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
+ NetEventSource.DumpArray(this, wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <= 0)
{
break;
@@ -1111,12 +1068,12 @@ namespace System.Net.Sockets
if (spe._buffer != null && spe._count > 0)
{
// This element is a buffer.
- SocketsEventSource.Dump(spe._buffer, spe._offset, Math.Min(spe._count, size));
+ NetEventSource.DumpArray(this, spe._buffer, spe._offset, Math.Min(spe._count, size));
}
else if (spe._filePath != null)
{
// This element is a file.
- SocketsEventSource.Log.NotLoggedFile(spe._filePath, LoggingHash.HashInt(_currentSocket), _completedOperation);
+ NetEventSource.NotLoggedFile(spe._filePath, _currentSocket, _completedOperation);
}
}
}
@@ -1254,16 +1211,10 @@ namespace System.Net.Sockets
private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
#if DEBUG
- GlobalLog.SetThreadSource(ThreadKinds.CompletionPort);
- using (GlobalLog.SetThreadKind(ThreadKinds.System))
+ DebugThreadTracking.SetThreadSource(ThreadKinds.CompletionPort);
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.System))
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Enter(
- "CompletionPortCallback",
- "errorCode: " + errorCode + ", numBytes: " + numBytes +
- ", overlapped#" + ((IntPtr)nativeOverlapped).ToString("x"));
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"errorCode:{errorCode}, numBytes:{numBytes}, overlapped:{(IntPtr)nativeOverlapped}");
#endif
SocketFlags socketFlags = SocketFlags.None;
SocketError socketError = (SocketError)errorCode;
@@ -1308,10 +1259,7 @@ namespace System.Net.Sockets
}
#if DEBUG
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Leave("CompletionPortCallback");
- }
+ NetEventSource.Exit(this);
}
#endif
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs
index 1c7f2d81c0..c19cd0f6be 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs
@@ -86,8 +86,6 @@ namespace System.Net.Sockets
private MultipleConnectAsync _multipleConnect;
- private static bool s_loggingEnabled = SocketsEventSource.Log.IsEnabled();
-
public SocketAsyncEventArgs()
{
InitializeInternals();
@@ -501,11 +499,7 @@ namespace System.Net.Sockets
// _currentSocket will only be null if _multipleConnect was set, so we don't have to check.
if (_currentSocket == null)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Assert("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
- }
- Debug.Fail("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
+ NetEventSource.Fail(this, "CurrentSocket and MultipleConnect both null!");
}
_currentSocket.Dispose();
}
@@ -677,7 +671,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
@@ -696,8 +690,7 @@ namespace System.Net.Sockets
{
_acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));
- if (s_loggingEnabled)
- SocketsEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
+ NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
}
else
{
@@ -710,7 +703,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
@@ -725,8 +718,7 @@ namespace System.Net.Sockets
// Mark socket connected.
if (socketError == SocketError.Success)
{
- if (s_loggingEnabled)
- SocketsEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
+ NetEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
_currentSocket.SetToConnected();
_connectSocket = _currentSocket;
@@ -743,7 +735,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
@@ -758,7 +750,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
@@ -787,7 +779,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
@@ -818,7 +810,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
@@ -833,7 +825,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogSendPacketsBuffers(bytesTransferred);
}
@@ -850,7 +842,7 @@ namespace System.Net.Sockets
if (bytesTransferred > 0)
{
// Log and Perf counters.
- if (s_loggingEnabled)
+ if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs b/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs
index 5f9b7a7b18..9944ad0bab 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs
@@ -687,10 +687,7 @@ namespace System.Net.Sockets
IntPtr.Zero);
}
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("Socket::Select() Interop.Winsock.select returns socketCount:" + socketCount);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Interop.Winsock.select returns socketCount:{socketCount}");
if ((SocketError)socketCount == SocketError.SocketError)
{
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs b/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs
index 839f32091c..c727063f88 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs
@@ -26,10 +26,7 @@ namespace System.Net.Sockets
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), family);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(this, family);
// Validate parameter
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
@@ -40,27 +37,18 @@ namespace System.Net.Sockets
_family = family;
InitializeClientSocket();
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), null);
- }
+ NetEventSource.Exit(this);
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), acceptedSocket);
- }
+ NetEventSource.Enter(this, acceptedSocket);
_clientSocket = acceptedSocket;
_active = true;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), null);
- }
+ NetEventSource.Exit(this);
}
// Used by the class to indicate that a connection has been made.
@@ -96,61 +84,37 @@ namespace System.Net.Sockets
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), address);
- }
+ NetEventSource.Enter(this, address);
IAsyncResult result = BeginConnectCore(address, port, requestCallback, state);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), null);
- }
-
+ NetEventSource.Exit(this);
return result;
}
public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), host);
- }
+ NetEventSource.Enter(this, (string)host);
IAsyncResult result = BeginConnectCore(host, port, requestCallback, state);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), null);
- }
-
+ NetEventSource.Exit(this);
return result;
}
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), addresses);
- }
+ NetEventSource.Enter(this, addresses);
IAsyncResult result = BeginConnectCore(addresses, port, requestCallback, state);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(BeginConnect), null);
- }
-
+ NetEventSource.Exit(this);
return result;
}
public void EndConnect(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(EndConnect), asyncResult);
- }
+ NetEventSource.Enter(this, asyncResult);
Socket s = Client;
if (s == null)
@@ -163,19 +127,13 @@ namespace System.Net.Sockets
_active = true;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(EndConnect), null);
- }
+ NetEventSource.Exit(this);
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(GetStream), "");
- }
+ NetEventSource.Enter(this);
if (_cleanedUp)
{
@@ -191,29 +149,18 @@ namespace System.Net.Sockets
_dataStream = new NetworkStream(Client, true);
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(GetStream), _dataStream);
- }
-
+ NetEventSource.Exit(this, _dataStream);
return _dataStream;
}
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Dispose), "");
- }
+ NetEventSource.Enter(this);
if (_cleanedUp)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Dispose), "");
- }
-
+ NetEventSource.Exit(this);
return;
}
@@ -251,10 +198,7 @@ namespace System.Net.Sockets
}
_cleanedUp = true;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Dispose), "");
- }
+ NetEventSource.Exit(this);
}
public void Dispose()
@@ -265,8 +209,8 @@ namespace System.Net.Sockets
~TcpClient()
{
#if DEBUG
- GlobalLog.SetThreadSource(ThreadKinds.Finalization);
- using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
+ DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
+ using (DebugThreadTracking.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
Dispose(false);
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.netstandard17.cs b/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.netstandard17.cs
index 1b6935117f..bb552dc5cb 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.netstandard17.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/TCPClient.netstandard17.cs
@@ -9,10 +9,7 @@ namespace System.Net.Sockets
// Initializes a new instance of the System.Net.Sockets.TcpClient class with the specified end point.
public TcpClient(IPEndPoint localEP)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), localEP);
- }
+ NetEventSource.Enter(this, localEP);
if (localEP == null)
{
@@ -25,20 +22,14 @@ namespace System.Net.Sockets
InitializeClientSocket();
Client.Bind(localEP);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), "");
- }
+ NetEventSource.Exit(this);
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on
// the specified host.
public TcpClient(string hostname, int port)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), hostname);
- }
+ NetEventSource.Enter(this, hostname);
if (hostname == null)
{
@@ -68,19 +59,13 @@ namespace System.Net.Sockets
throw;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(TcpClient), null);
- }
+ NetEventSource.Exit(this);
}
// Connects the Client to the specified port on the specified host.
public void Connect(string hostname, int port)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), hostname);
- }
+ NetEventSource.Enter(this, hostname);
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -106,19 +91,13 @@ namespace System.Net.Sockets
ConnectCore(hostname, port);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), null);
- }
+ NetEventSource.Exit(this);
}
// Connects the Client to the specified port on the specified host.
public void Connect(IPAddress address, int port)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), address);
- }
+ NetEventSource.Enter(this, address);
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -135,19 +114,13 @@ namespace System.Net.Sockets
IPEndPoint remoteEP = new IPEndPoint(address, port);
Connect(remoteEP);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), null);
- }
+ NetEventSource.Exit(this);
}
// Connect the Client to the specified end point.
public void Connect(IPEndPoint remoteEP)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), remoteEP);
- }
+ NetEventSource.Enter(this, remoteEP);
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
@@ -160,25 +133,16 @@ namespace System.Net.Sockets
Client.Connect(remoteEP);
_active = true;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), null);
- }
+ NetEventSource.Exit(this);
}
public void Connect(IPAddress[] ipAddresses, int port)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(Connect), ipAddresses);
- }
+ NetEventSource.Enter(this, ipAddresses);
ConnectCore(ipAddresses, port);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(Connect), null);
- }
+ NetEventSource.Exit(this);
}
public void Close()
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs b/src/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs
index 02a4043276..2a71fb0487 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs
@@ -21,32 +21,21 @@ namespace System.Net.Sockets
// Initializes a new instance of the TcpListener class with the specified local end point.
public TcpListener(IPEndPoint localEP)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpListener", localEP);
- }
-
+ NetEventSource.Enter(this, localEP);
if (localEP == null)
{
throw new ArgumentNullException(nameof(localEP));
}
_serverSocketEP = localEP;
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpListener", null);
- }
+ NetEventSource.Exit(this);
}
// Initializes a new instance of the TcpListener class that listens to the specified IP address
// and port.
public TcpListener(IPAddress localaddr, int port)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpListener", localaddr);
- }
-
+ NetEventSource.Enter(this, localaddr);
if (localaddr == null)
{
throw new ArgumentNullException(nameof(localaddr));
@@ -58,10 +47,7 @@ namespace System.Net.Sockets
_serverSocketEP = new IPEndPoint(localaddr, port);
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpListener", null);
- }
+ NetEventSource.Exit(this);
}
// Initiailizes a new instance of the TcpListener class that listens on the specified port.
@@ -146,15 +132,7 @@ namespace System.Net.Sockets
throw new ArgumentOutOfRangeException(nameof(backlog));
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Start", null);
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TCPListener::Start()");
- }
+ NetEventSource.Enter(this);
if (_serverSocket == null)
{
@@ -164,11 +142,7 @@ namespace System.Net.Sockets
// Already listening.
if (_active)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Start", null);
- }
-
+ NetEventSource.Exit(this);
return;
}
@@ -185,24 +159,13 @@ namespace System.Net.Sockets
}
_active = true;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Start", null);
- }
+ NetEventSource.Exit(this);
}
// Closes the network connection.
public void Stop()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Stop", null);
- }
-
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("TCPListener::Stop()");
- }
+ NetEventSource.Enter(this);
if (_serverSocket != null)
{
@@ -218,10 +181,7 @@ namespace System.Net.Sockets
_serverSocket.ExclusiveAddressUse = true;
}
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Stop", null);
- }
+ NetEventSource.Exit(this);
}
// Determine if there are pending connection requests.
@@ -238,10 +198,7 @@ namespace System.Net.Sockets
// Accept the first pending connection
public Socket AcceptSocket()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(AcceptSocket), null);
- }
+ NetEventSource.Enter(this);
if (!_active)
{
@@ -250,19 +207,13 @@ namespace System.Net.Sockets
Socket socket = _serverSocket.Accept();
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(AcceptSocket), socket);
- }
+ NetEventSource.Exit(this, socket);
return socket;
}
public TcpClient AcceptTcpClient()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, nameof(AcceptTcpClient), null);
- }
+ NetEventSource.Enter(this);
if (!_active)
{
@@ -272,19 +223,13 @@ namespace System.Net.Sockets
Socket acceptedSocket = _serverSocket.Accept();
TcpClient returnValue = new TcpClient(acceptedSocket);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, nameof(AcceptTcpClient), returnValue);
- }
+ NetEventSource.Exit(this, returnValue);
return returnValue;
}
public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginAcceptSocket", null);
- }
+ NetEventSource.Enter(this);
if (!_active)
{
@@ -292,20 +237,14 @@ namespace System.Net.Sockets
}
IAsyncResult result = _serverSocket.BeginAccept(callback, state);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginAcceptSocket", null);
- }
+ NetEventSource.Exit(this);
return result;
}
public Socket EndAcceptSocket(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndAcceptSocket", null);
- }
+ NetEventSource.Enter(this);
if (asyncResult == null)
{
@@ -322,20 +261,13 @@ namespace System.Net.Sockets
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndAcceptSocket", socket);
- }
-
+ NetEventSource.Exit(this, socket);
return socket;
}
public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginAcceptTcpClient", null);
- }
+ NetEventSource.Enter(this);
if (!_active)
{
@@ -343,20 +275,13 @@ namespace System.Net.Sockets
}
IAsyncResult result = _serverSocket.BeginAccept(callback, state);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginAcceptTcpClient", null);
- }
-
+ NetEventSource.Exit(this, result);
return result;
}
public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndAcceptTcpClient", null);
- }
+ NetEventSource.Enter(this);
if (asyncResult == null)
{
@@ -372,12 +297,7 @@ namespace System.Net.Sockets
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
-
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndAcceptTcpClient", socket);
- }
-
+ NetEventSource.Exit(this, socket);
return new TcpClient(socket);
}
@@ -401,10 +321,7 @@ namespace System.Net.Sockets
// This creates a TcpListener that listens on both IPv4 and IPv6 on the given port.
public static TcpListener Create(int port)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.Socket, "TcpListener.Create", "Port: " + port, null);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(null, port);
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
@@ -414,10 +331,7 @@ namespace System.Net.Sockets
TcpListener listener = new TcpListener(IPAddress.IPv6Any, port);
listener.Server.DualMode = true;
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.Socket, "TcpListener.Create", "Port: " + port, null);
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(null, port);
return listener;
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs b/src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs
index 179ceb4666..d1a4db5b98 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs
@@ -233,11 +233,7 @@ namespace System.Net.Sockets
{
if (disposing)
{
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("UdpClient::Dispose()");
- }
-
+ NetEventSource.Info(this);
FreeResources();
GC.SuppressFinalize(this);
}
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/LoggingTest.cs b/src/System.Net.Sockets/tests/FunctionalTests/LoggingTest.cs
new file mode 100644
index 0000000000..1e35fbc211
--- /dev/null
+++ b/src/System.Net.Sockets/tests/FunctionalTests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.Sockets.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(Socket).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-Sockets", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("42c8027b-f048-58d2-537d-a4a9d5ee7038"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj b/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj
index 6fdc3061f0..931480d003 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj
+++ b/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj
@@ -95,6 +95,9 @@
<Link>Common\System\Threading\Tasks\TaskToApm.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup Condition="'$(NugetTargetMoniker)' == ''">
+ <Compile Include="LoggingTest.cs" />
+ </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\System.Security.Principal.Windows\pkg\System.Security.Principal.Windows.pkgproj" />
<ProjectReference Include="..\..\pkg\System.Net.Sockets.pkgproj">
diff --git a/src/System.Net.WebHeaderCollection/src/System.Net.WebHeaderCollection.csproj b/src/System.Net.WebHeaderCollection/src/System.Net.WebHeaderCollection.csproj
index 0e39bc0a38..49b6960a80 100644
--- a/src/System.Net.WebHeaderCollection/src/System.Net.WebHeaderCollection.csproj
+++ b/src/System.Net.WebHeaderCollection/src/System.Net.WebHeaderCollection.csproj
@@ -4,6 +4,7 @@
<PropertyGroup>
<ProjectGuid>{5EE76DCC-9FD5-47FD-AB45-BD0F0857740F}</ProjectGuid>
<AssemblyName>System.Net.WebHeaderCollection</AssemblyName>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'net463'">true</IsPartialFacadeAssembly>
<ResourcesSourceOutputDirectory Condition="'$(TargetGroup)' == 'net463'">None</ResourcesSourceOutputDirectory>
<NuGetTargetMoniker Condition="'$(TargetGroup)' == ''">.NETStandard,Version=v1.7</NuGetTargetMoniker>
@@ -19,6 +20,7 @@
<Compile Include="System\Net\HttpRequestHeader.cs" />
<Compile Include="System\Net\HeaderInfo.cs" />
<Compile Include="System\Net\HeaderInfoTable.cs" />
+ <Compile Include="System\Net\NetEventSource.WebHeaderCollection.cs" />
<Compile Include="$(CommonPath)\System\StringExtensions.cs">
<Link>Common\System\StringExtensions.cs</Link>
</Compile>
@@ -31,11 +33,8 @@
<Compile Include="$(CommonPath)\System\Net\InternalException.cs">
<Link>Common\System\Net\InternalException.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\GlobalLog.cs">
- <Link>Common\System\Net\Logging\GlobalLog.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\EventSourceLogging.cs">
- <Link>Common\System\Net\Logging\EventSourceLogging.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'net463'">
diff --git a/src/System.Net.WebHeaderCollection/src/System/Net/NetEventSource.WebHeaderCollection.cs b/src/System.Net.WebHeaderCollection/src/System/Net/NetEventSource.WebHeaderCollection.cs
new file mode 100644
index 0000000000..8a0e4d1397
--- /dev/null
+++ b/src/System.Net.WebHeaderCollection/src/System/Net/NetEventSource.WebHeaderCollection.cs
@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-WebHeaderCollection")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs b/src/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs
index 940768e7f8..b4f7efaa00 100644
--- a/src/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs
+++ b/src/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs
@@ -44,10 +44,7 @@ namespace System.Net
{
string headerName = serializationInfo.GetString(i.ToString(NumberFormatInfo.InvariantInfo));
string headerValue = serializationInfo.GetString((i + count).ToString(NumberFormatInfo.InvariantInfo));
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WebHeaderCollection::.ctor(ISerializable) calling InnerCollection.Add() key:[" + headerName + "], value:[" + headerValue + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"calling InnerCollection.Add() key:[{headerName}], value:[{headerValue}]");
InnerCollection.Add(headerName, headerValue);
}
}
@@ -152,10 +149,7 @@ namespace System.Net
name = HttpValidationHelpers.CheckBadHeaderNameChars(name);
ThrowOnRestrictedHeader(name);
value = HttpValidationHelpers.CheckBadHeaderValueChars(value);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WebHeaderCollection::Set() calling InnerCollection.Set() key:[" + name + "], value:[" + value + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"calling InnerCollection.Set() key:[{name}], value:[{value}]");
if (_type == WebHeaderCollectionType.WebResponse)
{
if (value != null && value.Length > ushort.MaxValue)
@@ -328,10 +322,7 @@ namespace System.Net
name = HttpValidationHelpers.CheckBadHeaderNameChars(name);
ThrowOnRestrictedHeader(name);
value = HttpValidationHelpers.CheckBadHeaderValueChars(value);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WebHeaderCollection::Add(" + header + ") calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Add({header}) calling InnerCollection.Add() key:[{name}], value:[{value}]");
if (_type == WebHeaderCollectionType.WebResponse)
{
if (value != null && value.Length > ushort.MaxValue)
@@ -348,10 +339,7 @@ namespace System.Net
name = HttpValidationHelpers.CheckBadHeaderNameChars(name);
ThrowOnRestrictedHeader(name);
value = HttpValidationHelpers.CheckBadHeaderValueChars(value);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WebHeaderCollection::Add() calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"calling InnerCollection.Add() key:[{name}], value:[{value}]");
if (_type == WebHeaderCollectionType.WebResponse)
{
if (value != null && value.Length > ushort.MaxValue)
@@ -367,10 +355,7 @@ namespace System.Net
{
name = HttpValidationHelpers.CheckBadHeaderNameChars(name);
value = HttpValidationHelpers.CheckBadHeaderValueChars(value);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WebHeaderCollection::AddWithoutValidate() calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"calling InnerCollection.Add() key:[{name}], value:[{value}]");
if (_type == WebHeaderCollectionType.WebResponse)
{
if (value != null && value.Length > ushort.MaxValue)
@@ -421,10 +406,7 @@ namespace System.Net
}
ThrowOnRestrictedHeader(name);
name = HttpValidationHelpers.CheckBadHeaderNameChars(name);
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WebHeaderCollection::Remove() calling InnerCollection.Remove() key:[" + name + "]");
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"calling InnerCollection.Remove() key:[{name}]");
if (_innerCollection != null)
{
InvalidateCachedArrays();
@@ -467,10 +449,7 @@ namespace System.Net
}
sb.Append("\r\n");
- if (GlobalLog.IsEnabled)
- {
- GlobalLog.Print("WebHeaderCollection::ToString: \r\n" + sb.ToString());
- }
+ if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ToString: {sb}");
return sb.ToString();
}
diff --git a/src/System.Net.WebHeaderCollection/tests/LoggingTest.cs b/src/System.Net.WebHeaderCollection/tests/LoggingTest.cs
new file mode 100644
index 0000000000..0b1051a988
--- /dev/null
+++ b/src/System.Net.WebHeaderCollection/tests/LoggingTest.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using Xunit;
+
+namespace System.Net.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(WebHeaderCollection).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-WebHeaderCollection", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("fd36452f-9f2b-5850-d212-6c436231e3dc"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj b/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj
index 5de8c2675c..d21f778bc3 100644
--- a/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj
+++ b/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj
@@ -16,6 +16,7 @@
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == ''">
+ <Compile Include="LoggingTest.cs" />
<Compile Include="WebHeaderCollectionTest.netstandard17.cs" />
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
<Link>Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
diff --git a/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj b/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj
index 0dd152c80e..593f254a77 100644
--- a/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj
+++ b/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj
@@ -38,12 +38,10 @@
<ItemGroup Condition="'$(TargetGroup)' != 'net46'">
<Compile Include="System\Net\WebSockets\ClientWebSocket.cs" />
<Compile Include="System\Net\WebSockets\ClientWebSocketOptions.cs" />
+ <Compile Include="System\Net\WebSockets\NetEventSource.WebSockets.cs" />
<!-- Common -->
- <Compile Include="$(CommonPath)\System\Net\Logging\LoggingHash.cs">
- <Link>Common\System\Net\Logging\LoggingHash.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.cs">
- <Link>Common\System\Net\Logging\NetEventSource.cs</Link>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\UriScheme.cs">
<Link>Common\System\Net\UriScheme.cs</Link>
diff --git a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs
index 547a701b7e..3dd61abf23 100644
--- a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs
+++ b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs
@@ -27,20 +27,13 @@ namespace System.Net.WebSockets
public ClientWebSocket()
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Enter(NetEventSource.ComponentType.WebSocket, this, ".ctor", null);
- }
-
+ NetEventSource.Enter(this);
WebSocketHandle.CheckPlatformSupport();
_state = (int)InternalState.Created;
_options = new ClientWebSocketOptions();
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exit(NetEventSource.ComponentType.WebSocket, this, ".ctor", null);
- }
+ NetEventSource.Exit(this);
}
#region Properties
@@ -160,10 +153,7 @@ namespace System.Net.WebSockets
}
catch (Exception ex)
{
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.WebSocket, this, nameof(ConnectAsync), ex);
- }
+ NetEventSource.Error(this, ex);
throw;
}
}
diff --git a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/NetEventSource.WebSockets.cs b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/NetEventSource.WebSockets.cs
new file mode 100644
index 0000000000..ca940c7ae2
--- /dev/null
+++ b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/NetEventSource.WebSockets.cs
@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+
+namespace System.Net
+{
+ [EventSource(Name = "Microsoft-System-Net-WebSockets-Client")]
+ internal sealed partial class NetEventSource { }
+}
diff --git a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Win32.cs b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Win32.cs
index 2a1525b82a..6ecee52dc2 100644
--- a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Win32.cs
+++ b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Win32.cs
@@ -55,11 +55,8 @@ namespace System.Net.WebSockets
}
catch (Win32Exception ex)
{
- WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, ex);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.WebSocket, this, "ConnectAsync", wex);
- }
+ var wex = new WebSocketException(SR.net_webstatus_ConnectFailure, ex);
+ NetEventSource.Error(_webSocket, wex);
throw wex;
}
}
diff --git a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.WinRT.cs b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.WinRT.cs
index f465a042d0..8863c472ce 100644
--- a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.WinRT.cs
+++ b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.WinRT.cs
@@ -48,11 +48,7 @@ namespace System.Net.WebSockets
WebErrorStatus status = RTWebSocketError.GetStatus(ex.HResult);
var inner = new Exception(status.ToString(), ex);
WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, inner);
- if (NetEventSource.Log.IsEnabled())
- {
- NetEventSource.Exception(NetEventSource.ComponentType.WebSocket, this, "ConnectAsync", wex);
- }
-
+ NetEventSource.Error(_webSocket, wex);
throw wex;
}
}
diff --git a/src/System.Net.WebSockets.Client/tests/LoggingTest.cs b/src/System.Net.WebSockets.Client/tests/LoggingTest.cs
new file mode 100644
index 0000000000..6425789002
--- /dev/null
+++ b/src/System.Net.WebSockets.Client/tests/LoggingTest.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics.Tracing;
+using System.Reflection;
+using Xunit;
+
+namespace System.Net.WebSockets.Tests
+{
+ public static class LoggingTest
+ {
+ [Fact]
+ public static void EventSource_ExistsWithCorrectId()
+ {
+ Type esType = typeof(ClientWebSocket).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
+ Assert.NotNull(esType);
+ Assert.Equal("Microsoft-System-Net-WebSockets-Client", EventSource.GetName(esType));
+ Assert.Equal(Guid.Parse("71cddde3-cf58-52d5-094f-927828a09337"), EventSource.GetGuid(esType));
+ }
+ }
+}
diff --git a/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj b/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj
index f1c2bc97d8..935f1a3b89 100644
--- a/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj
+++ b/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj
@@ -37,6 +37,7 @@
<Compile Include="ClientWebSocketUnitTest.cs" />
<Compile Include="CloseTest.cs" />
<Compile Include="ConnectTest.cs" />
+ <Compile Include="LoggingTest.cs" />
<Compile Include="KeepAliveTest.cs" />
<Compile Include="ResourceHelper.cs" />
<Compile Include="SendReceiveTest.cs" />