我有一个POST控制器方法使用异步等待在很多服务和控制器级别我需要发送一些新的遗物参数。 New Relic在参数从非请求启动的线程发送时发出警告日志。如何在同一个线程上调用请求开始
NewRelic WARN: Agent API Error: An error occurred invoking API method "AddCustomParameter" - "System.InvalidOperationException: The API method called is only valid from within a transaction. This error can occur if you call the API method from a thread other than the one the transaction started on. at NewRelic.Agent.Core.Api.AsyncAgentApi.GetCurrentTransactionBuilder()
at NewRelic.Agent.Core.Api.AsyncAgentApi.AddCustomParameter(String key, String value)"
如何在我的控制器方法中调用将参数值发送到New Relic的代码?
例如,下面的代码在控制器中。
var threadid = Thread.CurrentThread.ManagedThreadId;
Log.Debug($"Before async method : {ThreadIdMessage(threadid)}");
var reportObject = await ReportService.GetReportAsync(requestModel).ConfigureAwait(true);
if (reportObject.PolicyModels != null)
{
threadid = Thread.CurrentThread.ManagedThreadId;
Log.Debug($"Before sending New Relic values: {ThreadIdMessage(threadid)}");
AddPoliciesCountInNewRelic(reportObject.PolicyModels.Count);
AddTotalTransactionsCountInNewRelic(
reportObject.PolicyModels.SelectMany(p => p.PolicyTransactionModels).Count());
threadid = Thread.CurrentThread.ManagedThreadId;
Log.Debug($"After sending New Relic values: {ThreadIdMessage(threadid)}");
}
将打印
DEBUG - Before async method : Current Thread Id: 5
DEBUG - Before sending New Relic values: Current Thread Id: 9
NewRelic.AddCustomParameter(CVPoliciesCount,2)
NewRelic.AddCustomParameter(CVTotalTransactionsCount,8)
DEBUG - After sending New Relic values: Current Thread Id: 9
每New Relic的警告日志,我应该在调用线程ID的AddCustomParameter
方法5.
AddPoliciesCountInNewRelic
和AddTotalTransactionsCountInNewRelic
调用ApiControllerBase.AddNewRelicParameter(string, string)
基类的保护方法。
private void AddPoliciesCountInNewRelic(int policiesCount)
{
AddNewRelicParameter("CVPoliciesCount", policiesCount.ToString());
}
private void AddTotalTransactionsCountInNewRelic(int transactionsCount)
{
AddNewRelicParameter("CVTotalTransactionsCount", transactionsCount.ToString());
}
protected void AddNewRelicParameter(string key, string value)
{
if (!string.IsNullOrWhiteSpace(key) &&
!string.IsNullOrWhiteSpace(value))
{
try
{
NewRelic.Api.Agent.NewRelic.AddCustomParameter(key, value);
}
catch (Exception ex)
{
Log.Error($"ERROR! : New Relic Parameter Exception {ex}");
}
}
}
https://discuss.newrelic.com/t/are-custom-params-supported-in-async-mode/37601 <他们声称现在支持异步控制器。 – Evk
asp.net中的'ConfigureAwait(true)'并不能保证你回到开始调用的那个线程,就像你在Winforms或WPF中使用UI线程时一样。 –
实际上'ConfigureAwait(true)'是默认行为。它和'等待ReportService.GetReportAsync(requestModel);'完全一样。 –