diff --git a/src/Agent/NewRelic/Agent/Core/Agent.cs b/src/Agent/NewRelic/Agent/Core/Agent.cs index 6386366b8..e9e5f7291 100644 --- a/src/Agent/NewRelic/Agent/Core/Agent.cs +++ b/src/Agent/NewRelic/Agent/Core/Agent.cs @@ -213,7 +213,7 @@ bool ShouldRunExplain() var vendorValidationResult = vendorValidateShouldExplain(); if (!vendorValidationResult.IsValid) { - Log.DebugFormat("Failed vendor condition for executing explain plan: {0}", vendorValidationResult.ValidationMessage); + Log.Debug("Failed vendor condition for executing explain plan: {0}", vendorValidationResult.ValidationMessage); return false; } } @@ -281,7 +281,7 @@ public void HandleWrapperException(Exception exception) return; } - Log.Error($"An exception occurred in a wrapper: {exception}"); + Log.Error(exception, "An exception occurred in a wrapper"); } #endregion Error handling @@ -336,7 +336,7 @@ public Stream TryGetStreamInjector(Stream stream, Encoding encoding, string cont } catch (Exception ex) { - Log.Error($"RUM: Failed to build Browser Monitoring agent script: {ex}"); + Log.Error(ex, "RUM: Failed to build Browser Monitoring agent script"); { return null; } diff --git a/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs b/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs index 64f29e3f0..4653fc732 100644 --- a/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs +++ b/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs @@ -26,7 +26,7 @@ public class AgentHealthReporter : ConfigurationBasedService, IAgentHealthReport private readonly IMetricBuilder _metricBuilder; private readonly IScheduler _scheduler; - private readonly IList _recurringLogDatas = new ConcurrentList(); + private readonly IList _recurringLogData = new ConcurrentList(); private readonly IDictionary _agentHealthEventCounters = new Dictionary(); private readonly ConcurrentDictionary _logLinesCountByLevel = new ConcurrentDictionary(); private readonly ConcurrentDictionary _logDeniedCountByLevel = new ConcurrentDictionary(); @@ -63,9 +63,9 @@ public override void Dispose() private void LogPeriodicReport() { - foreach (var data in _recurringLogDatas) + foreach (var logMessage in _recurringLogData) { - data?.LogAction(data.Message); + Log.Debug(logMessage); } List events = new List(); @@ -252,7 +252,7 @@ public void ReportWrapperShutdown(IWrapper wrapper, Method method) } Log.Error($"Wrapper {wrapperName} is being disabled for {method.MethodName} due to too many consecutive exceptions. All other methods using this wrapper will continue to be instrumented. This will reduce the functionality of the agent until the agent is restarted."); - _recurringLogDatas.Add(new RecurringLogData(Log.Debug, $"Wrapper {wrapperName} was disabled for {method.MethodName} at {DateTime.Now} due to too many consecutive exceptions. All other methods using this wrapper will continue to be instrumented. This will reduce the functionality of the agent until the agent is restarted.")); + _recurringLogData.Add($"Wrapper {wrapperName} was disabled for {method.MethodName} at {DateTime.Now} due to too many consecutive exceptions. All other methods using this wrapper will continue to be instrumented. This will reduce the functionality of the agent until the agent is restarted."); } public void ReportIfHostIsLinuxOs() @@ -714,7 +714,7 @@ private void TrySend(MetricWireModel metric) if (_publishMetricDelegate == null) { - Log.WarnFormat("No PublishMetricDelegate to flush metric '{0}' through.", metric.MetricName.Name); + Log.Warn("No PublishMetricDelegate to flush metric '{0}' through.", metric.MetricName.Name); return; } @@ -724,7 +724,7 @@ private void TrySend(MetricWireModel metric) } catch (Exception ex) { - Log.Error(ex); + Log.Error(ex, "TrySend() failed"); } } private bool TryGetCount(InterlockedCounter counter, out int metricCount) @@ -811,17 +811,5 @@ protected override void OnConfigurationUpdated(ConfigurationUpdateSource configu // Some one time metrics are reporting configured values, so we want to re-report them if the configuration changed _oneTimeMetricsCollected = false; } - - private class RecurringLogData - { - public readonly Action LogAction; - public readonly string Message; - - public RecurringLogData(Action logAction, string message) - { - LogAction = logAction; - Message = message; - } - } } } diff --git a/src/Agent/NewRelic/Agent/Core/AgentInstallConfiguration.cs b/src/Agent/NewRelic/Agent/Core/AgentInstallConfiguration.cs index 50fe93b0a..67c97d7fb 100644 --- a/src/Agent/NewRelic/Agent/Core/AgentInstallConfiguration.cs +++ b/src/Agent/NewRelic/Agent/Core/AgentInstallConfiguration.cs @@ -111,7 +111,7 @@ private static string GetAgentVersion() } catch (Exception ex) { - Log.Error($"Failed to determine agent version. {ex}"); + Log.Error(ex, "Failed to determine agent version."); return "?.?.?.?"; } } diff --git a/src/Agent/NewRelic/Agent/Core/AgentManager.cs b/src/Agent/NewRelic/Agent/Core/AgentManager.cs index 8b704a8f5..a98187236 100644 --- a/src/Agent/NewRelic/Agent/Core/AgentManager.cs +++ b/src/Agent/NewRelic/Agent/Core/AgentManager.cs @@ -55,7 +55,7 @@ protected override IAgentManager CreateInstance() { try { - Log.Error($"There was an error initializing the agent: {exception}"); + Log.Error(exception, "There was an error initializing the agent"); return DisabledAgentManager; } catch @@ -182,7 +182,7 @@ private void Initialize() private void LogInitialized() { - Log.InfoFormat("The New Relic .NET Agent v{0} started (pid {1}) on app domain '{2}'", AgentInstallConfiguration.AgentVersion, AgentInstallConfiguration.ProcessId, AgentInstallConfiguration.AppDomainAppVirtualPath ?? AgentInstallConfiguration.AppDomainName); + Log.Info("The New Relic .NET Agent v{0} started (pid {1}) on app domain '{2}'", AgentInstallConfiguration.AgentVersion, AgentInstallConfiguration.ProcessId, AgentInstallConfiguration.AppDomainAppVirtualPath ?? AgentInstallConfiguration.AppDomainName); //Log here for debugging configuration issues if (Log.IsDebugEnabled) { @@ -270,7 +270,7 @@ private void LogInitialized() { if (!string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable(ev))) { - Log.DebugFormat("Environment Variable {0} value: {1}", ev, System.Environment.GetEnvironmentVariable(ev)); + Log.Debug("Environment Variable {0} value: {1}", ev, System.Environment.GetEnvironmentVariable(ev)); } } @@ -278,7 +278,7 @@ private void LogInitialized() { if (!string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable(evs))) { - Log.DebugFormat("Environment Variable {0} is configured with a value. Not logging potentially sensitive value", evs); + Log.Debug("Environment Variable {0} is configured with a value. Not logging potentially sensitive value", evs); } } @@ -288,12 +288,12 @@ private void LogInitialized() #if NETFRAMEWORK if (NewRelic.Core.DotnetVersion.IsUnsupportedDotnetFrameworkVersion(AgentInstallConfiguration.DotnetFrameworkVersion)) { - Log.WarnFormat("Unsupported installed .NET Framework version {0} dectected. Please use a version of .NET Framework >= 4.6.2.", AgentInstallConfiguration.DotnetFrameworkVersion); + Log.Warn("Unsupported installed .NET Framework version {0} dectected. Please use a version of .NET Framework >= 4.6.2.", AgentInstallConfiguration.DotnetFrameworkVersion); } #else if (NewRelic.Core.DotnetVersion.IsUnsupportedDotnetCoreVersion(AgentInstallConfiguration.DotnetCoreVersion)) { - Log.WarnFormat("Unsupported .NET version {0} detected. Please use a version of .NET >= net6.", AgentInstallConfiguration.DotnetCoreVersion); + Log.Warn("Unsupported .NET version {0} detected. Please use a version of .NET >= net6.", AgentInstallConfiguration.DotnetCoreVersion); } #endif } @@ -340,7 +340,7 @@ public ITracer GetTracerImpl(string tracerFactoryName, uint tracerArguments, str } catch (Exception e) { - Log.Error($"Tracer invocation error: {e}"); + Log.Error(e, "Tracer invocation error"); return null; } } @@ -375,11 +375,11 @@ private void Shutdown(bool cleanShutdown) Log.Debug("Shutting down public agent services..."); StopServices(); - Log.InfoFormat("The New Relic .NET Agent v{0} has shutdown (pid {1}) on app domain '{2}'", AgentInstallConfiguration.AgentVersion, AgentInstallConfiguration.ProcessId, AgentInstallConfiguration.AppDomainAppVirtualPath ?? AgentInstallConfiguration.AppDomainName); + Log.Info("The New Relic .NET Agent v{0} has shutdown (pid {1}) on app domain '{2}'", AgentInstallConfiguration.AgentVersion, AgentInstallConfiguration.ProcessId, AgentInstallConfiguration.AppDomainAppVirtualPath ?? AgentInstallConfiguration.AppDomainName); } catch (Exception e) { - Log.Debug($"Shutdown error: {e}"); + Log.Debug(e, "Shutdown error"); } finally { diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/MetricStatsCollectionQueue.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/MetricStatsCollectionQueue.cs index afaf1f79a..bde01bba0 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/MetricStatsCollectionQueue.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/MetricStatsCollectionQueue.cs @@ -66,7 +66,7 @@ private void AddMetricsToCollection(ConcurrentQueue stats } catch (Exception e) { - Log.Warn($"Exception dequeueing/creating stats collection: {e}"); + Log.Warn(e, "Exception dequeueing/creating stats collection"); } finally { diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionTraceAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionTraceAggregator.cs index a8d15bb40..a0781b378 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionTraceAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionTraceAggregator.cs @@ -106,7 +106,7 @@ private void LogUnencodedTraceData(IEnumerable sample { if (sample != null) { - Log.DebugFormat("TransactionTraceData: {0}", SerializeTransactionTraceData(sample)); + Log.Debug("TransactionTraceData: {0}", SerializeTransactionTraceData(sample)); } } } diff --git a/src/Agent/NewRelic/Agent/Core/Api/AgentApiImplementation.cs b/src/Agent/NewRelic/Agent/Core/Api/AgentApiImplementation.cs index 27922cd7f..be5989f5b 100644 --- a/src/Agent/NewRelic/Agent/Core/Api/AgentApiImplementation.cs +++ b/src/Agent/NewRelic/Agent/Core/Api/AgentApiImplementation.cs @@ -79,7 +79,7 @@ public void InitializePublicAgent(object publicAgent) { try { - Log.Error($"Failed to initialize the Agent API: {ex}"); + Log.Error(ex, "Failed to initialize the Agent API"); } catch (Exception)//Swallow the error { @@ -728,7 +728,7 @@ private static string GetCustomMetricSuffix(string name) { if (_configurationService.Configuration.DistributedTracingEnabled) { - Log.FinestFormat(DistributedTracingIsEnabledIgnoringCall, nameof(GetRequestMetadata)); + Log.Finest(DistributedTracingIsEnabledIgnoringCall, nameof(GetRequestMetadata)); return Enumerable.Empty>(); } @@ -742,7 +742,7 @@ private static string GetCustomMetricSuffix(string name) { if (_configurationService.Configuration.DistributedTracingEnabled) { - Log.FinestFormat(DistributedTracingIsEnabledIgnoringCall, nameof(GetResponseMetadata)); + Log.Finest(DistributedTracingIsEnabledIgnoringCall, nameof(GetResponseMetadata)); return Enumerable.Empty>(); } diff --git a/src/Agent/NewRelic/Agent/Core/Api/AgentBridgeApi.cs b/src/Agent/NewRelic/Agent/Core/Api/AgentBridgeApi.cs index 9bd934d3e..7f7b9cfbe 100644 --- a/src/Agent/NewRelic/Agent/Core/Api/AgentBridgeApi.cs +++ b/src/Agent/NewRelic/Agent/Core/Api/AgentBridgeApi.cs @@ -40,7 +40,7 @@ public TransactionBridgeApi CurrentTransaction { try { - Log.ErrorFormat("Failed to get CurrentTransaction: {0}", ex); + Log.Error(ex, "Failed to get CurrentTransaction"); } catch (Exception) { @@ -67,7 +67,7 @@ public object TraceMetadata { try { - Log.ErrorFormat("Failed to get TraceMetadata: {0}", ex); + Log.Error(ex, "Failed to get TraceMetadata"); } catch (Exception) { @@ -93,7 +93,7 @@ public object TraceMetadata { try { - Log.ErrorFormat("Error in GetLinkingMetadata: {0}", ex); + Log.Error(ex, "Error in GetLinkingMetadata"); } catch (Exception) { diff --git a/src/Agent/NewRelic/Agent/Core/Api/DistributedTraceApiModel.cs b/src/Agent/NewRelic/Agent/Core/Api/DistributedTraceApiModel.cs index 422f3272d..961f2b48a 100644 --- a/src/Agent/NewRelic/Agent/Core/Api/DistributedTraceApiModel.cs +++ b/src/Agent/NewRelic/Agent/Core/Api/DistributedTraceApiModel.cs @@ -35,7 +35,7 @@ string DecodePayload() { try { - Log.ErrorFormat("Failed to get DistributedTraceApiModel.Text: {0}", ex); + Log.Error(ex, "Failed to get DistributedTraceApiModel.Text"); } catch (Exception) { diff --git a/src/Agent/NewRelic/Agent/Core/Api/SpanBridgeApi.cs b/src/Agent/NewRelic/Agent/Core/Api/SpanBridgeApi.cs index 8afd85a3d..631c28fc8 100644 --- a/src/Agent/NewRelic/Agent/Core/Api/SpanBridgeApi.cs +++ b/src/Agent/NewRelic/Agent/Core/Api/SpanBridgeApi.cs @@ -39,7 +39,7 @@ public object AddCustomAttribute(string key, object value) { try { - Log.Error($"Error in AddCustomAttribute: {ex}"); + Log.Error(ex, "Error in AddCustomAttribute"); } catch (Exception) { @@ -62,7 +62,7 @@ public object SetName(string name) { try { - Log.Error($"Error in SetName: {ex}"); + Log.Error(ex, "Error in SetName"); } catch (Exception) { diff --git a/src/Agent/NewRelic/Agent/Core/Api/TransactionBridgeApi.cs b/src/Agent/NewRelic/Agent/Core/Api/TransactionBridgeApi.cs index 065bc9605..672880222 100644 --- a/src/Agent/NewRelic/Agent/Core/Api/TransactionBridgeApi.cs +++ b/src/Agent/NewRelic/Agent/Core/Api/TransactionBridgeApi.cs @@ -79,7 +79,7 @@ public void InsertDistributedTraceHeaders(T carrier, Action(T, Action): {0}", ex); + Log.Error(ex, "Error in InsertDistributedTraceHeaders(T, Action)"); } catch (Exception) { @@ -102,7 +102,7 @@ public void AcceptDistributedTraceHeaders(T carrier, Func(T, Func>, TransportType): {0}", ex); + Log.Error(ex, "Error in AcceptDistributedTraceHeaders(T, Func>, TransportType)"); } catch (Exception) { @@ -138,7 +138,7 @@ public object AddCustomAttribute(string key, object value) { try { - Log.Error($"Error in AddCustomAttribute: {ex}"); + Log.Error(ex, "Error in AddCustomAttribute"); } catch (Exception) { @@ -167,7 +167,7 @@ public SpanBridgeApi CurrentSpan { try { - Log.ErrorFormat("Failed to get CurrentSpan: {0}", ex); + Log.Error(ex, "Failed to get CurrentSpan"); } catch (Exception) { @@ -195,7 +195,7 @@ public void SetUserId(string userid) { try { - Log.Error($"Error in SetUserId: {ex}"); + Log.Error(ex, "Error in SetUserId"); } catch (Exception) { diff --git a/src/Agent/NewRelic/Agent/Core/Attributes/AttributeValueCollection.cs b/src/Agent/NewRelic/Agent/Core/Attributes/AttributeValueCollection.cs index b7a6498e6..5e4db37f8 100644 --- a/src/Agent/NewRelic/Agent/Core/Attributes/AttributeValueCollection.cs +++ b/src/Agent/NewRelic/Agent/Core/Attributes/AttributeValueCollection.cs @@ -286,7 +286,7 @@ public void MakeImmutable() } catch (Exception ex) { - Log.Finest($"{attribVal.AttributeDefinition.Classification} Attribute '{attribVal.AttributeDefinition.Name}' was not recorded - exception occurred while resolving value (lazy) - {ex}"); + Log.Finest(ex, "{attribVal.AttributeDefinition.Classification} Attribute '{attribVal.AttributeDefinition.Name}' was not recorded - exception occurred while resolving value (lazy)"); itemsToRemove.Add(attribVal); } } diff --git a/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringPrereqChecker.cs b/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringPrereqChecker.cs index 351d2329e..191595f41 100644 --- a/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringPrereqChecker.cs +++ b/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringPrereqChecker.cs @@ -82,7 +82,7 @@ private static bool IsHtmlContent(string contentType) } catch (Exception ex) { - Log.Debug($"Unable to parse content type: {ex}"); + Log.Debug(ex, "Unable to parse content type"); return false; } } @@ -134,7 +134,7 @@ private static bool IsMatch(string path, Regex regex) } catch (Exception e) { - Log.Error($"Exception attempting to validate request path for Browser Instrumentation blacklisting: {e}"); + Log.Error(e, "Exception attempting to validate request path for Browser Instrumentation blacklisting"); return false; } } diff --git a/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringStreamInjector.cs b/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringStreamInjector.cs index 75f75ec42..a0ad8e164 100644 --- a/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringStreamInjector.cs +++ b/src/Agent/NewRelic/Agent/Core/BrowserMonitoring/BrowserMonitoringStreamInjector.cs @@ -105,7 +105,7 @@ private void PassThroughStreamWriter(byte[] buffer, int offset, int count) } catch (Exception exception) { - Log.Error($"Failed to inject JavaScript agent into response stream: {exception}"); + Log.Error(exception, "Failed to inject JavaScript agent into response stream"); scriptInjected = false; buffer = originalBuffer; offset = originalOffset; diff --git a/src/Agent/NewRelic/Agent/Core/CallStack/CallStackManager.cs b/src/Agent/NewRelic/Agent/Core/CallStack/CallStackManager.cs index 20df753a2..84e46c5b6 100644 --- a/src/Agent/NewRelic/Agent/Core/CallStack/CallStackManager.cs +++ b/src/Agent/NewRelic/Agent/Core/CallStack/CallStackManager.cs @@ -61,14 +61,14 @@ private static ICallStackManagerFactory CreateFactory(IEnumerable f.Type == ContextStorageType.AsyncLocal); if (asyncLocalFactory != null) { - Log.DebugFormat("Using async storage {0} for call stack with AsyncCallStackManagerFactory", asyncLocalFactory.GetType().FullName); + Log.Debug("Using async storage {0} for call stack with AsyncCallStackManagerFactory", asyncLocalFactory.GetType().FullName); return new AsyncCallStackManagerFactory(asyncLocalFactory); } var callContextLogicalDataFactory = listOfFactories.FirstOrDefault(f => f.Type == ContextStorageType.CallContextLogicalData); if (callContextLogicalDataFactory != null) { - Log.DebugFormat("Using async storage {0} for call stack with AsyncCallStackManagerFactory", callContextLogicalDataFactory.GetType().FullName); + Log.Debug("Using async storage {0} for call stack with AsyncCallStackManagerFactory", callContextLogicalDataFactory.GetType().FullName); return new AsyncCallStackManagerFactory(callContextLogicalDataFactory); } diff --git a/src/Agent/NewRelic/Agent/Core/Commands/InstrumentationUpdateCommand.cs b/src/Agent/NewRelic/Agent/Core/Commands/InstrumentationUpdateCommand.cs index 4a49c7df4..31a2131d3 100644 --- a/src/Agent/NewRelic/Agent/Core/Commands/InstrumentationUpdateCommand.cs +++ b/src/Agent/NewRelic/Agent/Core/Commands/InstrumentationUpdateCommand.cs @@ -52,7 +52,7 @@ private string InstrumentationUpdate(IDictionary arguments) } catch (Exception e) { - Log.Error(e); + Log.Error(e, "The instrumentation update was malformed"); return "The instrumentation update was malformed"; } } diff --git a/src/Agent/NewRelic/Agent/Core/Commands/StopThreadProfilerCommand.cs b/src/Agent/NewRelic/Agent/Core/Commands/StopThreadProfilerCommand.cs index d707afff4..159083ad8 100644 --- a/src/Agent/NewRelic/Agent/Core/Commands/StopThreadProfilerCommand.cs +++ b/src/Agent/NewRelic/Agent/Core/Commands/StopThreadProfilerCommand.cs @@ -48,7 +48,7 @@ private string StopThreadProfilingSessions(IDictionary arguments } catch (InvalidProfileIdException e) { - Log.Error(e.Message); + Log.Error(e, "StopThreadProfilingSessions() failed"); return e.Message; } diff --git a/src/Agent/NewRelic/Agent/Core/Commands/ThreadProfilerCommandArgs.cs b/src/Agent/NewRelic/Agent/Core/Commands/ThreadProfilerCommandArgs.cs index c26f0e6ec..6d4e7514f 100644 --- a/src/Agent/NewRelic/Agent/Core/Commands/ThreadProfilerCommandArgs.cs +++ b/src/Agent/NewRelic/Agent/Core/Commands/ThreadProfilerCommandArgs.cs @@ -64,7 +64,7 @@ private uint ParseFloatArgument(IDictionary arguments, string ar } catch (OverflowException) { - Log.DebugFormat("Received a sample_period value with start_profiler command that caused an overflow converting to milliseconds. value = {0}", parsedValue); + Log.Debug("Received a sample_period value with start_profiler command that caused an overflow converting to milliseconds. value = {0}", parsedValue); return (uint)maxValue * 1000; } } diff --git a/src/Agent/NewRelic/Agent/Core/Config/ConfigurationLoader.cs b/src/Agent/NewRelic/Agent/Core/Config/ConfigurationLoader.cs index 66c7c7f24..8c019aa85 100644 --- a/src/Agent/NewRelic/Agent/Core/Config/ConfigurationLoader.cs +++ b/src/Agent/NewRelic/Agent/Core/Config/ConfigurationLoader.cs @@ -154,7 +154,7 @@ private static string TryGetAgentConfigFileFromAppConfig() return null; } - Log.InfoFormat("Configuration file found in path pointed to by NewRelic.ConfigFile appSetting: {0}", fileName); + Log.Info("Configuration file found in path pointed to by NewRelic.ConfigFile appSetting: {0}", fileName); return fileName; } catch (Exception) @@ -171,7 +171,7 @@ private static string TryGetAgentConfigFileFromAppConfig() return null; } - Log.InfoFormat("Configuration file found in path pointed to by NewRelic.ConfigFile appSetting of app/web config: {0}", fileName); + Log.Info("Configuration file found in path pointed to by NewRelic.ConfigFile appSetting of app/web config: {0}", fileName); return fileName; } catch (Exception) @@ -195,7 +195,7 @@ private static string TryGetAgentConfigFileFromAppRoot() filename = Path.Combine(directory, NewRelicConfigFileName); if (File.Exists(filename)) { - Log.InfoFormat("Configuration file found in app/web root directory: {0}", filename); + Log.Info("Configuration file found in app/web root directory: {0}", filename); return filename; } } @@ -204,7 +204,7 @@ private static string TryGetAgentConfigFileFromAppRoot() filename = Path.Combine(currentDirectory, NewRelicConfigFileName); if (File.Exists(filename)) { - Log.InfoFormat("Configuration file found in app/web root directory: {0}", filename); + Log.Info("Configuration file found in app/web root directory: {0}", filename); return filename; } @@ -227,7 +227,7 @@ private static string TryGetAgentConfigFileFromAppRoot() if (!FileExists(fileName)) return null; - Log.InfoFormat("Configuration file found in app/web root directory: {0}", fileName); + Log.Info("Configuration file found in app/web root directory: {0}", fileName); return fileName; } catch (Exception) @@ -250,7 +250,7 @@ private static string TryGetAgentConfigFileFromExecutionPath() if (!FileExists(fileName)) return null; - Log.InfoFormat("Configuration file found in execution path: {0}", fileName); + Log.Info("Configuration file found in execution path: {0}", fileName); return fileName; } catch (Exception) @@ -271,7 +271,7 @@ private static string TryGetAgentConfigFileFromNewRelicHome() if (!FileExists(fileName)) return null; - Log.InfoFormat("Configuration file found in New Relic home directory: {0}", fileName); + Log.Info("Configuration file found in New Relic home directory: {0}", fileName); return fileName; } catch (Exception) @@ -287,7 +287,7 @@ private static string TryGetAgentConfigFileFromCurrentDirectory() if (!FileExists(NewRelicConfigFileName)) return null; - Log.InfoFormat("Configuration file found in current working directory: {0}", NewRelicConfigFileName); + Log.Info("Configuration file found in current working directory: {0}", NewRelicConfigFileName); return NewRelicConfigFileName; } catch (Exception) @@ -363,10 +363,10 @@ private static void ValidationEventHandler(object sender, ValidationEventArgs e) switch (e.Severity) { case XmlSeverityType.Error: - Log.ErrorFormat("An error occurred parsing {0} - {1}", NewRelicConfigFileName, e.Message); + Log.Error(e.Exception, "An error occurred parsing {0}", NewRelicConfigFileName); break; case XmlSeverityType.Warning: - Log.WarnFormat("{0} warning - {1}", NewRelicConfigFileName, e.Message); + Log.Warn(e.Exception, "{0} warning", NewRelicConfigFileName); break; } @@ -405,7 +405,7 @@ public static configuration InitializeFromXml(string configXml, Func con } catch (Exception ex) { - Log.WarnFormat("An unknown error occurred when performing XML schema validation on config file {0}: {1}", NewRelicConfigFileName, ex.Message); + Log.Warn(ex, "An unknown error occurred when performing XML schema validation on config file {0}", NewRelicConfigFileName); } EventBus.Publish(new ConfigurationDeserializedEvent(config)); @@ -438,7 +438,7 @@ private static void ValidateConfigXmlWithSchema(string configXml, string schemaX } catch (Exception ex) { - Log.WarnFormat("An error occurred parsing {0} - {1}", NewRelicConfigFileName, ex.Message); + Log.Warn(ex, "An error occurred parsing {0}", NewRelicConfigFileName); } } } @@ -455,7 +455,7 @@ private static string GetConfigSchemaContents() } catch (Exception ex) { - Log.WarnFormat("An error occurred reading config file schema: {0}", ex.Message); + Log.Warn(ex, "An error occurred reading config file schema"); } return configSchemaContents; @@ -501,7 +501,7 @@ private static void RemoveSslAttribute(XmlDocument document) var sslAttribute = node?.Attributes?["ssl"]; if (sslAttribute != null) { - Log.WarnFormat("'ssl' is no longer a configurable service attribute and cannot be disabled. Please remove from {0}.", NewRelicConfigFileName); + Log.Warn("'ssl' is no longer a configurable service attribute and cannot be disabled. Please remove from {0}.", NewRelicConfigFileName); node.Attributes.Remove(sslAttribute); } diff --git a/src/Agent/NewRelic/Agent/Core/Config/ConfigurationTracker.cs b/src/Agent/NewRelic/Agent/Core/Config/ConfigurationTracker.cs index 5eba703b1..d8bac0330 100644 --- a/src/Agent/NewRelic/Agent/Core/Config/ConfigurationTracker.cs +++ b/src/Agent/NewRelic/Agent/Core/Config/ConfigurationTracker.cs @@ -27,7 +27,7 @@ public ConfigurationTracker(IConfigurationService configurationService) if (fileName == null) return; - Log.InfoFormat("Reading configuration from \"{0}\"", fileName); + Log.Info("Reading configuration from \"{0}\"", fileName); _lastWriteTime = File.GetLastWriteTimeUtc(fileName); diff --git a/src/Agent/NewRelic/Agent/Core/Configuration/ConfigurationService.cs b/src/Agent/NewRelic/Agent/Core/Configuration/ConfigurationService.cs index 28fb62029..18283fce9 100644 --- a/src/Agent/NewRelic/Agent/Core/Configuration/ConfigurationService.cs +++ b/src/Agent/NewRelic/Agent/Core/Configuration/ConfigurationService.cs @@ -63,7 +63,7 @@ private void OnConfigurationDeserialized(ConfigurationDeserializedEvent configur private static void UpdateLogLevel(configuration localConfiguration) { - Log.InfoFormat("The log level was updated to {0}", localConfiguration.LogConfig.LogLevel); + Log.Info("The log level was updated to {0}", localConfiguration.LogConfig.LogLevel); LoggerBootstrapper.UpdateLoggingLevel(localConfiguration.LogConfig.LogLevel); } @@ -76,7 +76,7 @@ private void OnServerConfigurationUpdated(ServerConfigurationUpdatedEvent server } catch (Exception exception) { - Log.Error($"Unable to parse the Configuration data from the server so no server side configuration was applied: {exception}"); + Log.Error(exception, "Unable to parse the Configuration data from the server so no server side configuration was applied"); } } diff --git a/src/Agent/NewRelic/Agent/Core/Configuration/DefaultConfiguration.cs b/src/Agent/NewRelic/Agent/Core/Configuration/DefaultConfiguration.cs index 72b05d301..edc05de3f 100644 --- a/src/Agent/NewRelic/Agent/Core/Configuration/DefaultConfiguration.cs +++ b/src/Agent/NewRelic/Agent/Core/Configuration/DefaultConfiguration.cs @@ -2397,8 +2397,8 @@ private IList ReadUrlBlacklist(configuration config) } catch (Exception ex) { - Log.ErrorFormat("A Browser Monitoring Request Path failed regular expression parsing: {0}", - p.regex, ex); + Log.Error(ex, "A Browser Monitoring Request Path failed regular expression parsing: {0}", + p.regex); } } } @@ -2463,14 +2463,14 @@ private static string UpdateRegexForDotNet(string replacement) { if (rule.Terms == null) { - Log.WarnFormat("Ignoring transaction_segment_term with null terms for prefix '{0}'", rule.Prefix); + Log.Warn("Ignoring transaction_segment_term with null terms for prefix '{0}'", rule.Prefix); return null; } var prefix = TryGetValidPrefix(rule.Prefix); if (prefix == null) { - Log.WarnFormat("Ignoring transaction_segment_term with invalid prefix '{0}'", rule.Prefix); + Log.Warn("Ignoring transaction_segment_term with invalid prefix '{0}'", rule.Prefix); return null; } @@ -2731,7 +2731,7 @@ private void LogDisabledPropertyUse(string disabledPropertyName, string newPrope { replacementText = $"Use {newPropertyName} instead."; } - Log.WarnFormat("Configuration property '{0}' is disabled (unused) and will be removed from the config schema in a future release. {1} See https://docs.newrelic.com/docs/agents/net-agent/configuration/net-agent-configuration/ for details.", disabledPropertyName, replacementText); + Log.Warn("Configuration property '{0}' is disabled (unused) and will be removed from the config schema in a future release. {1} See https://docs.newrelic.com/docs/agents/net-agent/configuration/net-agent-configuration/ for details.", disabledPropertyName, replacementText); } int? _databaseStatementCacheCapacity = null; diff --git a/src/Agent/NewRelic/Agent/Core/Configuration/IConfigurationManagerStatic.cs b/src/Agent/NewRelic/Agent/Core/Configuration/IConfigurationManagerStatic.cs index c7ce4e79d..6bfc27ffc 100644 --- a/src/Agent/NewRelic/Agent/Core/Configuration/IConfigurationManagerStatic.cs +++ b/src/Agent/NewRelic/Agent/Core/Configuration/IConfigurationManagerStatic.cs @@ -66,7 +66,7 @@ public string GetAppSetting(string key) } catch (Exception ex) { - Log.Error($"Failed to read '{key}' using System.Configuration.ConfigurationManager.AppSettings. Reading New Relic configuration values using System.Configuration.ConfigurationManager.AppSettings will be disabled. Exception: {ex}"); + Log.Error(ex, $"Failed to read '{key}' using System.Configuration.ConfigurationManager.AppSettings. Reading New Relic configuration values using System.Configuration.ConfigurationManager.AppSettings will be disabled."); localConfigChecksDisabled = true; return null; } @@ -91,13 +91,13 @@ public string GetAppSetting(string key) } catch (FileNotFoundException e) { - if (Log.IsDebugEnabled) Log.Debug($"appsettings.json will not be searched for config values because this application does not reference: {e.FileName}."); + Log.Debug(e, "appsettings.json will not be searched for config values because this application does not reference: {e.FileName}."); localConfigChecksDisabled = true; return null; } catch (Exception e) { - if (Log.IsDebugEnabled) Log.Debug($"appsettings.json will not be searched for config values because an error was encountered: {e}"); + Log.Debug(e, "appsettings.json will not be searched for config values because an error was encountered"); localConfigChecksDisabled = true; return null; } diff --git a/src/Agent/NewRelic/Agent/Core/Configuration/ServerConfiguration.cs b/src/Agent/NewRelic/Agent/Core/Configuration/ServerConfiguration.cs index d767b547f..aba34c60c 100644 --- a/src/Agent/NewRelic/Agent/Core/Configuration/ServerConfiguration.cs +++ b/src/Agent/NewRelic/Agent/Core/Configuration/ServerConfiguration.cs @@ -334,7 +334,7 @@ public static ServerConfiguration FromDeserializedReturnValue(object deserialize [OnError] public void OnError(StreamingContext context, ErrorContext errorContext) { - Log.ErrorFormat("Json serializer context path: {0}. Error message: {1}", errorContext.Path, errorContext.Error.Message); + Log.Error(errorContext.Error, "Json serializer context path: {0}", errorContext.Path); } } } diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpClientBase.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpClientBase.cs index 0898c4579..858d64c2b 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpClientBase.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpClientBase.cs @@ -44,9 +44,9 @@ protected void DiagnoseConnectionError(string host) Dns.GetHostEntry(host); } } - catch (Exception) + catch (Exception ex) { - Log.ErrorFormat("Unable to resolve host name \"{0}\"", host); + Log.Error(ex, "Unable to resolve host name \"{0}\"", host); } TestConnection(); @@ -67,7 +67,7 @@ protected void TestConnection() #else _lazyHttpClient.Value.GetAsync(testAddress).GetAwaiter().GetResult(); #endif - Log.InfoFormat("Connection test to \"{0}\" succeeded", testAddress); + Log.Info("Connection test to \"{0}\" succeeded", testAddress); } catch (Exception) { diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpResponse.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpResponse.cs index e17a14f75..7d90fe569 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpResponse.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/HttpResponse.cs @@ -60,8 +60,7 @@ public async Task GetContentAsync() } catch (Exception ex) { - Log.ErrorFormat("Request({0}): Unable to parse response body with exception: {1}", _requestGuid, - ex.Message); + Log.Error(ex, "Request({0}): Unable to parse response body.", _requestGuid); return Constants.EmptyResponseBody; } } diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRHttpClient.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRHttpClient.cs index a95596ee0..b6f4203ea 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRHttpClient.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRHttpClient.cs @@ -27,7 +27,7 @@ public NRHttpClient(IWebProxy proxy, IConfiguration configuration) : base(proxy) // set the default timeout to "infinite", but specify the configured collector timeout as the actual timeout for SendAsync() calls var httpHandler = new HttpClientHandler { Proxy = proxy }; - Log.InfoFormat("Current HttpClientHandler TLS Configuration (HttpClientHandler.SslProtocols): {0}", httpHandler.SslProtocols.ToString()); + Log.Info("Current HttpClientHandler TLS Configuration (HttpClientHandler.SslProtocols): {0}", httpHandler.SslProtocols.ToString()); var httpClient = new HttpClient(httpHandler, true) {Timeout = System.Threading.Timeout.InfiniteTimeSpan}; _httpClientWrapper = new HttpClientWrapper(httpClient, (int)configuration.CollectorTimeout); } diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/WebRequestClientResponse.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/WebRequestClientResponse.cs index 668ff3af6..18a7380c9 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/WebRequestClientResponse.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/WebRequestClientResponse.cs @@ -56,8 +56,7 @@ public Task GetContentAsync() } catch (Exception ex) { - Log.ErrorFormat("Request({0}): Unable to parse response body with exception: {1}", _requestGuid, - ex.Message); + Log.Error(ex, "Request({0}): Unable to parse response body.", _requestGuid); return Task.FromResult(Constants.EmptyResponseBody); } diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionHandler.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionHandler.cs index 1faa0e25c..934cf4315 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionHandler.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionHandler.cs @@ -28,7 +28,7 @@ namespace NewRelic.Agent.Core.DataTransport /// public class ConnectionHandler : ConfigurationBasedService, IConnectionHandler { - private static readonly Dictionary> ServerLogLevelMap = new Dictionary> + private static readonly Dictionary> ServerLogLevelMap = new Dictionary> { {"INFO", Log.Info}, {"WARN", Log.Warn}, @@ -108,7 +108,7 @@ public void Connect() catch (Exception e) { Disable(); - Log.Error($"Unable to connect to the New Relic service at {_connectionInfo} : {e}"); + Log.Error(e, $"Unable to connect to the New Relic service at {_connectionInfo}"); throw; } } @@ -133,12 +133,12 @@ private void LogSecurityPolicySettingsOnceAllSettingsResolved() return; } - Log.DebugFormat("Setting applied: {{\"record_sql\": \"{0}\"}}. Source: {1}", _configuration.TransactionTracerRecordSql, _configuration.TransactionTracerRecordSqlSource); - Log.DebugFormat("Setting applied: {{\"attributes_include\": {0}}}. Source: {1}", _configuration.CanUseAttributesIncludes, _configuration.CanUseAttributesIncludesSource); - Log.DebugFormat("Setting applied: {{\"allow_raw_exception_messages\": {0}}}. Source: {1}", !_configuration.StripExceptionMessages, _configuration.StripExceptionMessagesSource); - Log.DebugFormat("Setting applied: {{\"custom_events\": {0}}}. Source: {1}", _configuration.CustomEventsEnabled, _configuration.CustomEventsEnabledSource); - Log.DebugFormat("Setting applied: {{\"custom_parameters\": {0}}}. Source: {1}", _configuration.CaptureCustomParameters, _configuration.CaptureCustomParametersSource); - Log.DebugFormat("Setting applied: {{\"custom_instrumentation_editor\": {0}}}. Source: {1}", _configuration.CustomInstrumentationEditorEnabled, _configuration.CustomInstrumentationEditorEnabledSource); + Log.Debug("Setting applied: {{\"record_sql\": \"{0}\"}}. Source: {1}", _configuration.TransactionTracerRecordSql, _configuration.TransactionTracerRecordSqlSource); + Log.Debug("Setting applied: {{\"attributes_include\": {0}}}. Source: {1}", _configuration.CanUseAttributesIncludes, _configuration.CanUseAttributesIncludesSource); + Log.Debug("Setting applied: {{\"allow_raw_exception_messages\": {0}}}. Source: {1}", !_configuration.StripExceptionMessages, _configuration.StripExceptionMessagesSource); + Log.Debug("Setting applied: {{\"custom_events\": {0}}}. Source: {1}", _configuration.CustomEventsEnabled, _configuration.CustomEventsEnabledSource); + Log.Debug("Setting applied: {{\"custom_parameters\": {0}}}. Source: {1}", _configuration.CaptureCustomParameters, _configuration.CaptureCustomParametersSource); + Log.Debug("Setting applied: {{\"custom_instrumentation_editor\": {0}}}. Source: {1}", _configuration.CustomInstrumentationEditorEnabled, _configuration.CustomInstrumentationEditorEnabledSource); } public void Disconnect() @@ -237,7 +237,7 @@ private ServerConfiguration SendConnectRequest() if (responseMap == null) throw new Exception("Empty connect result payload"); - Log.InfoFormat("Agent {0} connected to {1}:{2}", GetIdentifier(), _connectionInfo.Host, _connectionInfo.Port); + Log.Info("Agent {0} connected to {1}:{2}", GetIdentifier(), _connectionInfo.Host, _connectionInfo.Port); var serverConfiguration = ServerConfiguration.FromDeserializedReturnValue(responseMap, _configuration.IgnoreServerSideConfiguration); LogConfigurationMessages(serverConfiguration); @@ -277,7 +277,7 @@ private void LogConfigurationMessages(ServerConfiguration serverConfiguration) continue; var logMethod = ServerLogLevelMap.GetValueOrDefault(message.Level) ?? Log.Info; - logMethod(message.Text); + logMethod(message.Text, null); } } @@ -288,7 +288,7 @@ private ConnectModel GetConnectParameters() if (!appNames.Any()) appNames.Add(identifier); - Log.InfoFormat("Your New Relic Application Name(s): {0}", string.Join(":", appNames.ToArray())); + Log.Info("Your New Relic Application Name(s): {0}", string.Join(":", appNames.ToArray())); var metadata = _environmentVariableHelper.GetEnvironmentVariablesWithPrefix("NEW_RELIC_METADATA_"); @@ -340,7 +340,7 @@ private void SendAgentSettings() } catch (Exception ex) { - Log.Error(ex); + Log.Error(ex, "SendAgentSettings() failed"); } } @@ -371,7 +371,7 @@ private void GenerateFasterEventHarvestConfigMetrics(EventHarvestConfig eventHar if (fasterEventHarvestEnabledTypes.Count > 0) { - Log.InfoFormat("The following events will be harvested every {1}ms: {0}", string.Join(", ", fasterEventHarvestEnabledTypes), eventHarvestConfig.ReportPeriodMs); + Log.Info("The following events will be harvested every {1}ms: {0}", string.Join(", ", fasterEventHarvestEnabledTypes), eventHarvestConfig.ReportPeriodMs); } } @@ -391,7 +391,7 @@ private void SendShutdownCommand() } catch (Exception ex) { - Log.Error($"Shutdown error: {ex}"); + Log.Error(ex, "Shutdown error"); } } @@ -428,24 +428,24 @@ private T SendDataOverWire(ICollectorWire wire, string method, params object[ } catch (DataTransport.HttpException ex) { - Log.DebugFormat("Request({0}): Received a {1} {2} response invoking method \"{3}\" with payload \"{4}\"", requestGuid, (int)ex.StatusCode, ex.StatusCode, method, serializedData); + Log.Debug(ex, "Request({0}): Received a {1} {2} response invoking method \"{3}\" with payload \"{4}\"", requestGuid, (int)ex.StatusCode, ex.StatusCode, method, serializedData); if (ex.StatusCode == HttpStatusCode.Gone) { - Log.InfoFormat("Request({0}): The server has requested that the agent disconnect. The agent is shutting down.", requestGuid); + Log.Info(ex, "Request({0}): The server has requested that the agent disconnect. The agent is shutting down.", requestGuid); } throw; } catch (Exception ex) { - Log.DebugFormat("Request({0}): An error occurred invoking method \"{1}\" with payload \"{2}\": {3}", requestGuid, method, serializedData, ex); + Log.Debug(ex, "Request({0}): An error occurred invoking method \"{1}\" with payload \"{2}\": {3}", requestGuid, method, serializedData, ex); throw; } } catch (Exception ex) { - Log.DebugFormat("Request({0}): Exception occurred serializing request data: {1}", requestGuid, ex); + Log.Debug(ex, "Request({0}): Exception occurred serializing request data: {1}", requestGuid, ex); throw; } } diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionManager.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionManager.cs index ec5a3c048..d0228cbd1 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionManager.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/ConnectionManager.cs @@ -174,14 +174,14 @@ public T SendDataRequest(string method, params object[] data) private static void ImmediateShutdown(string message) { - Log.InfoFormat("Shutting down: {0}", message); + Log.Info("Shutting down: {0}", message); EventBus.Publish(new KillAgentEvent()); } private void ScheduleRestart() { var _retryTime = ConnectionRetryBackoffSequence[_connectionAttempt]; - Log.InfoFormat("Will attempt to reconnect in {0} seconds", _retryTime.TotalSeconds); + Log.Info("Will attempt to reconnect in {0} seconds", _retryTime.TotalSeconds); _scheduler.ExecuteOnce(Connect, _retryTime); _connectionAttempt = Math.Min(_connectionAttempt + 1, ConnectionRetryBackoffSequence.Length - 1); diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/DataStreamingService.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/DataStreamingService.cs index 99a380d50..f01c1ab17 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/DataStreamingService.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/DataStreamingService.cs @@ -64,11 +64,11 @@ private async Task WaitForResponse() { if (rpcEx.Status.StatusCode == StatusCode.Cancelled && rpcEx.Status.Detail == NoStatusMessage) { - Log.LogMessage(logLevel, $"ResponseStreamWrapper: consumer {ConsumerID} - gRPC RpcException encountered marking the response stream as cancelled. This occurs when a stream has been inactive for period of time. A new stream will be created when needed. {rpcEx}"); + Log.LogMessage(logLevel, rpcEx, $"ResponseStreamWrapper: consumer {ConsumerID} - gRPC RpcException encountered marking the response stream as cancelled. This occurs when a stream has been inactive for period of time. A new stream will be created when needed."); } else { - Log.LogMessage(logLevel, $"ResponseStreamWrapper: consumer {ConsumerID} - gRPC RpcException encountered while handling gRPC server responses: {rpcEx}"); + Log.LogMessage(logLevel, rpcEx, $"ResponseStreamWrapper: consumer {ConsumerID} - gRPC RpcException encountered while handling gRPC server responses."); } } } @@ -79,7 +79,7 @@ private async Task WaitForResponse() var logLevel = LogLevel.Debug; if (Log.IsEnabledFor(logLevel)) { - Log.LogMessage(logLevel, $"ResponseStreamWrapper: consumer {ConsumerID} - Unknown exception encountered while handling gRPC server responses: {ex}"); + Log.LogMessage(logLevel, ex, $"ResponseStreamWrapper: consumer {ConsumerID} - Unknown exception encountered while handling gRPC server responses."); } } @@ -1018,26 +1018,17 @@ private TrySendStatus TrySend(int consumerId, IClientStreamWriter protected void LogMessage(LogLevel level, string message, Exception ex = null) { - if (Log.IsEnabledFor(level)) - { - Log.LogMessage(level, $"{GetType().Name}: {message} {(ex == null ? string.Empty : $" - Exception: {ex}")}"); - } + Log.LogMessage(level, ex, $"{GetType().Name}: {message}"); } protected void LogMessage(LogLevel level, int consumerId, string message, Exception ex = null) { - if (Log.IsEnabledFor(level)) - { - LogMessage(level, $"consumer {consumerId} - {message}", ex); - } + LogMessage(level, $"consumer {consumerId} - {message}", ex); } protected void LogMessage(LogLevel level, int consumerId, TRequest item, string message, Exception ex = null) { - if (Log.IsEnabledFor(level)) - { - LogMessage(level, consumerId, $"{_modelType} {item.DisplayName} - {message}", ex); - } + LogMessage(level, consumerId, $"{_modelType} {item.DisplayName} - {message}", ex); } private enum TrySendStatus diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/DataTransportService.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/DataTransportService.cs index 980d1d7bd..086d92419 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/DataTransportService.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/DataTransportService.cs @@ -125,7 +125,7 @@ public DataTransportResponseStatus Send(IEnumerable metrics) var endTime = _dateTimeStatic.UtcNow; if (beginTime >= endTime) { - Log.ErrorFormat("The last data send timestamp ({0}) is greater than or equal to the current timestamp ({1}). The metrics in this batch will be dropped.", _lastMetricSendTime, endTime); + Log.Error("The last data send timestamp ({0}) is greater than or equal to the current timestamp ({1}). The metrics in this batch will be dropped.", _lastMetricSendTime, endTime); _lastMetricSendTime = _dateTimeStatic.UtcNow; return DataTransportResponseStatus.Discard; } @@ -204,7 +204,7 @@ private static void RestartOrShutdownIfNecessary(HttpException ex) private static void Shutdown(string message) { - Log.InfoFormat("Shutting down: {0}", message); + Log.Info("Shutting down: {0}", message); EventBus.Publish(new KillAgentEvent()); } @@ -225,7 +225,7 @@ private void LogErrorResponse(Exception exception, string method, DateTime start { var endTime = DateTime.UtcNow; _agentHealthReporter.ReportSupportabilityCollectorErrorException(method, endTime - startTime, httpStatusCode); - Log.Error(exception); + Log.Error(exception, ""); } private DataTransportResponseStatus GetDataTransportResponseStatusByHttpStatusCode(HttpStatusCode httpStatusCode) diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/GrpcWrapper.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/GrpcWrapper.cs index 715797162..8d328c541 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/GrpcWrapper.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/GrpcWrapper.cs @@ -248,10 +248,7 @@ public void Shutdown() } catch (Exception ex) { - if (Log.IsFinestEnabled) - { - Log.Finest($"{this.GetType().Name}: Error encountered shutting down gRPC channel: {ex}"); - } + Log.Finest(ex, "{0}: Error encountered shutting down gRPC channel", this.GetType().Name); } _channel = null; @@ -265,11 +262,7 @@ public void TryCloseRequestStream(IClientStreamWriter requestStream) } catch (Exception ex) { - if (Log.IsFinestEnabled) - { - Log.Finest($"{this.GetType().Name}: Error encountered closing gRPC request channel: {ex}"); - - } + Log.Finest(ex, "{0}: Error encountered closing gRPC request channel.", this.GetType().Name); } } } diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/HttpCollectorWire.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/HttpCollectorWire.cs index 9a6dd6d08..34c62c5bb 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/HttpCollectorWire.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/HttpCollectorWire.cs @@ -77,17 +77,17 @@ public string SendData(string method, ConnectionInfo connectionInfo, string seri _agentHealthReporter.ReportSupportabilityDataUsage("Collector", method, request.Content.UncompressedByteCount, new UTF8Encoding().GetBytes(responseContent).Length); // Possibly combine these logs? makes parsing harder in tests... - Log.DebugFormat("Request({0}): Invoked \"{1}\" with : {2}", requestGuid, method, serializedData); - Log.DebugFormat("Request({0}): Invocation of \"{1}\" yielded response : {2}", requestGuid, method, responseContent); + Log.Debug("Request({0}): Invoked \"{1}\" with : {2}", requestGuid, method, serializedData); + Log.Debug("Request({0}): Invocation of \"{1}\" yielded response : {2}", requestGuid, method, responseContent); DataTransportAuditLogger.Log(DataTransportAuditLogger.AuditLogDirection.Received, DataTransportAuditLogger.AuditLogSource.Collector, responseContent); return responseContent; } - catch (PayloadSizeExceededException) + catch (PayloadSizeExceededException ex) { // Log that the payload is being dropped - Log.ErrorFormat("Request({0}): Dropped large payload: size: {1}, max_payload_size_bytes={2}", + Log.Error(ex, "Request({0}): Dropped large payload: size: {1}, max_payload_size_bytes={2}", request!.RequestGuid, request!.Content.PayloadBytes.Length, _configuration.CollectorMaxPayloadSizeInBytes); _agentHealthReporter.ReportSupportabilityPayloadsDroppeDueToMaxPayloadSizeLimit(method); @@ -100,11 +100,11 @@ private static void ThrowExceptionFromHttpResponseMessage(string serializedData, { if (statusCode == HttpStatusCode.UnsupportedMediaType) { - Log.ErrorFormat("Request({0}): Had invalid json: {1}. Please report to support@newrelic.com", requestGuid, serializedData); + Log.Error("Request({0}): Had invalid json: {1}. Please report to support@newrelic.com", requestGuid, serializedData); } // P17: Not supposed to read/use the exception message in the connect response body. We are still going to log it, carefully, since it is very useful for support. - Log.ErrorFormat("Request({0}): Received HTTP status code {1} with message {2}. Request content was: {3}", requestGuid, statusCode.ToString(), responseText, serializedData); + Log.Error("Request({0}): Received HTTP status code {1} with message {2}. Request content was: {3}", requestGuid, statusCode.ToString(), responseText, serializedData); throw new HttpException(statusCode, responseText); } diff --git a/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs b/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs index fadb253e5..f640b7ef6 100644 --- a/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs +++ b/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs @@ -94,7 +94,7 @@ public IEnumerable ResolveAll() } catch (Exception ex) { - Log.Error($"Error during ResolveAll of {typeof(T)}: {ex}"); + Log.Error(ex,"Error during ResolveAll of {0}", typeof(T)); throw; } } diff --git a/src/Agent/NewRelic/Agent/Core/DistributedTracing/DistributedTracePayloadHandler.cs b/src/Agent/NewRelic/Agent/Core/DistributedTracing/DistributedTracePayloadHandler.cs index b9e44515d..fd9c16586 100644 --- a/src/Agent/NewRelic/Agent/Core/DistributedTracing/DistributedTracePayloadHandler.cs +++ b/src/Agent/NewRelic/Agent/Core/DistributedTracing/DistributedTracePayloadHandler.cs @@ -93,7 +93,7 @@ public void InsertDistributedTraceHeaders(IInternalTransaction transaction, T catch (Exception ex) { _agentHealthReporter.ReportSupportabilityTraceContextCreateException(); - Log.Error(ex); + Log.Error(ex, "InsertDistributedTraceHeaders() failed"); } if (createOutboundTraceContextHeadersSuccess && _configurationService.Configuration.PayloadSuccessMetricsEnabled) @@ -103,7 +103,7 @@ public void InsertDistributedTraceHeaders(IInternalTransaction transaction, T } catch (Exception ex) { - Log.Error(ex); + Log.Error(ex, "InsertDistributedTraceHeaders() failed"); } } @@ -232,7 +232,7 @@ private IDistributedTracePayload TryGetOutboundDistributedTraceApiModelInternal( } catch (Exception ex) { - Log.Error($"Failed to get encoded distributed trace headers for outbound request: {ex}"); + Log.Error(ex, "Failed to get encoded distributed trace headers for outbound request."); _agentHealthReporter.ReportSupportabilityDistributedTraceCreatePayloadException(); return DistributedTraceApiModel.EmptyModel; } @@ -285,7 +285,7 @@ public ITracingState AcceptDistributedTraceHeaders(T carrier, Func valueGetter) } catch (Exception ex) { - Log.Warn($"Error getting value for environment variable {name}: {ex}"); + Log.Warn(ex, "Error getting value for environment variable {name}", name); } _environmentMap.Add(new[] { name, value }); @@ -156,7 +156,7 @@ private IProcess TryGetCurrentProcess() } catch (Exception ex) { - Log.Warn(ex); + Log.Warn(ex, "TryGetCurrentProcess() failed"); return null; } } @@ -170,7 +170,7 @@ private static FileVersionInfo TryGetFileVersionInfo() } catch (Exception ex) { - Log.Warn(ex); + Log.Warn(ex, "TryGetFileVersionInfo() failed"); return null; } } @@ -184,7 +184,7 @@ private static string TryGetAppDomainAppId() } catch (Exception ex) { - Log.Warn(ex); + Log.Warn(ex, "TryGetAppDomainAppId() failed"); return null; } } @@ -214,7 +214,7 @@ public static string TryGetAppPath(Func pathGetter) } catch (Exception ex) { - Log.Warn(ex); + Log.Warn(ex, "TryGetAppPath() failed"); return null; } } @@ -245,7 +245,7 @@ public Version TryGetIisVersion() } catch (Exception ex) { - Log.Warn(ex); + Log.Warn(ex, "TryGetIisVersion() failed"); return null; } } @@ -276,7 +276,7 @@ private static IEnumerable TryGetManagementObjects(string } catch (Exception ex) { - Log.Warn($"Could not retrieve processor count information: {ex}"); + Log.Warn(ex, "Could not retrieve processor count information"); return Enumerable.Empty(); } } diff --git a/src/Agent/NewRelic/Agent/Core/Instrumentation/InstrumentationWatcher.cs b/src/Agent/NewRelic/Agent/Core/Instrumentation/InstrumentationWatcher.cs index fdeb54c45..6825b17a4 100644 --- a/src/Agent/NewRelic/Agent/Core/Instrumentation/InstrumentationWatcher.cs +++ b/src/Agent/NewRelic/Agent/Core/Instrumentation/InstrumentationWatcher.cs @@ -30,7 +30,7 @@ public void Start() { if (AgentInstallConfiguration.HomeExtensionsDirectory == null) { - Log.WarnFormat("Live instrumentation updates due to instrumentation file changes will not be applied because HomeExtensionsDirectory is null."); + Log.Warn("Live instrumentation updates due to instrumentation file changes will not be applied because HomeExtensionsDirectory is null."); return; } @@ -60,18 +60,18 @@ private void RequestRejit() Log.Info("Starting instrumentation refresh from InstrumentationWatcher"); var result = _instrumentationService.InstrumentationRefresh(); _wrapperService.ClearCaches(); - Log.InfoFormat("Completed instrumentation refresh from InstrumentationWatcher: {0}", result); + Log.Info("Completed instrumentation refresh from InstrumentationWatcher: {0}", result); } private void OnChanged(object sender, FileSystemEventArgs e) { - Log.InfoFormat("Instrumentation change detected: {0} - {1}", e.ChangeType, e.FullPath); + Log.Info("Instrumentation change detected: {0} - {1}", e.ChangeType, e.FullPath); _action.Signal(); } private void OnRenamed(object sender, RenamedEventArgs e) { - Log.InfoFormat("Instrumentation change detected: {0} - {1} -> {2}", e.ChangeType, e.OldFullPath, e.FullPath); + Log.Info("Instrumentation change detected: {0} - {1} -> {2}", e.ChangeType, e.OldFullPath, e.FullPath); _action.Signal(); } diff --git a/src/Agent/NewRelic/Agent/Core/Instrumentation/LiveInstrumentationServerConfigurationListener.cs b/src/Agent/NewRelic/Agent/Core/Instrumentation/LiveInstrumentationServerConfigurationListener.cs index e84222244..20ad46cfe 100644 --- a/src/Agent/NewRelic/Agent/Core/Instrumentation/LiveInstrumentationServerConfigurationListener.cs +++ b/src/Agent/NewRelic/Agent/Core/Instrumentation/LiveInstrumentationServerConfigurationListener.cs @@ -39,7 +39,7 @@ private void OnServerConfigurationUpdated(ServerConfigurationUpdatedEvent server _instrumentationService.AddOrUpdateLiveInstrumentation(instrumentationSet.Name, instrumentationSet.Config); } - Log.InfoFormat("Applying live instrumentation from Custom Instrumentation Editor."); + Log.Info("Applying live instrumentation from Custom Instrumentation Editor."); // We want to apply custom instrumentation regardless of whether or not any was received on // this connect because we may have received instrumentation on a previous connect. @@ -47,12 +47,12 @@ private void OnServerConfigurationUpdated(ServerConfigurationUpdatedEvent server } catch (Exception ex) { - Log.Error(ex); + Log.Error(ex, "OnServerConfigurationUpdated() failed"); } } else { - Log.WarnFormat("Live instrumentation received from server Custom Instrumentation Editor not applied due to configuration."); + Log.Warn("Live instrumentation received from server Custom Instrumentation Editor not applied due to configuration."); var liveInstrumentationCleared = _instrumentationService.ClearLiveInstrumentation(); if (liveInstrumentationCleared) { diff --git a/src/Agent/NewRelic/Agent/Core/Labels/LabelsService.cs b/src/Agent/NewRelic/Agent/Core/Labels/LabelsService.cs index 07345ad0a..c90cb8cb6 100644 --- a/src/Agent/NewRelic/Agent/Core/Labels/LabelsService.cs +++ b/src/Agent/NewRelic/Agent/Core/Labels/LabelsService.cs @@ -51,7 +51,7 @@ private IEnumerable