diff --git a/src/Microsoft.SqlTools.Hosting/Utility/SqlClientEventListener.cs b/src/Microsoft.SqlTools.Hosting/Utility/SqlClientEventListener.cs new file mode 100644 index 00000000..d517c3af --- /dev/null +++ b/src/Microsoft.SqlTools.Hosting/Utility/SqlClientEventListener.cs @@ -0,0 +1,51 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using System.Diagnostics.Tracing; +using Microsoft.SqlTools.Utility; + +namespace Microsoft.SqlTools.ServiceLayer.Utility +{ + + /// + /// This listener class will listen for events from the SqlClientEventSource class + /// and forward them to the logger. + /// + internal class SqlClientListener : EventListener + { + protected override void OnEventSourceCreated(EventSource eventSource) + { + // Only enable events from SqlClientEventSource. + if (eventSource.Name.Equals("Microsoft.Data.SqlClient.EventSource")) + { + // Use EventKeyWord 2 to capture basic application flow events. + // See https://docs.microsoft.com/sql/connect/ado-net/enable-eventsource-tracing for all available keywords. + EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)2); + } + } + + /// + /// This callback runs whenever an event is written by SqlClientEventSource. + /// Event data is accessed through the EventWrittenEventArgs parameter. + /// + /// The data for the event + protected override void OnEventWritten(EventWrittenEventArgs eventData) + { + if (eventData.Payload == null) + { + return; + } + foreach (object payload in eventData.Payload) + { + if (payload != null) + { + Logger.Verbose(payload.ToString()); + } + + } + + } + } +} diff --git a/src/Microsoft.SqlTools.ServiceLayer/Program.cs b/src/Microsoft.SqlTools.ServiceLayer/Program.cs index a5f1e711..3a0a6368 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Program.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Program.cs @@ -23,6 +23,7 @@ namespace Microsoft.SqlTools.ServiceLayer /// internal static void Main(string[] args) { + SqlClientListener? sqlClientListener = null; try { // read command-line arguments @@ -39,6 +40,12 @@ namespace Microsoft.SqlTools.ServiceLayer } Logger.Initialize(tracingLevel: commandOptions.TracingLevel, logFilePath: logFilePath, traceSource: "sqltools", commandOptions.AutoFlushLog); + // Only enable SQL Client logging when verbose or higher to avoid extra overhead when the + // detailed logging it provides isn't needed + if (Logger.TracingLevel.HasFlag(SourceLevels.Verbose)) + { + sqlClientListener = new SqlClientListener(); + } // set up the host details and profile paths var hostDetails = new HostDetails(version: new Version(1, 0)); @@ -73,6 +80,7 @@ namespace Microsoft.SqlTools.ServiceLayer finally { Logger.Close(); + sqlClientListener?.Dispose(); } }