From 40c0521f93ac463e704b0a23a84410b44e36e1d4 Mon Sep 17 00:00:00 2001 From: Dan Jagnow Date: Wed, 31 Mar 2021 16:20:04 -0500 Subject: [PATCH 1/5] Updated SwqlStudio.csproj to use Serilog for logging Updated SwqlStudio.csproj to eliminate the SolarWinds.Logging dependency (and a transitive dependency on log4net. It is configured instead to use Microsoft.Extensions.Logging and Serilog for logging. The log file path is no longer configurable via the App.config file in this approach. Updated the installer to add the new dependencies, including transitive dependencies. The SolarWinds.Logging and log4net assemblies are still deployed since SolarWinds.InformationService.Contract still depends on them. This is not ready for merging. --- Src/Install/Product.wxs | 17 +++++++++++ Src/SwqlStudio/MainForm.cs | 7 +++-- .../ObjectExplorer/ObjectExplorer.cs | 6 ++-- Src/SwqlStudio/Playback/PlaybackManager.cs | 7 +++-- .../CustomCertificateValidator.cs | 6 ++-- Src/SwqlStudio/Program.cs | 18 +++++++++--- .../Subscriptions/SubscriptionManager.cs | 8 +++--- .../Subscriptions/SubscriptionServiceHost.cs | 16 +++++------ Src/SwqlStudio/SwqlStudio.csproj | 4 ++- Src/SwqlStudio/TabsFactory.cs | 5 ++-- Src/SwqlStudio/app.config | 28 ------------------- 11 files changed, 63 insertions(+), 59 deletions(-) diff --git a/Src/Install/Product.wxs b/Src/Install/Product.wxs index 204fbe36c..edaf0ee1e 100644 --- a/Src/Install/Product.wxs +++ b/Src/Install/Product.wxs @@ -120,11 +120,26 @@ + + + + + + + + + + + + + + + @@ -133,6 +148,8 @@ + + diff --git a/Src/SwqlStudio/MainForm.cs b/Src/SwqlStudio/MainForm.cs index e03aabbf0..1ebf97e5b 100644 --- a/Src/SwqlStudio/MainForm.cs +++ b/Src/SwqlStudio/MainForm.cs @@ -3,6 +3,7 @@ using System.Linq; using System.ServiceModel; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using SolarWinds.InformationService.Contract2; using SolarWinds.InformationService.InformationServiceClient; using SwqlStudio.Metadata; @@ -17,7 +18,7 @@ namespace SwqlStudio UseSynchronizationContext = false)] internal partial class MainForm : Form, IApplicationService { - private static readonly SolarWinds.Logging.Log log = new SolarWinds.Logging.Log(); + private static readonly ILogger log = Program.LoggerFactory.CreateLogger(); private ServerList serverList; private readonly BindingList connectionsDataSource = new BindingList(); private ConnectionsManager connectionsManager; @@ -137,7 +138,7 @@ private void menuFileNew_Click(object sender, EventArgs e) } catch (Exception ex) { - log.Error("Failed to connect", ex); + log.LogError(ex, "Failed to connect"); var msg = $"Unable to connect to Information Service.\n{ex.Message}"; MessageBox.Show(msg, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -296,7 +297,7 @@ private void enumEntitiesToolStripMenuItem_Click(object sender, EventArgs e) } catch (FaultException ex) { - log.Error("Failed to connect", ex); + log.LogError(ex, "Failed to connect"); errorMsg = ex.Detail.Message; } catch (Exception ex) diff --git a/Src/SwqlStudio/ObjectExplorer/ObjectExplorer.cs b/Src/SwqlStudio/ObjectExplorer/ObjectExplorer.cs index 7144ca82f..b5d02d25c 100644 --- a/Src/SwqlStudio/ObjectExplorer/ObjectExplorer.cs +++ b/Src/SwqlStudio/ObjectExplorer/ObjectExplorer.cs @@ -8,7 +8,7 @@ using System.Text; using System.Threading; using System.Windows.Forms; -using SolarWinds.Logging; +using Microsoft.Extensions.Logging; using SwqlStudio.Filtering; using SwqlStudio.Metadata; using SwqlStudio.Utils; @@ -20,7 +20,7 @@ namespace SwqlStudio.ObjectExplorer { internal class ObjectExplorer : Control { - private static readonly Log log = new Log(); + private static readonly ILogger log = Program.LoggerFactory.CreateLogger(); private readonly SearchTextBox _treeSearch; private readonly TreeView _tree; @@ -411,7 +411,7 @@ public void AddServer(IMetadataProvider provider, ConnectionInfo connection) } catch (ApplicationException e) { - log.Info("Exception checking if we can create subscriptions.", e); + log.LogInformation(e, "Exception checking if we can create subscriptions."); } if (dt != null && (dt.Rows.Count == 1 && dt.Columns.Count == 1)) diff --git a/Src/SwqlStudio/Playback/PlaybackManager.cs b/Src/SwqlStudio/Playback/PlaybackManager.cs index db2cf49dd..516039f76 100644 --- a/Src/SwqlStudio/Playback/PlaybackManager.cs +++ b/Src/SwqlStudio/Playback/PlaybackManager.cs @@ -5,12 +5,13 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading; +using Microsoft.Extensions.Logging; namespace SwqlStudio.Playback { internal class PlaybackManager { - private static readonly SolarWinds.Logging.Log log = new SolarWinds.Logging.Log(); + private static readonly ILogger log = Program.LoggerFactory.CreateLogger(); public static void StartPlayback(PlaybackItem file) { @@ -27,7 +28,7 @@ private static void RunPlaybackFile(object f) var playbackItem = f as PlaybackItem; if (playbackItem != null) { - log.DebugFormat("Playing back file: {0}", playbackItem.FileName); + log.LogDebug("Playing back file: {fileName}", playbackItem.FileName); var sb = new StringBuilder(); using (var sr = new StreamReader(playbackItem.FileName)) { @@ -53,7 +54,7 @@ private static void RunPlaybackFile(object f) } catch (Exception e) { - log.Error(e); + log.LogError(e, "Error while running playback file."); } } diff --git a/Src/SwqlStudio/ProductSpecific/CustomCertificateValidator.cs b/Src/SwqlStudio/ProductSpecific/CustomCertificateValidator.cs index 64a58398c..4e4ebe8ce 100644 --- a/Src/SwqlStudio/ProductSpecific/CustomCertificateValidator.cs +++ b/Src/SwqlStudio/ProductSpecific/CustomCertificateValidator.cs @@ -1,18 +1,18 @@ using System; using System.IdentityModel.Selectors; using System.Security.Cryptography.X509Certificates; -using SolarWinds.Logging; +using Microsoft.Extensions.Logging; using SwqlStudio.Properties; namespace SwqlStudio.ProductSpecific { public class CustomCertificateValidator : X509CertificateValidator { - private static readonly Log log = new Log(); + private static readonly ILogger log = Program.LoggerFactory.CreateLogger(); public override void Validate(X509Certificate2 certificate) { - log.InfoFormat("Allowing certificate {0}", certificate); + log.LogInformation("Allowing certificate {certificate}", certificate); X509Certificate2Collection certs = LoadCertificates(); ValidateCertPresent(certs); X509Certificate2 cert = certs[0]; diff --git a/Src/SwqlStudio/Program.cs b/Src/SwqlStudio/Program.cs index d5b39a6f2..c80ba2cde 100644 --- a/Src/SwqlStudio/Program.cs +++ b/Src/SwqlStudio/Program.cs @@ -3,13 +3,17 @@ using System.IO; using System.Linq; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using Serilog; using SwqlStudio.Properties; namespace SwqlStudio { internal static class Program { - private static readonly SolarWinds.Logging.Log log = new SolarWinds.Logging.Log(); + private static Microsoft.Extensions.Logging.ILogger log; + + internal static ILoggerFactory LoggerFactory { get; } = new LoggerFactory(); /// /// The main entry point for the application. @@ -17,7 +21,13 @@ internal static class Program [STAThread] private static void Main() { - SolarWinds.Logging.Log.Configure(string.Empty); + // Configure Serilog logging. + string logFilePath = Environment.ExpandEnvironmentVariables(@"%ALLUSERSPROFILE%\Application Data\SolarWinds\Logs\SwqlStudio.log"); + var loggerConfig = new LoggerConfiguration() + .WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day) + .CreateLogger(); + LoggerFactory.AddSerilog(loggerConfig); + log = LoggerFactory.CreateLogger("Program"); AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException; if (Settings.Default.UpdateRequired) @@ -41,7 +51,7 @@ private static void Main() private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject is Exception) - log.Error("Unhandled exception", (Exception)e.ExceptionObject); + log.LogError((Exception)e.ExceptionObject, "Unhandled exception"); } private static void SearchAndCopyLastUserConfig(Version currentVersion) @@ -86,7 +96,7 @@ orderby dirVer.Ver descending } catch (Exception ex) { - log.Error("An error occurred while trying to upgrade user specific settings for the new version.", ex); + log.LogError(ex, "An error occurred while trying to upgrade user specific settings for the new version."); } } diff --git a/Src/SwqlStudio/Subscriptions/SubscriptionManager.cs b/Src/SwqlStudio/Subscriptions/SubscriptionManager.cs index 24a6925ee..7503b0f90 100644 --- a/Src/SwqlStudio/Subscriptions/SubscriptionManager.cs +++ b/Src/SwqlStudio/Subscriptions/SubscriptionManager.cs @@ -4,9 +4,9 @@ using System.Linq; using System.ServiceModel; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using SolarWinds.InformationService.Contract2; using SolarWinds.InformationService.Contract2.PubSub; -using SolarWinds.Logging; namespace SwqlStudio.Subscriptions { @@ -14,7 +14,7 @@ namespace SwqlStudio.Subscriptions public class SubscriptionManager : INotificationSubscriber { - private readonly static Log log = new Log(); + private readonly static ILogger log = Program.LoggerFactory.CreateLogger(); private readonly ConcurrentDictionary proxies = new ConcurrentDictionary(); private readonly SubscriptionServiceHost _subscriptionListener; @@ -39,12 +39,12 @@ public void Unsubscribe(ConnectionInfo connectionInfo, string subscriptionUri, S } catch (FaultException ex) { - log.Debug($"Unable to unsubscribe {subscriptionUri}. Must have been deleted already", ex); + log.LogDebug(ex, $"Unable to unsubscribe {subscriptionUri}. Must have been deleted already"); } catch (CommunicationException ex) { // also in case connection already disposed - log.Debug("Unable to unsubscribe due to communication error.", ex); + log.LogDebug(ex, "Unable to unsubscribe due to communication error."); } } diff --git a/Src/SwqlStudio/Subscriptions/SubscriptionServiceHost.cs b/Src/SwqlStudio/Subscriptions/SubscriptionServiceHost.cs index 542f8df87..06f257c1b 100644 --- a/Src/SwqlStudio/Subscriptions/SubscriptionServiceHost.cs +++ b/Src/SwqlStudio/Subscriptions/SubscriptionServiceHost.cs @@ -9,17 +9,17 @@ using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; +using Microsoft.Extensions.Logging; using Security.Cryptography; using Security.Cryptography.X509Certificates; using SolarWinds.InformationService.Contract2; using SolarWinds.InformationService.Contract2.PubSub; -using SolarWinds.Logging; namespace SwqlStudio.Subscriptions { internal class SubscriptionServiceHost { - private readonly static Log log = new Log(); + private readonly static ILogger log = Program.LoggerFactory.CreateLogger(); private readonly List subscriberHosts = new List(); private readonly INotificationSubscriber subscriber; private readonly string httpAddress; @@ -98,9 +98,9 @@ public void OpenSubscriber() if (IsListening()) return; - log.InfoFormat("Opening subscriber endpoint at {0}", netTcpAddress); + log.LogInformation("Opening subscriber endpoint at {netTcpAddress}", netTcpAddress); - log.InfoFormat("Opening http subscriber endpoint at {0}", httpAddress); + log.LogInformation("Opening http subscriber endpoint at {httpAddress}", httpAddress); NotificationSubscriber notificationSubscriber = new NotificationSubscriber(); notificationSubscriber.IndicationReceived += OnIndication; @@ -123,18 +123,18 @@ public void OpenSubscriber() subscriberHosts.Add(host); } - log.Info("Http Subscriber endpoint opened"); + log.LogInformation("Http Subscriber endpoint opened"); } catch (Exception ex) { - log.ErrorFormat("Exception opening subscriber host with address {0}.\n{1}", httpAddress, ex); + log.LogError(ex, $"Exception opening subscriber host with address {httpAddress}.", httpAddress); } foreach (ServiceHost serviceHost in subscriberHosts) { foreach (ChannelDispatcherBase channelDispatcher in serviceHost.ChannelDispatchers) { - log.InfoFormat("Listening on {0}", channelDispatcher.Listener.Uri.AbsoluteUri); + log.LogInformation("Listening on {uri}", channelDispatcher.Listener.Uri.AbsoluteUri); } } @@ -148,7 +148,7 @@ private void OnIndication(string subscriptionId, string indicationType, Property public void CloseSubscriber() { - using (log.Block()) + using (log.BeginScope(nameof(CloseSubscriber))) { subscriberHosts.ForEach(host => host.Close()); subscriberHosts.Clear(); diff --git a/Src/SwqlStudio/SwqlStudio.csproj b/Src/SwqlStudio/SwqlStudio.csproj index 1d675281a..1ad4303c6 100644 --- a/Src/SwqlStudio/SwqlStudio.csproj +++ b/Src/SwqlStudio/SwqlStudio.csproj @@ -27,6 +27,9 @@ + + + @@ -59,7 +62,6 @@ - diff --git a/Src/SwqlStudio/TabsFactory.cs b/Src/SwqlStudio/TabsFactory.cs index 09b8df398..1d0ca0586 100644 --- a/Src/SwqlStudio/TabsFactory.cs +++ b/Src/SwqlStudio/TabsFactory.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using SwqlStudio.Metadata; using SwqlStudio.Properties; using WeifenLuo.WinFormsUI.Docking; @@ -9,7 +10,7 @@ namespace SwqlStudio { internal class TabsFactory : ITabsFactory { - private static readonly SolarWinds.Logging.Log log = new SolarWinds.Logging.Log(); + private static readonly ILogger log = Program.LoggerFactory.CreateLogger(); private readonly ServerList serverList; private readonly QueriesDockPanel dockPanel; @@ -45,7 +46,7 @@ public void OpenQueryTab(string text, ConnectionInfo info) } catch (Exception ex) { - log.Error("Failed to connect", ex); + log.LogError(ex, "Failed to connect"); var msg = $"Unable to connect to Information Service.\n{ex.Message}"; MessageBox.Show(msg, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/Src/SwqlStudio/app.config b/Src/SwqlStudio/app.config index b8546368e..4f0789942 100644 --- a/Src/SwqlStudio/app.config +++ b/Src/SwqlStudio/app.config @@ -1,7 +1,6 @@ -
@@ -214,31 +213,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - From fe6ffab8c46eaf06d8707861666d3abb2a4ba6e1 Mon Sep 17 00:00:00 2001 From: Dan Jagnow Date: Wed, 31 Mar 2021 16:40:32 -0500 Subject: [PATCH 2/5] Removed SolarWinds.Logging from SwisPowerShell Removed SolarWinds.Logging references from SwisPowerShell. It was only referenced in the CustomCertificateValidator class for a single log entry, and logging was never configured. --- Src/SwisPowerShell/CustomCertificateValidator.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Src/SwisPowerShell/CustomCertificateValidator.cs b/Src/SwisPowerShell/CustomCertificateValidator.cs index ec401067e..0c430eb4f 100644 --- a/Src/SwisPowerShell/CustomCertificateValidator.cs +++ b/Src/SwisPowerShell/CustomCertificateValidator.cs @@ -1,18 +1,15 @@ using System; using System.IdentityModel.Selectors; using System.Security.Cryptography.X509Certificates; -using SolarWinds.Logging; namespace SwisPowerShell { public class CustomCertificateValidator : X509CertificateValidator { private const string subjectName = "SolarWinds-Orion"; - private static readonly Log log = new Log(); public override void Validate(X509Certificate2 certificate) { - log.InfoFormat("Allowing certificate {0}", certificate); X509Certificate2Collection certs = LoadCertificates(); ValidateCertPresent(certs); X509Certificate2 cert = certs[0]; From 724cede229615321428c393adac7789c1b31ee88 Mon Sep 17 00:00:00 2001 From: Dan Jagnow Date: Wed, 31 Mar 2021 17:42:41 -0500 Subject: [PATCH 3/5] Updated SolarWinds.InformationService.Contract logging Updated SolarWinds.InformationService.Contract to use Microsoft.Extensions.Logging instead of SolarWinds.Logging. Updated classes in SwqlStudio and SwisPowerShell accordingly. Note that SwisPowerShell uses null loggers after this change. --- Src/Contract/InfoServiceProxy.cs | 100 ++++++++++-------- .../InformationServiceConnection.cs | 80 ++------------ Src/Contract/InformationServiceContext.cs | 7 +- Src/Contract/InformationServiceQuery.cs | 10 +- Src/Contract/InformationServiceQueryOfT.cs | 9 +- ...arWinds.InformationService.Contract.csproj | 11 +- Src/SwisPowerShell/ConnectSwis.cs | 12 ++- Src/SwisPowerShell/GetSwisData.cs | 5 +- Src/SwqlStudio/ConnectionInfo.cs | 4 +- Src/SwqlStudio/InfoServiceBase.cs | 4 +- 10 files changed, 97 insertions(+), 145 deletions(-) diff --git a/Src/Contract/InfoServiceProxy.cs b/Src/Contract/InfoServiceProxy.cs index ca5d8323f..a93bc569a 100644 --- a/Src/Contract/InfoServiceProxy.cs +++ b/Src/Contract/InfoServiceProxy.cs @@ -3,13 +3,13 @@ using System.ServiceModel; using System.ServiceModel.Channels; using System.Xml; -using SolarWinds.Logging; +using Microsoft.Extensions.Logging; namespace SolarWinds.InformationService.Contract2 { public class InfoServiceProxy : IStreamInformationService, IDisposable { - private readonly static Log _log = new Log(); + private readonly ILogger _log; private static readonly TimeSpan longRunningQueryTime = TimeSpan.FromSeconds(15); private IStreamInformationServiceChannel _infoService; @@ -35,8 +35,10 @@ public IClientChannel ClientChannel #region Constructors - public InfoServiceProxy(string endpointConfiguration) + public InfoServiceProxy(ILogger logger, string endpointConfiguration) { + _log = logger ?? throw new ArgumentNullException(nameof(logger)); + if (endpointConfiguration == null) throw new ArgumentNullException(nameof(endpointConfiguration)); @@ -45,8 +47,8 @@ public InfoServiceProxy(string endpointConfiguration) FixBinding(); } - public InfoServiceProxy(string endpointConfiguration, ServiceCredentials credentials) - : this(endpointConfiguration) + public InfoServiceProxy(ILogger logger, string endpointConfiguration, ServiceCredentials credentials) + : this(logger, endpointConfiguration) { if (credentials == null) throw new ArgumentNullException(nameof(credentials)); @@ -54,8 +56,10 @@ public InfoServiceProxy(string endpointConfiguration, ServiceCredentials credent credentials.ApplyTo(ChannelFactory); } - public InfoServiceProxy(string endpointConfiguration, string remoteAddress) + public InfoServiceProxy(ILogger logger, string endpointConfiguration, string remoteAddress) { + _log = logger ?? throw new ArgumentNullException(nameof(logger)); + if (endpointConfiguration == null) throw new ArgumentNullException(nameof(endpointConfiguration)); @@ -67,8 +71,8 @@ public InfoServiceProxy(string endpointConfiguration, string remoteAddress) FixBinding(); } - public InfoServiceProxy(string endpointConfiguration, string remoteAddress, ServiceCredentials credentials) - : this(endpointConfiguration, remoteAddress) + public InfoServiceProxy(ILogger logger, string endpointConfiguration, string remoteAddress, ServiceCredentials credentials) + : this(logger, endpointConfiguration, remoteAddress) { if (credentials == null) throw new ArgumentNullException(nameof(credentials)); @@ -76,8 +80,10 @@ public InfoServiceProxy(string endpointConfiguration, string remoteAddress, Serv credentials.ApplyTo(ChannelFactory); } - public InfoServiceProxy(Uri address, Binding binding, ServiceCredentials credentials) + public InfoServiceProxy(ILogger logger, Uri address, Binding binding, ServiceCredentials credentials) { + _log = logger ?? throw new ArgumentNullException(nameof(logger)); + if (address == null) throw new ArgumentNullException(nameof(address)); @@ -166,7 +172,7 @@ public virtual XmlElement Invoke(string entity, string verb, params XmlElement[] } catch (FaultException ex) { - _log.Error("Error executing invoke: " + ex.Detail.Message + Environment.NewLine + entity + "." + verb); + _log.LogError(ex, "Error executing invoke on {entity}.{verb}", entity, verb); throw; } finally @@ -174,19 +180,19 @@ public virtual XmlElement Invoke(string entity, string verb, params XmlElement[] stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING INVOKE: {0} ms: {1}:{2}", stopwatch.Elapsed.TotalMilliseconds, verb, entity); + _log.LogWarning("Support! -- LONG RUNNING INVOKE: {elapsed} ms: {verb}:{entity}", stopwatch.Elapsed.TotalMilliseconds, verb, entity); } } } public virtual Message Query(QueryXmlRequest query) { - _log.DebugFormat("Query: {0}", query.query); - if (_log.IsDebugEnabled && query.parameters.Count > 0) + _log.LogDebug("Query: {query}", query.query); + if (_log.IsEnabled(LogLevel.Debug) && query.parameters.Count > 0) { - _log.Debug("Parameters: "); + _log.LogDebug("Parameters: "); foreach (var parameter in query.parameters) - _log.DebugFormat("\t{0}={1}", parameter.Key, parameter.Value); + _log.LogDebug("\t{parameter}={value}", parameter.Key, parameter.Value); } var stopwatch = new Stopwatch(); try @@ -200,14 +206,14 @@ public virtual Message Query(QueryXmlRequest query) } catch (FaultException ex) { - _log.Error("Error executing query: " + ex.Detail.Message + Environment.NewLine + query.query); + _log.LogError(ex, "Error executing query:" + Environment.NewLine + "{query}", query.query); throw; } catch (Exception ex) { - _log.ErrorFormat("Error executing query: {0} {1} {2}", ex, Environment.NewLine, query.query); + _log.LogError(ex, "Error executing query:" + Environment.NewLine + "{query}", query.query); foreach (var parameter in query.parameters) - _log.ErrorFormat("\t{0}={1}", parameter.Key, parameter.Value); + _log.LogError("\t{parameter}={value}", parameter.Key, parameter.Value); throw; } finally @@ -215,7 +221,7 @@ public virtual Message Query(QueryXmlRequest query) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING QUERY: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, query.query); + _log.LogWarning("Support! -- LONG RUNNING QUERY: {elapsed} ms: {query}", stopwatch.Elapsed.TotalMilliseconds, query.query); } } } @@ -234,7 +240,7 @@ public virtual string Create(string entityType, PropertyBag properties) } catch (FaultException ex) { - _log.Error("Error executing create operation: " + ex.Detail.Message + Environment.NewLine + entityType + Environment.NewLine + properties); + _log.LogError(ex, "Error executing create operation: " + Environment.NewLine + entityType + Environment.NewLine + properties); throw; } finally @@ -242,7 +248,7 @@ public virtual string Create(string entityType, PropertyBag properties) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING CREATE: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, entityType); + _log.LogWarning("Support! -- LONG RUNNING CREATE: {elapsed} ms: {entityType}", stopwatch.Elapsed.TotalMilliseconds, entityType); } } } @@ -261,7 +267,7 @@ public virtual PropertyBag Read(string uri) } catch (FaultException ex) { - _log.Error("Error executing read operation: " + ex.Detail.Message + Environment.NewLine + uri); + _log.LogError(ex, "Error executing read operation: {uri}", uri); throw; } finally @@ -269,7 +275,7 @@ public virtual PropertyBag Read(string uri) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING READ: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, uri); + _log.LogWarning("Support! -- LONG RUNNING READ: {elapsed} ms: {uri}", stopwatch.Elapsed.TotalMilliseconds, uri); } } } @@ -288,7 +294,7 @@ public virtual void Update(string uri, PropertyBag propertiesToUpdate) } catch (FaultException ex) { - _log.Error("Error executing update operation: " + ex.Detail.Message + Environment.NewLine + uri + Environment.NewLine + propertiesToUpdate); + _log.LogError(ex, "Error executing update operation: " + uri + Environment.NewLine + propertiesToUpdate); throw; } finally @@ -296,7 +302,7 @@ public virtual void Update(string uri, PropertyBag propertiesToUpdate) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING UPDATE: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, uri); + _log.LogWarning("Support! -- LONG RUNNING UPDATE: {elapsed} ms: {uri}", stopwatch.Elapsed.TotalMilliseconds, uri); } } } @@ -315,7 +321,7 @@ public virtual void BulkUpdate(string[] uris, PropertyBag propertiesToUpdate) } catch (FaultException ex) { - _log.Error("Error executing bulk update operation: " + ex.Detail.Message + Environment.NewLine + string.Join(Environment.NewLine, uris) + Environment.NewLine + propertiesToUpdate); + _log.LogError(ex, "Error executing bulk update operation:" + Environment.NewLine + string.Join(Environment.NewLine, uris) + Environment.NewLine + propertiesToUpdate); throw; } finally @@ -323,7 +329,7 @@ public virtual void BulkUpdate(string[] uris, PropertyBag propertiesToUpdate) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING BULK UPDATE: {0} ms", stopwatch.Elapsed.TotalMilliseconds); + _log.LogWarning("Support! -- LONG RUNNING BULK UPDATE: {elapsed} ms", stopwatch.Elapsed.TotalMilliseconds); } } } @@ -342,7 +348,7 @@ public virtual void Delete(string uri) } catch (FaultException ex) { - _log.Error("Error executing delete operation: " + ex.Detail.Message + Environment.NewLine + uri); + _log.LogError(ex, "Error executing delete operation: {uri}", uri); throw; } finally @@ -350,7 +356,7 @@ public virtual void Delete(string uri) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING DELETE: {0} ms: {1}", stopwatch.Elapsed.TotalMilliseconds, uri); + _log.LogWarning("Support! -- LONG RUNNING DELETE: {elapsed} ms: {uri}", stopwatch.Elapsed.TotalMilliseconds, uri); } } } @@ -369,7 +375,7 @@ public virtual void BulkDelete(string[] uris) } catch (FaultException ex) { - _log.Error("Error executing bulk delete operation: " + ex.Detail.Message + Environment.NewLine + string.Join(Environment.NewLine, uris)); + _log.LogError(ex, "Error executing bulk delete operation: " + Environment.NewLine + string.Join(Environment.NewLine, uris)); throw; } finally @@ -377,7 +383,7 @@ public virtual void BulkDelete(string[] uris) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING BULK DELETE: {0} ms", stopwatch.Elapsed.TotalMilliseconds); + _log.LogWarning("Support! -- LONG RUNNING BULK DELETE: {elapsed} ms", stopwatch.Elapsed.TotalMilliseconds); } } } @@ -400,7 +406,7 @@ public VerbInvokeResponse StreamedInvoke(VerbInvokeArguments parameter) } catch (FaultException ex) { - _log.Error("Error executing invoke: " + ex.Detail.Message + Environment.NewLine + parameter.Entity + "." + parameter.Verb); + _log.LogError(ex, "Error executing invoke: {entity}.{verb}", parameter.Entity, parameter.Verb); throw; } finally @@ -408,7 +414,7 @@ public VerbInvokeResponse StreamedInvoke(VerbInvokeArguments parameter) stopwatch.Stop(); if (stopwatch.Elapsed > longRunningQueryTime) { - _log.WarnFormat("Support! -- LONG RUNNING INVOKE: {0} ms: {1}:{2}", stopwatch.Elapsed.TotalMilliseconds, parameter.Verb, parameter.Entity); + _log.LogWarning("Support! -- LONG RUNNING INVOKE: {elapsed} ms: {verb}:{entity}", stopwatch.Elapsed.TotalMilliseconds, parameter.Verb, parameter.Entity); } } } @@ -432,7 +438,7 @@ public void Open() } catch (Exception ex) { - _log.Error("An error occured opening a connection to the orion communication service.", ex); + _log.LogError(ex, "An error occurred opening a connection to the Orion communication service."); throw; } } @@ -462,12 +468,12 @@ public void Close() catch (TimeoutException exception) { _infoService.Abort(); - _log.Error("Error closing exception.", exception); + _log.LogError(exception, "Error closing exception."); } catch (CommunicationException exception) { _infoService.Abort(); - _log.Error("Error closing exception.", exception); + _log.LogError(exception, "Error closing exception."); } _infoService = null; @@ -475,26 +481,26 @@ public void Close() #region Create Channel Factory - private static ChannelFactory CreateChannelFactory(Binding binding, EndpointAddress address) + private ChannelFactory CreateChannelFactory(Binding binding, EndpointAddress address) { - if (_log.IsDebugEnabled) - _log.DebugFormat("Creating channel factory for Information Service @ {0}", address.Uri); + if (_log.IsEnabled(LogLevel.Debug)) + _log.LogDebug("Creating channel factory for Information Service @ {uri}", address.Uri); return new ChannelFactory(binding, address); } - private static ChannelFactory CreateChannelFactory(string endpointConfiguration) + private ChannelFactory CreateChannelFactory(string endpointConfiguration) { - if (_log.IsDebugEnabled) - _log.DebugFormat("Creating channel factory for Information Service using endpoint configuration '{0}'", endpointConfiguration); + if (_log.IsEnabled(LogLevel.Debug)) + _log.LogDebug($"Creating channel factory for Information Service using endpoint configuration '{endpointConfiguration}'", endpointConfiguration); return new ChannelFactory(endpointConfiguration); } - private static ChannelFactory CreateChannelFactory(string endpointConfiguration, EndpointAddress remoteAddress) + private ChannelFactory CreateChannelFactory(string endpointConfiguration, EndpointAddress remoteAddress) { - if (_log.IsDebugEnabled) - _log.DebugFormat("Creating channel factory for Information Service using endpoint configuration '{0}' and remote address '{1}'", endpointConfiguration, remoteAddress.ToString()); + if (_log.IsEnabled(LogLevel.Debug)) + _log.LogDebug("Creating channel factory for Information Service using endpoint configuration '{endpointConfiguration}' and remote address '{remoteAddress}'", endpointConfiguration, remoteAddress.ToString()); return new ChannelFactory(endpointConfiguration, remoteAddress); } @@ -509,8 +515,8 @@ private void ValidateUsedConnection() if (_activityMonitor == null || _activityMonitor.RequestSent) return; - _log.Info("Non-used connection was opened. Information for developers. No impact on product functionality. See verbose log for more details."); - _log.VerboseFormat("StackTrace: {0}", Environment.StackTrace); + _log.LogInformation("Non-used connection was opened. Information for developers. No impact on product functionality. See verbose log for more details."); + _log.LogTrace("StackTrace: {stackTrace}", Environment.StackTrace); try { diff --git a/Src/Contract/InformationServiceClient/InformationServiceConnection.cs b/Src/Contract/InformationServiceClient/InformationServiceConnection.cs index c74d0d150..3a04f6459 100644 --- a/Src/Contract/InformationServiceClient/InformationServiceConnection.cs +++ b/Src/Contract/InformationServiceClient/InformationServiceConnection.cs @@ -2,6 +2,7 @@ using System.Data; using System.Data.Common; using System.ServiceModel; +using Microsoft.Extensions.Logging; using SolarWinds.InformationService.Contract2; namespace SolarWinds.InformationService.InformationServiceClient @@ -15,78 +16,17 @@ public sealed class InformationServiceConnection : DbConnection private string remoteAddress; private InfoServiceProxy proxy; private ServiceCredentials credentials; + private readonly ILoggerFactory _loggerFactory; private readonly bool bProxyOwner = true; private bool open = false; - public InformationServiceConnection() - : this(string.Empty) + public InformationServiceConnection(ILoggerFactory loggerFactory, IInformationService service) { - } - - public InformationServiceConnection(string endpointName) - { - if (endpointName == null) - throw new ArgumentNullException(nameof(endpointName)); - - Initialize(endpointName, null, null); - } - - //This is required by NCM. NCM provide it's own proxy object - public InformationServiceConnection(InfoServiceProxy proxy) : this(proxy, false) - { - } - - public InformationServiceConnection(InfoServiceProxy proxy, bool takeOwnership) - { - Service = proxy; - bProxyOwner = takeOwnership; - if (bProxyOwner) - { - this.proxy = proxy; - } - } - - public InformationServiceConnection(IInformationService service) - { - if (service == null) - throw new ArgumentNullException(nameof(service)); - - Service = service; + _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); + Service = service ?? throw new ArgumentNullException(nameof(service)); bProxyOwner = false; } - public InformationServiceConnection(string endpointName, string remoteAddress) - { - if (endpointName == null) - throw new ArgumentNullException(nameof(endpointName)); - if (remoteAddress == null) - throw new ArgumentNullException(nameof(remoteAddress)); - - Initialize(endpointName, remoteAddress, null); - } - - public InformationServiceConnection(string endpointName, string remoteAddress, ServiceCredentials credentials) - { - if (endpointName == null) - throw new ArgumentNullException(nameof(endpointName)); - if (remoteAddress == null) - throw new ArgumentNullException(nameof(remoteAddress)); - if (credentials == null) - throw new ArgumentNullException(nameof(credentials)); - - Initialize(endpointName, remoteAddress, credentials); - } - - public InformationServiceConnection(string endpointName, ServiceCredentials credentials) - { - if (endpointName == null) - throw new ArgumentNullException(nameof(endpointName)); - if (credentials == null) - throw new ArgumentNullException(nameof(credentials)); - - Initialize(endpointName, null, credentials); - } - protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { throw new NotSupportedException(); @@ -241,19 +181,21 @@ private void CreateProxy() { if (endpointName.Length != 0) { + ILogger logger = _loggerFactory.CreateLogger(); + if (remoteAddress != null) { if (credentials != null) - proxy = new InfoServiceProxy(endpointName, remoteAddress, credentials); + proxy = new InfoServiceProxy(logger, endpointName, remoteAddress, credentials); else - proxy = new InfoServiceProxy(endpointName, remoteAddress); + proxy = new InfoServiceProxy(logger, endpointName, remoteAddress); } else { if (credentials != null) - proxy = new InfoServiceProxy(endpointName, credentials); + proxy = new InfoServiceProxy(logger, endpointName, credentials); else - proxy = new InfoServiceProxy(endpointName); + proxy = new InfoServiceProxy(logger, endpointName); } Service = proxy; diff --git a/Src/Contract/InformationServiceContext.cs b/Src/Contract/InformationServiceContext.cs index 1f4a6b3be..0ae0ad868 100644 --- a/Src/Contract/InformationServiceContext.cs +++ b/Src/Contract/InformationServiceContext.cs @@ -1,14 +1,17 @@ using System; +using Microsoft.Extensions.Logging; namespace SolarWinds.InformationService.Contract2 { public class InformationServiceContext : IDisposable { private bool disposed = false; + private readonly ILoggerFactory _loggerFactory; private readonly IInformationService service = null; - public InformationServiceContext(IInformationService service) + public InformationServiceContext(ILoggerFactory loggerFactory, IInformationService service) { + _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); this.service = service; } @@ -26,7 +29,7 @@ public InformationServiceContext(IInformationService service) if (disposed) throw new InvalidOperationException("context disposed"); - return new InformationServiceQuery(this, queryString); + return new InformationServiceQuery(_loggerFactory.CreateLogger>(), this, queryString); } public InfoServiceProxy Proxy { get; private set; } = null; diff --git a/Src/Contract/InformationServiceQuery.cs b/Src/Contract/InformationServiceQuery.cs index 62e1d8a94..33ef30618 100644 --- a/Src/Contract/InformationServiceQuery.cs +++ b/Src/Contract/InformationServiceQuery.cs @@ -3,13 +3,13 @@ using System.ServiceModel; using System.ServiceModel.Channels; using System.Xml; -using SolarWinds.Logging; +using Microsoft.Extensions.Logging; namespace SolarWinds.InformationService.Contract2 { public class InformationServiceQuery : IDisposable { - private static readonly Log log = new Log(); + private readonly ILogger log; private readonly InformationServiceContext context; private readonly string queryString; @@ -19,8 +19,10 @@ public class InformationServiceQuery : IDisposable protected bool disposed = false; - public InformationServiceQuery(InformationServiceContext context, string queryString, PropertyBag parameters) + public InformationServiceQuery(ILogger logger, InformationServiceContext context, string queryString, PropertyBag parameters) { + log = logger ?? throw new ArgumentNullException(nameof(logger)); + if (context == null) throw new ArgumentNullException(nameof(context)); if (queryString == null) @@ -47,7 +49,7 @@ public XmlReader Execute(bool hierarchical) Message response = context.Service.Query(request); - log.Debug(response); + log.LogDebug(response.ToString()); if (response.IsFault) { diff --git a/Src/Contract/InformationServiceQueryOfT.cs b/Src/Contract/InformationServiceQueryOfT.cs index 198290b28..2bf488955 100644 --- a/Src/Contract/InformationServiceQueryOfT.cs +++ b/Src/Contract/InformationServiceQueryOfT.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Xml; +using Microsoft.Extensions.Logging; namespace SolarWinds.InformationService.Contract2 { @@ -9,13 +10,13 @@ namespace SolarWinds.InformationService.Contract2 private readonly Type type = typeof(T); private readonly IResponseParser parser; - public InformationServiceQuery(InformationServiceContext context, string queryString) - : this(context, queryString, null) + public InformationServiceQuery(ILogger> logger, InformationServiceContext context, string queryString) + : this(logger, context, queryString, null) { } - public InformationServiceQuery(InformationServiceContext context, string query, PropertyBag parameters) - : base(context, query, parameters) + public InformationServiceQuery(ILogger> logger, InformationServiceContext context, string query, PropertyBag parameters) + : base(logger, context, query, parameters) { object[] attributes = type.GetCustomAttributes(typeof(InformationServiceEntityAttribute), false); diff --git a/Src/Contract/SolarWinds.InformationService.Contract.csproj b/Src/Contract/SolarWinds.InformationService.Contract.csproj index aa65b47fe..0592e5117 100644 --- a/Src/Contract/SolarWinds.InformationService.Contract.csproj +++ b/Src/Contract/SolarWinds.InformationService.Contract.csproj @@ -9,10 +9,7 @@ - - - - + @@ -20,12 +17,6 @@ - - diff --git a/Src/SwisPowerShell/ConnectSwis.cs b/Src/SwisPowerShell/ConnectSwis.cs index cd67ba941..7d612ce7f 100644 --- a/Src/SwisPowerShell/ConnectSwis.cs +++ b/Src/SwisPowerShell/ConnectSwis.cs @@ -9,6 +9,8 @@ using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Security; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using SolarWinds.InformationService.Contract2; namespace SwisPowerShell @@ -16,6 +18,8 @@ namespace SwisPowerShell [Cmdlet(VerbsCommunications.Connect, "Swis", DefaultParameterSetName = "Credential")] public class ConnectSwis : Cmdlet { + private static ILogger _infoServiceLogger = new NullLogger(); + [Parameter(ParameterSetName = "UserName", Mandatory = false, Position = 0, HelpMessage = "UserName for connecting to Orion.")] public string UserName { get; set; } @@ -149,7 +153,7 @@ private static InfoServiceProxy ConnectSoap12(Uri address, string username, stri var credentials = new UsernameCredentials(username, password); - return new InfoServiceProxy(address, binding, credentials); + return new InfoServiceProxy(_infoServiceLogger, address, binding, credentials); } private InfoServiceProxy ConnectNetTcp() @@ -165,7 +169,7 @@ private InfoServiceProxy ConnectNetTcp() var uri = new Uri(string.Format(addresses.activeDirectory, Hostname ?? "localhost")); - infoServiceProxy = new InfoServiceProxy(uri, binding, new WindowsCredential()); + infoServiceProxy = new InfoServiceProxy(_infoServiceLogger, uri, binding, new WindowsCredential()); } else if (Certificate.IsPresent) { @@ -190,7 +194,7 @@ private InfoServiceProxy ConnectNetTcp() ServiceCredentials credentials = new MyCertificateCredential("SolarWinds-Orion", StoreLocation.LocalMachine, StoreName.My); - infoServiceProxy = new InfoServiceProxy(uri, binding, credentials); + infoServiceProxy = new InfoServiceProxy(_infoServiceLogger, uri, binding, credentials); } else { @@ -215,7 +219,7 @@ private InfoServiceProxy ConnectNetTcp() var credentials = new UsernameCredentials(username, password); - infoServiceProxy = new InfoServiceProxy(uri, binding, credentials); + infoServiceProxy = new InfoServiceProxy(_infoServiceLogger, uri, binding, credentials); } return infoServiceProxy; } diff --git a/Src/SwisPowerShell/GetSwisData.cs b/Src/SwisPowerShell/GetSwisData.cs index 0c81e49d1..d082f18ee 100644 --- a/Src/SwisPowerShell/GetSwisData.cs +++ b/Src/SwisPowerShell/GetSwisData.cs @@ -4,6 +4,7 @@ using System.Management.Automation; using System.Text; using System.Xml; +using Microsoft.Extensions.Logging.Abstractions; using SolarWinds.InformationService.Contract2; using SolarWinds.InformationService.InformationServiceClient; @@ -38,7 +39,7 @@ protected override void InternalProcessRecord() { if (returnClauses.Any(s => Query.Trim().EndsWith(s, StringComparison.OrdinalIgnoreCase))) { - using (var connection = new InformationServiceConnection((IInformationService)SwisConnection)) + using (var connection = new InformationServiceConnection(NullLoggerFactory.Instance, SwisConnection)) { InformationServiceXmlReader reader = new InformationServiceXmlReader(connection) { ApplicationTag = "SwisPowerShell" }; @@ -58,7 +59,7 @@ protected override void InternalProcessRecord() private void ProcessDataReader() { CheckConnection(); - using (var connection = new InformationServiceConnection((IInformationService)SwisConnection)) + using (var connection = new InformationServiceConnection(NullLoggerFactory.Instance, SwisConnection)) { connection.Open(); using (var command = new InformationServiceCommand(Query, connection)) diff --git a/Src/SwqlStudio/ConnectionInfo.cs b/Src/SwqlStudio/ConnectionInfo.cs index fbf2dd694..f29eb5b51 100644 --- a/Src/SwqlStudio/ConnectionInfo.cs +++ b/Src/SwqlStudio/ConnectionInfo.cs @@ -148,7 +148,7 @@ public void Connect() _proxy.Open(); } - Connection = new InformationServiceConnection((IInformationService)_proxy); + Connection = new InformationServiceConnection(Program.LoggerFactory, _proxy); Connection.Open(); } @@ -175,7 +175,7 @@ private void EnsureConnection() { EnsureConnection(); - using (var context = new InformationServiceContext(_proxy)) + using (var context = new InformationServiceContext(Program.LoggerFactory, _proxy)) using (var serviceQuery = context.CreateQuery(swql)) { var enumerator = serviceQuery.GetEnumerator(); diff --git a/Src/SwqlStudio/InfoServiceBase.cs b/Src/SwqlStudio/InfoServiceBase.cs index e9d87fbe9..8b4e2455a 100644 --- a/Src/SwqlStudio/InfoServiceBase.cs +++ b/Src/SwqlStudio/InfoServiceBase.cs @@ -1,6 +1,7 @@ using System; using System.Globalization; using System.ServiceModel.Channels; +using Microsoft.Extensions.Logging; using SolarWinds.InformationService.Contract2; using SolarWinds.InformationService.Contract2.PubSub; using SwqlStudio.Properties; @@ -61,7 +62,8 @@ private Uri Uri(string serverAddress, string port) public virtual InfoServiceProxy CreateProxy(string server) { - return new InfoServiceProxy(Uri(server), Binding, Credentials); + ILogger logger = Program.LoggerFactory.CreateLogger(); + return new InfoServiceProxy(logger, Uri(server), Binding, Credentials); } public virtual bool SupportsActiveSubscriber { get { return false; } } From b02ed4124de4cf2c224da703f9477c8a5706ccae Mon Sep 17 00:00:00 2001 From: Dan Jagnow Date: Wed, 31 Mar 2021 17:43:54 -0500 Subject: [PATCH 4/5] Removed SolarWinds.Logging.csproj Removed SolarWinds.Logging.csproj from the solution. --- Src/Logging/EventIDLogImpl.cs | 418 ------------ Src/Logging/EventIDLogManager.cs | 264 ------- Src/Logging/ForceMessageLog.cs | 73 -- Src/Logging/IEventIDLog.cs | 32 - Src/Logging/Log.cs | 642 ------------------ ...SolarWinds.Logging.ExternalAnnotations.xml | 534 --------------- Src/Logging/SolarWinds.Logging.csproj | 30 - Src/OrionSDK.sln | 12 - 8 files changed, 2005 deletions(-) delete mode 100644 Src/Logging/EventIDLogImpl.cs delete mode 100644 Src/Logging/EventIDLogManager.cs delete mode 100644 Src/Logging/ForceMessageLog.cs delete mode 100644 Src/Logging/IEventIDLog.cs delete mode 100644 Src/Logging/Log.cs delete mode 100644 Src/Logging/SolarWinds.Logging.ExternalAnnotations.xml delete mode 100644 Src/Logging/SolarWinds.Logging.csproj diff --git a/Src/Logging/EventIDLogImpl.cs b/Src/Logging/EventIDLogImpl.cs deleted file mode 100644 index a36aa2e0e..000000000 --- a/Src/Logging/EventIDLogImpl.cs +++ /dev/null @@ -1,418 +0,0 @@ -using System; -using System.Globalization; -using log4net.Core; -using log4net.Util; - -namespace SolarWinds.Logging.Ext.EventID -{ - public class EventIDLogImpl : LogImpl, IEventIDLog - { - /// - /// The declaring type of the method that is the stack boundary into the logging system for this call. - /// - private readonly Type ThisDeclaringType = typeof(Log); - - public EventIDLogImpl(ILogger logger) : base(logger) - { - } - - #region Implementation of IEventIDLog - - public void Debug(int eventId, object message) - { - Debug(eventId, message, null); - } - - public void Debug(int eventId, object message, Exception t) - { - if (IsDebugEnabled) - { - LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Debug, message, t); - loggingEvent.Properties["EventID"] = eventId; - Logger.Log(loggingEvent); - } - } - - public void Info(int eventId, object message) - { - Info(eventId, message, null); - } - - public void Info(int eventId, object message, Exception t) - { - if (IsInfoEnabled) - { - LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Info, message, t); - loggingEvent.Properties["EventID"] = eventId; - Logger.Log(loggingEvent); - } - } - - public void Warn(int eventId, object message) - { - Warn(eventId, message, null); - } - - public void Warn(int eventId, object message, Exception t) - { - if (IsWarnEnabled) - { - LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Warn, message, t); - loggingEvent.Properties["EventID"] = eventId; - Logger.Log(loggingEvent); - } - } - - public void Error(int eventId, object message) - { - Error(eventId, message, null); - } - - public void Error(int eventId, object message, Exception t) - { - if (IsErrorEnabled) - { - LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Error, message, t); - loggingEvent.Properties["EventID"] = eventId; - Logger.Log(loggingEvent); - } - } - - public void Fatal(int eventId, object message) - { - Fatal(eventId, message, null); - } - - public void Fatal(int eventId, object message, Exception t) - { - if (IsFatalEnabled) - { - LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Fatal, message, t); - loggingEvent.Properties["EventID"] = eventId; - Logger.Log(loggingEvent); - } - } - - public void Verbose(int eventId, object message) - { - Verbose(eventId, message, null); - } - - public void Verbose(int eventId, object message, Exception t) - { - if (IsVerboseEnabled) - { - LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Verbose, message, t); - loggingEvent.Properties["EventID"] = eventId; - Logger.Log(loggingEvent); - } - } - - public bool IsVerboseEnabled - { - get { return Logger.IsEnabledFor(Level.Verbose); } - } - - public void Trace(int eventId, object message) - { - Trace(eventId, message, null); - } - - public void Trace(int eventId, object message, Exception t) - { - if (IsTraceEnabled) - { - LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Trace, message, t); - loggingEvent.Properties["EventID"] = eventId; - Logger.Log(loggingEvent); - } - } - - public bool IsTraceEnabled - { - get { return Logger.IsEnabledFor(Level.Trace); } - } - - #endregion Implementation of IEventIDLog - - #region Forward Debug logs - public override void Debug(object msg) - { - Log(Level.Debug, msg); - } - - public override void Debug(object msg, Exception exc) - { - Log(Level.Debug, msg, exc); - } - - public override void DebugFormat(string format, object arg0) - { - LogFormat(Level.Debug, format, arg0); - } - - public override void DebugFormat(string format, params object[] args) - { - LogFormat(Level.Debug, format, args); - } - - public override void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Debug, provider, format, args); - } - - public override void DebugFormat(string format, object arg0, object arg1) - { - LogFormat(Level.Debug, format, arg0, arg1); - } - - public override void DebugFormat(string format, object arg0, object arg1, object arg2) - { - LogFormat(Level.Debug, format, arg0, arg1, arg2); - } - #endregion - - #region Forward Error logs - public override void Error(object msg) - { - Log(Level.Error, msg); - } - - public override void Error(object msg, Exception exc) - { - Log(Level.Error, msg, exc); - } - - public override void ErrorFormat(string format, object arg0) - { - LogFormat(Level.Error, format, arg0); - } - - public override void ErrorFormat(string format, params object[] args) - { - LogFormat(Level.Error, format, args); - } - - public override void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Error, provider, format, args); - } - - public override void ErrorFormat(string format, object arg0, object arg1) - { - LogFormat(Level.Error, format, arg0, arg1); - } - - public override void ErrorFormat(string format, object arg0, object arg1, object arg2) - { - LogFormat(Level.Error, format, arg0, arg1, arg2); - } - - public override void Fatal(object msg) - { - Log(Level.Fatal, msg); - } - #endregion - - #region Foward Fatal errors - public override void Fatal(object msg, Exception exc) - { - Log(Level.Fatal, msg, exc); - } - - public override void FatalFormat(string format, object arg0) - { - LogFormat(Level.Fatal, format, arg0); - } - - public override void FatalFormat(string format, params object[] args) - { - LogFormat(Level.Fatal, format, args); - } - - public override void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Fatal, provider, format, args); - } - - public override void FatalFormat(string format, object arg0, object arg1) - { - LogFormat(Level.Fatal, format, arg0, arg1); - } - - public override void FatalFormat(string format, object arg0, object arg1, object arg2) - { - LogFormat(Level.Fatal, format, arg0, arg1, arg2); - } - #endregion - - #region Forward Info logs - public override void Info(object msg) - { - Log(Level.Info, msg); - } - - public override void Info(object msg, Exception exc) - { - Log(Level.Info, msg, exc); - } - - public override void InfoFormat(string format, object arg0) - { - LogFormat(Level.Info, format, arg0); - } - - public override void InfoFormat(string format, params object[] args) - { - LogFormat(Level.Info, format, args); - } - - public override void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Info, provider, format, args); - } - - public override void InfoFormat(string format, object arg0, object arg1) - { - LogFormat(Level.Info, format, arg0, arg1); - } - - public override void InfoFormat(string format, object arg0, object arg1, object arg2) - { - LogFormat(Level.Info, format, arg0, arg1, arg2); - } - #endregion - - #region Forward Verbose logs - public void Verbose(object msg) - { - Log(Level.Verbose, msg); - } - - public void Verbose(object msg, Exception exc) - { - Log(Level.Verbose, msg, exc); - } - - public void VerboseFormat(string format, object arg0) - { - LogFormat(Level.Verbose, format, arg0); - } - - public void VerboseFormat(string format, params object[] args) - { - LogFormat(Level.Verbose, format, args); - } - - public void VerboseFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Verbose, provider, format, args); - } - - public void VerboseFormat(string format, object arg0, object arg1) - { - LogFormat(Level.Verbose, format, arg0, arg1); - } - - public void VerboseFormat(string format, object arg0, object arg1, object arg2) - { - LogFormat(Level.Verbose, format, arg0, arg1, arg2); - } - #endregion - - #region Forward Warn logs - public override void Warn(object msg) - { - Log(Level.Warn, msg); - } - - public override void Warn(object msg, Exception exc) - { - Log(Level.Warn, msg, exc); - } - - public override void WarnFormat(string format, object arg0) - { - LogFormat(Level.Warn, format, arg0); - } - - public override void WarnFormat(string format, params object[] args) - { - LogFormat(Level.Warn, format, args); - } - - public override void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - LogFormat(Level.Warn, provider, format, args); - } - - public override void WarnFormat(string format, object arg0, object arg1) - { - LogFormat(Level.Warn, format, arg0, arg1); - } - - public override void WarnFormat(string format, object arg0, object arg1, object arg2) - { - LogFormat(Level.Warn, format, arg0, arg1, arg2); - } - #endregion - - #region Forward logs based on the LogLevel - private methods - private void Log(Level logLevel, object msg) - { - if (Logger.IsEnabledFor(logLevel)) - { - Logger.Log(ThisDeclaringType, logLevel, msg, null); - } - } - - private void Log(Level logLevel, object msg, Exception exc) - { - if (Logger.IsEnabledFor(logLevel)) - { - Logger.Log(ThisDeclaringType, logLevel, msg, exc); - } - } - - private void LogFormat(Level logLevel, string format, object arg0) - { - if (Logger.IsEnabledFor(logLevel)) - { - Logger.Log(ThisDeclaringType, logLevel, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } - - private void LogFormat(Level logLevel, string format, params object[] args) - { - if (Logger.IsEnabledFor(logLevel)) - { - Logger.Log(ThisDeclaringType, logLevel, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } - - private void LogFormat(Level logLevel, IFormatProvider provider, string format, params object[] args) - { - if (Logger.IsEnabledFor(logLevel)) - { - Logger.Log(ThisDeclaringType, logLevel, new SystemStringFormat(provider, format, args), null); - } - } - - private void LogFormat(Level logLevel, string format, object arg0, object arg1) - { - if (Logger.IsEnabledFor(logLevel)) - { - Logger.Log(ThisDeclaringType, logLevel, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } - - private void LogFormat(Level logLevel, string format, object arg0, object arg1, object arg2) - { - if (Logger.IsEnabledFor(logLevel)) - { - Logger.Log(ThisDeclaringType, logLevel, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } - #endregion - } -} diff --git a/Src/Logging/EventIDLogManager.cs b/Src/Logging/EventIDLogManager.cs deleted file mode 100644 index f2adf76fd..000000000 --- a/Src/Logging/EventIDLogManager.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Reflection; - -using log4net; -using log4net.Core; - -namespace SolarWinds.Logging.Ext.EventID -{ - public class EventIDLogManager - { - #region Static Member Variables - - /// - /// The wrapper map to use to hold the objects - /// - private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler)); - - #endregion - - #region Constructor - - /// - /// Private constructor to prevent object creation - /// - private EventIDLogManager() { } - - #endregion - - #region Type Specific Manager Methods - - /// - /// Returns the named logger if it exists - /// - /// - /// If the named logger exists (in the default hierarchy) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// The fully qualified logger name to look for - /// The logger found, or null - public static IEventIDLog Exists(string name) - { - return Exists(Assembly.GetCallingAssembly(), name); - } - - /// - /// Returns the named logger if it exists - /// - /// - /// If the named logger exists (in the specified domain) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// the domain to lookup in - /// The fully qualified logger name to look for - /// The logger found, or null - public static IEventIDLog Exists(string domain, string name) - { - return WrapLogger(LoggerManager.Exists(domain, name)); - } - - /// - /// Returns the named logger if it exists - /// - /// - /// If the named logger exists (in the specified assembly's domain) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// the assembly to use to lookup the domain - /// The fully qualified logger name to look for - /// The logger found, or null - public static IEventIDLog Exists(Assembly assembly, string name) - { - return WrapLogger(LoggerManager.Exists(assembly, name)); - } - - /// - /// Returns all the currently defined loggers in the default domain. - /// - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers - public static IEventIDLog[] GetCurrentLoggers() - { - return GetCurrentLoggers(Assembly.GetCallingAssembly()); - } - - /// - /// Returns all the currently defined loggers in the specified domain. - /// - /// the domain to lookup in - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers - public static IEventIDLog[] GetCurrentLoggers(string domain) - { - return WrapLoggers(LoggerManager.GetCurrentLoggers(domain)); - } - - /// - /// Returns all the currently defined loggers in the specified assembly's domain. - /// - /// the assembly to use to lookup the domain - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers - public static IEventIDLog[] GetCurrentLoggers(Assembly assembly) - { - return WrapLoggers(LoggerManager.GetCurrentLoggers(assembly)); - } - - /// - /// Retrieve or create a named logger. - /// - /// - /// Retrieve a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// The name of the logger to retrieve. - /// the logger with the name specified - public static IEventIDLog GetLogger(string name) - { - return GetLogger(Assembly.GetCallingAssembly(), name); - } - - /// - /// Retrieve or create a named logger. - /// - /// - /// Retrieve a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// the domain to lookup in - /// The name of the logger to retrieve. - /// the logger with the name specified - public static IEventIDLog GetLogger(string domain, string name) - { - return WrapLogger(LoggerManager.GetLogger(domain, name)); - } - - /// - /// Retrieve or create a named logger. - /// - /// - /// Retrieve a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// the assembly to use to lookup the domain - /// The name of the logger to retrieve. - /// the logger with the name specified - public static IEventIDLog GetLogger(Assembly assembly, string name) - { - return WrapLogger(LoggerManager.GetLogger(assembly, name)); - } - - /// - /// Shorthand for . - /// - /// - /// Get the logger for the fully qualified name of the type specified. - /// - /// The full name of will - /// be used as the name of the logger to retrieve. - /// the logger with the name specified - public static IEventIDLog GetLogger(Type type) - { - return GetLogger(Assembly.GetCallingAssembly(), type.FullName); - } - - /// - /// Shorthand for . - /// - /// - /// Get the logger for the fully qualified name of the type specified. - /// - /// the domain to lookup in - /// The full name of will - /// be used as the name of the logger to retrieve. - /// the logger with the name specified - public static IEventIDLog GetLogger(string domain, Type type) - { - return WrapLogger(LoggerManager.GetLogger(domain, type)); - } - - /// - /// Shorthand for . - /// - /// - /// Get the logger for the fully qualified name of the type specified. - /// - /// the assembly to use to lookup the domain - /// The full name of will - /// be used as the name of the logger to retrieve. - /// the logger with the name specified - public static IEventIDLog GetLogger(Assembly assembly, Type type) - { - return WrapLogger(LoggerManager.GetLogger(assembly, type)); - } - - #endregion - - #region Extension Handlers - - /// - /// Lookup the wrapper object for the logger specified - /// - /// the logger to get the wrapper for - /// the wrapper for the logger specified - private static IEventIDLog WrapLogger(ILogger logger) - { - return (IEventIDLog)s_wrapperMap.GetWrapper(logger); - } - - /// - /// Lookup the wrapper objects for the loggers specified - /// - /// the loggers to get the wrappers for - /// Lookup the wrapper objects for the loggers specified - private static IEventIDLog[] WrapLoggers(ILogger[] loggers) - { - IEventIDLog[] results = new IEventIDLog[loggers.Length]; - for (int i = 0; i < loggers.Length; i++) - { - results[i] = WrapLogger(loggers[i]); - } - return results; - } - - /// - /// Method to create the objects used by - /// this manager. - /// - /// The logger to wrap - /// The wrapper for the logger specified - private static ILoggerWrapper WrapperCreationHandler(ILogger logger) - { - return new EventIDLogImpl(logger); - } - - #endregion - } -} diff --git a/Src/Logging/ForceMessageLog.cs b/Src/Logging/ForceMessageLog.cs deleted file mode 100644 index 70d0f6410..000000000 --- a/Src/Logging/ForceMessageLog.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using log4net; -using log4net.Appender; -using log4net.Core; -using log4net.Layout; -using log4net.Repository.Hierarchy; - -namespace SolarWinds.Logging -{ - /// - /// Allow force log message to log file in-depend from the log level - /// - internal static class ForceMessageLog - { - private static readonly SimpleLayout _simpleLayout = new SimpleLayout(); - - private class SimpleLayout : ILayout - { - private readonly PatternLayout _layout = new PatternLayout("%message%newline"); - - public string ContentType { get { return "text/plain"; } } - - public string Footer { get { return null; } } - - public string Header { get { return null; } } - - public bool IgnoresException { get { return false; } } - - public void Format(TextWriter writer, LoggingEvent loggingEvent) - { - _layout.Format(writer, loggingEvent); - } - } - - public static void Log(ILog log, object message) - { - if (log == null) return; - - Logger logger = log.Logger as Logger; - - if (logger != null) - { - try - { - // Save current log level and layouts - Dictionary existingLayout = new Dictionary(); - Level existingLevel = logger.Level; - - foreach (var appender in logger.Repository.GetAppenders().OfType()) - { - existingLayout[appender] = appender.Layout; - appender.Layout = _simpleLayout; - } - - logger.Level = Level.Verbose; - - logger.Log(Level.Verbose, message, null); - - // Restore layouts and log level - foreach (KeyValuePair kv in existingLayout) - { - kv.Key.Layout = kv.Value; - } - - logger.Level = existingLevel; - } - catch { } // Ignore exception - } - } - } -} diff --git a/Src/Logging/IEventIDLog.cs b/Src/Logging/IEventIDLog.cs deleted file mode 100644 index 96530d6a5..000000000 --- a/Src/Logging/IEventIDLog.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using log4net; - -namespace SolarWinds.Logging.Ext.EventID -{ - public interface IEventIDLog : ILog - { - void Debug(int eventId, object message); - void Debug(int eventId, object message, Exception exception); - - void Info(int eventId, object message); - void Info(int eventId, object message, Exception exception); - - void Warn(int eventId, object message); - void Warn(int eventId, object message, Exception exception); - - void Error(int eventId, object message); - void Error(int eventId, object message, Exception exception); - - void Fatal(int eventId, object message); - void Fatal(int eventId, object message, Exception exception); - - void Verbose(int eventId, object message); - void Verbose(int eventId, object message, Exception exception); - bool IsVerboseEnabled { get; } - - void Trace(int eventId, object message); - void Trace(int eventId, object message, Exception exception); - bool IsTraceEnabled { get; } - } -} - diff --git a/Src/Logging/Log.cs b/Src/Logging/Log.cs deleted file mode 100644 index 43357f7f6..000000000 --- a/Src/Logging/Log.cs +++ /dev/null @@ -1,642 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Xml; -using log4net.Util; - -namespace SolarWinds.Logging -{ - /// - /// 2014-07-18: Modifyed to allow configure log4net from multiple configuration files. - /// Aseembly which needs to add own "log4net" configuration together with application - /// "log4net" configuration file should call Log.Configure([configuration file]). - /// Assembly loading event is not handling. - /// Be careful with overidding "log4net" settings. - /// Example: host and plugin configuration files - /// As well, allows properly using paterns %method and %line for log4net layout - /// - public class Log - { - private const string MasterNamespace = "SolarWinds"; - - private readonly Ext.EventID.IEventIDLog _log; - - private static readonly HashSet _configurations = new HashSet(StringComparer.OrdinalIgnoreCase); - private static readonly HashSet _assemblies = new HashSet(StringComparer.OrdinalIgnoreCase); - - /// - /// SpecialFolder CommonApplicationData + Solarwinds directory - /// - private static readonly string FolderCommonApplicationData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Solarwinds"); - - /// - /// Initializes static members of the class. - /// XP/2003 -> C:\Documents and Settings\All Users\Application Data - /// Vista/Win7/2008 -> C:\ProgramData - /// - static Log() - { - Environment.SetEnvironmentVariable("SWLogDir", FolderCommonApplicationData, EnvironmentVariableTarget.Process); - - Initialize(); - - /* - Handle assembly loading event is disabled because next loaded assembly configuration file - which has "log4net" section can override "log4net" configuration loaded from the - main application configuration file or, even worse, mext loaded assembly configuration file - can override "log4net" configruation loaded from other assemnly. - As result, logging is going to wrong log file. - - Assembly still has ability to configure "log4net" with own configuration file, basically add - own configuration to already loaded "log4net" configuration from the appication configuration file, - by calling Log.Configure() - */ - // AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad; - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static void Initialize() - { - try - { - Assembly currentAssembly = typeof(Log).Assembly; - - List asmList = new StackTrace().GetFrames() - .Where(frame => - { - MethodBase method = frame.GetMethod(); - return method != null && method.DeclaringType != null && method.DeclaringType.Assembly != null; - }) - .Select(frame => frame.GetMethod().DeclaringType.Assembly) - .ToList(); - int currentAssemblyIndex = asmList.FindLastIndex(asm => - asm.FullName.Equals(currentAssembly.FullName, StringComparison.OrdinalIgnoreCase)) + 1; - - Assembly entryAssembly = null; - if (currentAssemblyIndex < asmList.Count) - { - entryAssembly = asmList - .Skip(currentAssemblyIndex) - .LastOrDefault(asm => asm.FullName.IndexOf(MasterNamespace, StringComparison.OrdinalIgnoreCase) != -1); - } - else - { - entryAssembly = asmList.LastOrDefault(asm => asm.FullName.IndexOf(MasterNamespace, StringComparison.OrdinalIgnoreCase) != -1); - } - - if (entryAssembly == null) - { - if (currentAssemblyIndex < asmList.Count) - { - entryAssembly = asmList - .Skip(currentAssemblyIndex) - .LastOrDefault(asm => !asm.GlobalAssemblyCache); - } - else - { - entryAssembly = asmList.LastOrDefault(asm => !asm.GlobalAssemblyCache); - } - } - - if (entryAssembly == null) - { - MethodBase method = new StackTrace().GetFrames().Last().GetMethod(); - if (method != null && method.DeclaringType != null && method.DeclaringType.Assembly != null) - entryAssembly = method.DeclaringType.Assembly; - } - - Version asmVer = entryAssembly.GetName().Version; - - log4net.GlobalContext.Properties["Assembly.Version"] = asmVer.ToString(); - log4net.GlobalContext.Properties["Assembly.Version.Short"] = string.Format("{0}_{1}", asmVer.Major, asmVer.Minor); - log4net.GlobalContext.Properties["Assembly.FullName"] = entryAssembly.FullName; - log4net.GlobalContext.Properties["Runtime.Version"] = entryAssembly.ImageRuntimeVersion; - } - catch - { - // unable to set up log4net properties - } - - // Configure log4net within application configuration file - // For web apps, this will work if the config info is in web.config: - var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); - Configure(configuration.FilePath); - } - - private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) - { - try - { - Configure(string.Format("{0}.config", args.LoadedAssembly.Location)); - } - catch - { - // NotSupportedException is raised for dynamic library - access to Location property - // Simply ignore exception to allow normal behaviour for the caller - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - public Log() : this(GetCallerMethod()) - { - } - - private Log(MethodBase callerMethod) - { - Type callerType; - if ((callerType = callerMethod.DeclaringType) != null) - { - _log = Ext.EventID.EventIDLogManager.GetLogger(callerType.Assembly, callerType); - - LogAssemblyVersion(callerType.Assembly); - } - else - { - _log = Ext.EventID.EventIDLogManager.GetLogger(callerMethod.Name); - } - } - - public Log(Type callerType) - { - _log = Ext.EventID.EventIDLogManager.GetLogger(callerType.Assembly, callerType); - - LogAssemblyVersion(callerType.Assembly); - } - - public Log(string Name) - { - _log = Ext.EventID.EventIDLogManager.GetLogger(Name); - } - - /// - /// Record assembly version which initialize logging, assembly version is recorded only once per AppDomain - /// If assembly loaded as plugin, log header information (log4net.GlobalContext.Properties) - /// already initialized and contains host assembly information - /// - /// - private void LogAssemblyVersion(Assembly assembly) - { - if (assembly != null) - { - lock (_assemblies) - { - if (!_assemblies.Contains(assembly.FullName)) - { - string message = string.Format("*** Assembly {0}, .NET version {1} ***", assembly.FullName, assembly.ImageRuntimeVersion); - ForceMessageLog.Log(_log, message); - - _assemblies.Add(assembly.FullName); - } - } - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static MethodBase GetCallerMethod() - { - return new StackFrame(2, false).GetMethod(); - } - - public static void Configure(string configFile = null) - { - foreach (string fn in EnumFile(configFile)) - { - if (string.IsNullOrEmpty(fn)) continue; - - FileInfo fi = new FileInfo(fn); - if (fi.Exists) - { - lock (_configurations) - { - if (_configurations.Contains(fi.FullName)) continue; - } - - try - { - XmlDocument doc = new XmlDocument(); - doc.Load(fi.FullName); - XmlNodeList nodes = doc.GetElementsByTagName("log4net"); - if (nodes != null && nodes.Count > 0) - { - lock (_configurations) - { - if (!_configurations.Contains(fi.FullName)) - { - log4net.Config.XmlConfigurator.ConfigureAndWatch(fi); - _configurations.Add(fi.FullName); - } - } - } - } - catch { } - } - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static IEnumerable EnumFile(string fileName) - { - yield return fileName; - - MethodBase callerMethod = new StackFrame(2).GetMethod(); - if (callerMethod != null && callerMethod.DeclaringType != null) - { - Assembly callingAssembly = callerMethod.DeclaringType.Assembly; - if (callingAssembly != null) - { - yield return callingAssembly.Location + ".config"; - if (!string.IsNullOrEmpty(fileName)) - yield return Path.Combine(Path.GetDirectoryName(callingAssembly.Location), Path.GetFileName(fileName)); - } - } - - Assembly entryAssembly = Assembly.GetEntryAssembly(); - if (entryAssembly != null) - { - yield return entryAssembly.Location + ".config"; - if (!string.IsNullOrEmpty(fileName)) - yield return Path.Combine(Path.GetDirectoryName(entryAssembly.Location), Path.GetFileName(fileName)); - } - - var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); - yield return configuration.FilePath; - } - - #region Log Forwarding Members - - public void Debug(object message) - { - _log.Debug(message); - } - - public void Debug(object message, Exception exception) - { - _log.Debug(message, exception); - } - - public void DebugFormat(string format, params object[] args) - { - _log.DebugFormat(format, args); - } - - public void DebugFormat(string format, object arg0) - { - _log.DebugFormat(format, arg0); - } - - public void DebugFormat(string format, object arg0, object arg1) - { - _log.DebugFormat(format, arg0, arg1); - } - - public void DebugFormat(string format, object arg0, object arg1, object arg2) - { - _log.DebugFormat(format, arg0, arg1, arg2); - } - - public void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - _log.DebugFormat(provider, format, args); - } - - public void Debug(int eventId, object message) - { - _log.Debug(eventId, message); - } - - public void Debug(int eventId, object message, Exception exception) - { - _log.Debug(eventId, message, exception); - } - - public void Info(object message) - { - _log.Info(message); - } - - public void Info(object message, Exception exception) - { - _log.Info(message, exception); - } - - public void InfoFormat(string format, params object[] args) - { - _log.InfoFormat(format, args); - } - - public void InfoFormat(string format, object arg0) - { - _log.InfoFormat(format, arg0); - } - - public void InfoFormat(string format, object arg0, object arg1) - { - _log.InfoFormat(format, arg0, arg1); - } - - public void InfoFormat(string format, object arg0, object arg1, object arg2) - { - _log.InfoFormat(format, arg0, arg1, arg2); - } - - public void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - _log.InfoFormat(provider, format, args); - } - - public void Info(int eventId, object message) - { - _log.Info(eventId, message); - } - - public void Info(int eventId, object message, Exception exception) - { - _log.Info(eventId, message, exception); - } - - public void Warn(object message) - { - _log.Warn(message); - } - - public void Warn(object message, Exception exception) - { - _log.Warn(message, exception); - } - - public void WarnFormat(string format, params object[] args) - { - _log.WarnFormat(format, args); - } - - public void WarnFormat(string format, object arg0) - { - _log.WarnFormat(format, arg0); - } - - public void WarnFormat(string format, object arg0, object arg1) - { - _log.WarnFormat(format, arg0, arg1); - } - - public void WarnFormat(string format, object arg0, object arg1, object arg2) - { - _log.WarnFormat(format, arg0, arg1, arg2); - } - - public void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - _log.WarnFormat(provider, format, args); - } - - public void Warn(int eventId, object message) - { - _log.Warn(eventId, message); - } - - public void Warn(int eventId, object message, Exception exception) - { - _log.Warn(eventId, message, exception); - } - - public void Error(object message) - { - _log.Error(message); - } - - public void Error(object message, Exception exception) - { - _log.Error(message, exception); - } - - public void ErrorFormat(string format, params object[] args) - { - _log.ErrorFormat(format, args); - } - - public void ErrorFormat(string format, object arg0) - { - _log.ErrorFormat(format, arg0); - } - - public void ErrorFormat(string format, object arg0, object arg1) - { - _log.ErrorFormat(format, arg0, arg1); - } - - public void ErrorFormat(string format, object arg0, object arg1, object arg2) - { - _log.ErrorFormat(format, arg0, arg1, arg2); - } - - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - _log.ErrorFormat(provider, format, args); - } - - public void Error(int eventId, object message) - { - _log.Error(eventId, message); - } - - public void Error(int eventId, object message, Exception exception) - { - _log.Error(eventId, message); - } - - public void Fatal(object message) - { - _log.Fatal(message); - } - - public void Fatal(object message, Exception exception) - { - _log.Fatal(message, exception); - } - - public void FatalFormat(string format, params object[] args) - { - _log.FatalFormat(format, args); - } - - public void FatalFormat(string format, object arg0) - { - _log.FatalFormat(format, arg0); - } - - public void FatalFormat(string format, object arg0, object arg1) - { - _log.FatalFormat(format, arg0, arg1); - } - - public void FatalFormat(string format, object arg0, object arg1, object arg2) - { - _log.FatalFormat(format, arg0, arg1, arg2); - } - - public void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - _log.FatalFormat(provider, format, args); - } - - public void Fatal(int eventId, object message) - { - _log.Fatal(eventId, message); - } - - public void Fatal(int eventId, object message, Exception exception) - { - _log.Fatal(eventId, message, exception); - } - - public void Verbose(object message) - { - _log.Logger.Log(MethodBase.GetCurrentMethod().DeclaringType, - log4net.Core.Level.Verbose, message, null); - } - - public void Verbose(object message, Exception exception) - { - _log.Logger.Log(MethodBase.GetCurrentMethod().DeclaringType, - log4net.Core.Level.Verbose, message, exception); - } - - public void VerboseFormat(string format, params object[] args) - { - VerboseFormat(CultureInfo.InvariantCulture, format, args); - } - - public void VerboseFormat(IFormatProvider provider, string format, params object[] args) - { - _log.Logger.Log(MethodBase.GetCurrentMethod().DeclaringType, - log4net.Core.Level.Verbose, new SystemStringFormat(provider, format, args), null); - } - - public void Verbose(int eventId, object message) - { - _log.Verbose(eventId, message); - } - - public void Verbose(int eventId, object message, Exception exception) - { - _log.Verbose(eventId, message, exception); - } - - public void Trace(object message) - { - _log.Logger.Log(MethodBase.GetCurrentMethod().DeclaringType, - log4net.Core.Level.Trace, message, null); - } - - public void Trace(object message, Exception exception) - { - _log.Logger.Log(MethodBase.GetCurrentMethod().DeclaringType, - log4net.Core.Level.Trace, message, exception); - } - - public void TraceFormat(string format, params object[] args) - { - TraceFormat(CultureInfo.InvariantCulture, format, args); - } - - public void TraceFormat(IFormatProvider provider, string format, params object[] args) - { - _log.Logger.Log(MethodBase.GetCurrentMethod().DeclaringType, - log4net.Core.Level.Trace, new SystemStringFormat(provider, format, args), null); - } - - public void Trace(int eventId, object message) - { - _log.Trace(eventId, message); - } - - public void Trace(int eventId, object message, Exception exception) - { - _log.Trace(eventId, message, exception); - } - - public bool IsDebugEnabled - { - get { return _log.IsDebugEnabled; } - } - - public bool IsInfoEnabled - { - get { return _log.IsInfoEnabled; } - } - - public bool IsWarnEnabled - { - get { return _log.IsWarnEnabled; } - } - - public bool IsErrorEnabled - { - get { return _log.IsErrorEnabled; } - } - - public bool IsFatalEnabled - { - get { return _log.IsFatalEnabled; } - } - - public bool IsVerboseEnabled - { - get { return _log.IsVerboseEnabled; } - } - - public bool IsTraceEnabled - { - get { return _log.IsTraceEnabled; } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - public IDisposable Block() - { - return Block(new StackFrame(1, false).GetMethod().Name); - } - - public IDisposable Block(string blockName) - { - return new LogBlock(this, blockName); - } - - #endregion - } - - internal class LogBlock : IDisposable - { - private readonly string _blockName; - private readonly Log _log; - private IDisposable _threadContextStackPopper; - - public LogBlock(Log log, string blockName) - { - _log = log; - _blockName = blockName; - _threadContextStackPopper = log4net.ThreadContext.Stacks["NDC"].Push(blockName); - _log.DebugFormat("{{ {0} entered", _blockName); - } - - #region IDisposable Members - - public void Dispose() - { - if (_threadContextStackPopper != null) - { - _log.DebugFormat("}} {0} exited", _blockName); - _threadContextStackPopper.Dispose(); - _threadContextStackPopper = null; - } - //GC.SuppressFinalize(this); // no finalizer on this object, so SuppressFinalize is not needed - } - - #endregion - } -} diff --git a/Src/Logging/SolarWinds.Logging.ExternalAnnotations.xml b/Src/Logging/SolarWinds.Logging.ExternalAnnotations.xml deleted file mode 100644 index c883712c8..000000000 --- a/Src/Logging/SolarWinds.Logging.ExternalAnnotations.xml +++ /dev/null @@ -1,534 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - format - - - - - - - - - format - - - - - - - - - format - - - - - - - - - - - - format - - - - - - - - - - - - - - - format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - format - - - - - - - - - format - - - - - - - - - format - - - - - - - - - - - - format - - - - - - - - - - - - - - - format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - format - - - - - - - - - format - - - - - - - - - format - - - - - - - - - - - - format - - - - - - - - - - - - - - - format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - format - - - - - - - - - format - - - - - - - - - format - - - - - - - - - - - - format - - - - - - - - - - - - - - - format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - format - - - - - - - - - - format - - - - - - - - - - format - - - - - - - - - - - - format - - - - - - - - - - - - - - - format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - format - - - - - - - - - format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - format - - - - - - - - - format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Src/Logging/SolarWinds.Logging.csproj b/Src/Logging/SolarWinds.Logging.csproj deleted file mode 100644 index d2b1bf643..000000000 --- a/Src/Logging/SolarWinds.Logging.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - net48;netstandard2.0 - SolarWinds - false - false - false - false - true - true - 1570,1571,1572,1573,1587,1591,1710,1711,1712 - - - - - - - - - - Properties\CommonAssemblyInfo.cs - - - - - - PreserveNewest - - - diff --git a/Src/OrionSDK.sln b/Src/OrionSDK.sln index c9c0c58a0..0de120ddb 100644 --- a/Src/OrionSDK.sln +++ b/Src/OrionSDK.sln @@ -5,8 +5,6 @@ VisualStudioVersion = 16.0.30320.27 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SolarWinds.InformationService.Contract", "Contract\SolarWinds.InformationService.Contract.csproj", "{7AB6A2C2-AD8F-40AF-9527-B12EB4B78B0A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SolarWinds.Logging", "Logging\SolarWinds.Logging.csproj", "{D6A25E78-F75D-4368-8244-BB33AAAA4AB2}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SwisPowerShell", "SwisPowerShell\SwisPowerShell.csproj", "{CEBB636F-B1BC-4C1D-847C-B059532B4699}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SwqlStudio", "SwqlStudio\SwqlStudio.csproj", "{B4F89558-AE9F-4704-B210-6949EF8DD65B}" @@ -37,16 +35,6 @@ Global {7AB6A2C2-AD8F-40AF-9527-B12EB4B78B0A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {7AB6A2C2-AD8F-40AF-9527-B12EB4B78B0A}.Release|Mixed Platforms.Build.0 = Release|Any CPU {7AB6A2C2-AD8F-40AF-9527-B12EB4B78B0A}.Release|x86.ActiveCfg = Release|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Debug|x86.ActiveCfg = Debug|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Release|Any CPU.Build.0 = Release|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {D6A25E78-F75D-4368-8244-BB33AAAA4AB2}.Release|x86.ActiveCfg = Release|Any CPU {CEBB636F-B1BC-4C1D-847C-B059532B4699}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CEBB636F-B1BC-4C1D-847C-B059532B4699}.Debug|Any CPU.Build.0 = Debug|Any CPU {CEBB636F-B1BC-4C1D-847C-B059532B4699}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU From 0b3117f0d81fe193e0b0a06fb38b08327cc2a484 Mon Sep 17 00:00:00 2001 From: Dan Jagnow Date: Wed, 31 Mar 2021 18:00:34 -0500 Subject: [PATCH 5/5] Updated the installer Updated the installer, removing SolarWinds.Logging.dll and log4net.dll and adding the new dependencies. --- Src/Install/Product.wxs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/Src/Install/Product.wxs b/Src/Install/Product.wxs index edaf0ee1e..6efc4e4db 100644 --- a/Src/Install/Product.wxs +++ b/Src/Install/Product.wxs @@ -119,7 +119,6 @@ - @@ -132,7 +131,6 @@ - @@ -169,11 +167,21 @@ + + + + + + + - - + + + + + @@ -182,6 +190,8 @@ + + @@ -195,11 +205,21 @@ + + + + + + + - - + + + + + @@ -208,6 +228,8 @@ + +