- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为了记录在 ASP.NET Core Web 应用程序中花费在 SQL Server 查询上的时间,我一直在使用以下代码,并订阅了所有 DiagnosticListeners
在一些中间件中并使用 Observable
以下。
我不确定这是性能方面的最佳解决方案,我想知道是否有更好的方法通过直接从 EFCore 捕获详细的日志记录对象来使用 ASP.NET Core Logging API?理想情况下,我希望保留通过请求执行的所有查询的总持续时间,并在中间件可以使用的请求结束时获得总持续时间(以毫秒为单位)。
public class QueryTimingObserver : IObserver<DiagnosticListener>
{
private readonly List<IDisposable> subscriptions = new List<IDisposable>();
private readonly AsyncLocal<Stopwatch> stopwatch = new AsyncLocal<Stopwatch>();
private double milliseconds = 0;
void IObserver<DiagnosticListener>.OnNext(DiagnosticListener diagnosticListener)
{
if (diagnosticListener.Name == "SqlClientDiagnosticListener")
{
IDisposable subscription = diagnosticListener.SubscribeWithAdapter(this);
subscriptions.Add(subscription);
}
}
void IObserver<DiagnosticListener>.OnError(Exception error)
{
}
void IObserver<DiagnosticListener>.OnCompleted()
{
subscriptions.ForEach(x => x.Dispose());
subscriptions.Clear();
}
[DiagnosticName("System.Data.SqlClient.WriteCommandBefore")]
public void OnCommandBefore()
{
stopwatch.Value = Stopwatch.StartNew();
}
[DiagnosticName("System.Data.SqlClient.WriteCommandAfter")]
public void OnCommandAfter(DbCommand command)
{
stopwatch.Value.Stop();
milliseconds += stopwatch.Value.Elapsed.TotalMilliseconds;
}
public double Milliseconds
{
get
{
return milliseconds;
}
}
}
最佳答案
分享我在我的项目中所做的事情。
public class ApiRequest : IDisposable
{
[BsonId]
public string Id { get; set; }
// public string RequestId { get; set; }
public string ClientSessionId { get; set; }
public DateTime RequestStartTime { get; set; }
public string LogLevel { get; set; }
public string AccessProfile { get; set; }
public string ApiClientIpAddress { get; set; }
public GeoData ApiClientGeoData { get; set; }
public string OriginatingIpAddress { get; set; }
public GeoData OriginatingGeoData { get; set; }
public int StatusCode { get; set; }
public bool IsError { get; set; }
// public string ErrorMessage { get; set; }
public ConcurrentBag<string> Errors { get; set; }
public ConcurrentBag<string> Warnings { get; set; }
public long TotalExecutionTimeInMs { get; set; }
public long? ResponseSizeInBytes { get; set; }
public long TotalMySqlSpCalls { get; set; }
public long DbConnectionTimeInMs { get; set; }
public long DbCallTimeInMs { get; set; }
public long OverheadTimeInMs { get; set; }
public string UriHost { get; set; }
public string UriPath { get; set; }
public string SearchRequest { get; set; }
public string Referrer { get; set; }
public string UserAgent { get; set; }
public string SearchType { get; set; }
public ConcurrentQueue<RequestExecutionStatistics> ExecutionHistory { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
[BsonIgnore]
public Stopwatch Timer { get; set; }
public ApiRequest(Stopwatch stopwatch)
{
Id = Guid.NewGuid().ToString();
// RequestId = Guid.NewGuid().ToString();
Timer = stopwatch;
RequestStartTime = DateTime.Now.Subtract(Timer.Elapsed);
ExecutionHistory = new ConcurrentQueue<RequestExecutionStatistics>();
ExecutionHistory.Enqueue(new RequestExecutionStatistics
{
Description = "HTTP Request Start",
Status = RequestExecutionStatus.Started,
Index = 1,
StartTime = Timer.ElapsedMilliseconds,
ExecutionTimeInMs = 0
});
Errors = new ConcurrentBag<string>();
Warnings = new ConcurrentBag<string>();
}
public Task AddExecutionTimeStats(string description, RequestExecutionStatus status, long startTime, long executionTimeInMs)
{
int count = ExecutionHistory.Count;
return Task.Run(() =>
ExecutionHistory.Enqueue(new RequestExecutionStatistics
{
Description = description,
Status = status,
Index = count + 1,
StartTime = startTime,
ExecutionTimeInMs = executionTimeInMs
}));
}
public Task UpdateExecutionTimeStats(string description, long executionTimeInMs)
{
return Task.Run(() =>
{
var stats = ExecutionHistory.FirstOrDefault(e => e.Description.ToLower() == description.ToLower());
if (stats != null) stats.ExecutionTimeInMs = executionTimeInMs;
});
}
#region IDisposable implementation
private bool _disposed;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (_disposed) { return; }
if (disposing)
{
// Free managed objects here.
Timer.Stop(); // Probably doesn't matter, but anyways...
}
// Free any unmanaged objects here.
// Mark this object as disposed.
_disposed = true;
}
#endregion
}
[Route("api/[controller]")]
[Authorize(Policy = Constants.Policies.CanAccessSampleSearch)]
public class SampleSearchController : Controller
{
private readonly AppSettings _appSettings;
private readonly ISampleSearchService _sampleService;
public SampleSearchController(IOptions<AppSettings> appSettings, ISampleSearchService sampleSearchService)
{
_appSettings = appSettings.Value;
_sampleService = sampleSearchService;
}
[HttpPost]
public async Task<Response> PostAsync([FromBody]PersonRequest request)
{
var apiRequest = HttpContext.Items[Constants.CacheKeys.SampleApiRequest] as ApiRequest;
await apiRequest.AddExecutionTimeStats("Sample Search Controller", RequestExecutionStatus.Started,
apiRequest.Timer.ElapsedMilliseconds, 0);
var result = new Response();
if (!ModelState.IsValid)
{
apiRequest.StatusCode = (int)HttpStatusCode.BadRequest;
apiRequest.IsError = true;
foreach (var modelState in ModelState.Values)
{
foreach (var error in modelState.Errors)
{
apiRequest.Errors.Add(error.ErrorMessage);
}
}
}
else
{
result = await _sampleService.Search(request);
}
await apiRequest.AddExecutionTimeStats("Sample Search Controller", RequestExecutionStatus.Complted, 0,
apiRequest.Timer.ElapsedMilliseconds);
return result;
}
}
public class SampleSearchService : ISampleSearchService
{
#region Variables
private readonly AppSettings _appSettings;
private readonly IStateService _stateService;
private readonly IDistrictService _districtService;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion Variables
public SampleSearchService(IOptions<AppSettings> appSettings, IStateService stateService,
IDistrictService districtService, IHttpContextAccessor httpContextAccessor)
{
_appSettings = appSettings.Value;
_stateService = stateService;
_districtService = districtService;
_httpContextAccessor = httpContextAccessor;
}
public async Task<Response> Search(PersonRequest request)
{
var apiRequest =
_httpContextAccessor.HttpContext.Items[Constants.CacheKeys.SampleApiRequest] as ApiRequest;
await apiRequest.AddExecutionTimeStats("Sample Search Service", RequestExecutionStatus.Started,
apiRequest.Timer.ElapsedMilliseconds, 0);
var response = new Response();
using (var db = new ApplicationDb(_appSettings.ConnectionStrings.MyContext))
{
var dbConnectionStartTime = apiRequest.Timer.ElapsedMilliseconds;
await db.Connection.OpenAsync();
apiRequest.DbConnectionTimeInMs = apiRequest.Timer.ElapsedMilliseconds - dbConnectionStartTime;
await apiRequest.AddExecutionTimeStats("DB Connection", RequestExecutionStatus.Complted,
dbConnectionStartTime, apiRequest.DbConnectionTimeInMs);
using (var command = db.Command(_appSettings.StoredProcedures.GetSampleByCriteria,
_appSettings.Timeouts.GetSampleByCriteriaTimeout, CommandType.StoredProcedure, db.Connection))
{
command.Parameters.Add(new MySqlParameter
{
ParameterName = "p_Id",
DbType = DbType.Int64,
Value = request.Id
});
try
{
await apiRequest.AddExecutionTimeStats("Sample DB Call", RequestExecutionStatus.Started,
apiRequest.Timer.ElapsedMilliseconds, 0);
response = await ReadAllAsync(await command.ExecuteReaderAsync());
await apiRequest.AddExecutionTimeStats("Sample DB Call", RequestExecutionStatus.Complted, 0,
apiRequest.Timer.ElapsedMilliseconds);
}
catch (Exception e)
{
apiRequest.StatusCode = (int)HttpStatusCode.InternalServerError;
apiRequest.IsError = true;
apiRequest.Errors.Add(e.Message);
}
}
}
apiRequest.SearchRequest = JsonConvert.SerializeObject(request);
await apiRequest.AddExecutionTimeStats("Sample Search Service", RequestExecutionStatus.Complted, 0,
apiRequest.Timer.ElapsedMilliseconds);
return response;
}
private async Task<Response> ReadAllAsync(DbDataReader reader)
{
var SampleResponse = new Response();
using (reader)
{
while (await reader.ReadAsync())
{
SampleResponse.AvailableCount = Convert.ToInt32(await reader.GetFieldValueAsync<long>(0));
if (reader.NextResult())
{
while (await reader.ReadAsync())
{
var SampleRecord = new Record()
{
District = !await reader.IsDBNullAsync(1) ? await reader.GetFieldValueAsync<string>(6) : null,
State = !await reader.IsDBNullAsync(2) ? await reader.GetFieldValueAsync<string>(7) : null
};
SampleResponse.Records.Add(SampleRecord);
}
}
}
}
return SampleResponse;
}
}
public class ApiRequestsMiddleware
{
private readonly RequestDelegate _next;
private readonly IApiRequestService _apiRequestService;
public ApiRequestsMiddleware(RequestDelegate next, IApiRequestService apiRequestService)
{
_next = next;
_apiRequestService = apiRequestService;
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
var accessProfileName = context.User.Claims != null && context.User.Claims.Any()
? context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value
: null;
try
{
var request = new ApiRequest(stopwatch)
{
AccessProfile = accessProfileName,
ClientSessionId = ContextHelper.GetHeadersValue(context, Constants.Headers.ClientSessionId),
ApiClientIpAddress = context.Connection.RemoteIpAddress.ToString()
};
var originatingIpAddress = ContextHelper.GetHeadersValue(context, Constants.Headers.OriginatingIpAddress);
request.OriginatingIpAddress = !string.IsNullOrWhiteSpace(originatingIpAddress)
? originatingIpAddress
: context.Connection.RemoteIpAddress.ToString();
request.UriHost = context.Request.Host.ToString();
request.UriPath = context.Request.Path;
var referrer = ContextHelper.GetHeadersValue(context, Constants.Headers.Referrer);
request.Referrer = !string.IsNullOrWhiteSpace(referrer) ? referrer : null;
var userAgent = ContextHelper.GetHeadersValue(context, Constants.Headers.UserAgent);
request.UserAgent = !string.IsNullOrWhiteSpace(userAgent) ? userAgent : null;
request.SearchType = SearchHelper.GetSearchType(request.UriPath).ToString();
context.Items.Add(Constants.CacheKeys.SampleApiRequest, request);
await _next(context);
stopwatch.Stop();
request.StatusCode = context.Response.StatusCode;
request.LogLevel = LogLevel.Information.ToString();
request.TotalExecutionTimeInMs = stopwatch.ElapsedMilliseconds;
if (request.IsError)
request.LogLevel = LogLevel.Error.ToString();
if (_apiRequestService != null)
Task.Run(() => _apiRequestService.Create(request));
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
public static class ApiRequestsMiddlewareExtensions
{
public static IApplicationBuilder UseApiRequests(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ApiRequestsMiddleware>();
}
}
public class ApiRequestService : IApiRequestService
{
private readonly IMongoDbContext _context;
private readonly IIpLocatorService _ipLocatorService;
public ApiRequestService(IMongoDbContext context, IIpLocatorService ipLocatorService)
{
_context = context;
_ipLocatorService = ipLocatorService;
}
public async Task<IEnumerable<ApiRequest>> Get()
{
return await _context.ApiRequests.Find(_ => true).ToListAsync();
}
public async Task<ApiRequest> Get(string id)
{
var filter = Builders<ApiRequest>.Filter.Eq("Id", id);
try
{
return await _context.ApiRequests.Find(filter).FirstOrDefaultAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public async Task Create(ApiRequest request)
{
try
{
request.OriginatingGeoData = null; // await _ipLocatorService.Get(request.OriginatingIpAddress);
var finalHistory = new ConcurrentQueue<RequestExecutionStatistics>();
foreach (var history in request.ExecutionHistory.ToList())
{
if (history.Status == RequestExecutionStatus.Started)
{
var findPartner = request.ExecutionHistory.FirstOrDefault(e =>
e.Description.ToLower() == history.Description.ToLower() &&
e.Status == RequestExecutionStatus.Complted);
if (findPartner != null)
{
var temp = history.Clone();
temp.Status = RequestExecutionStatus.Complted;
temp.ExecutionTimeInMs = findPartner.ExecutionTimeInMs - history.StartTime;
finalHistory.Enqueue(temp);
}
else
finalHistory.Enqueue(history);
}
else if (history.Status == RequestExecutionStatus.Complted)
{
var findPartner = request.ExecutionHistory.FirstOrDefault(e =>
e.Description.ToLower() == history.Description.ToLower() &&
e.Status == RequestExecutionStatus.Started);
if (findPartner == null)
finalHistory.Enqueue(history);
}
}
request.ExecutionHistory = finalHistory;
request.CreatedDate = DateTime.Now;
request.CreatedBy = Environment.MachineName;
await _context.ApiRequests.InsertOneAsync(request);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Other code
app.UseApiRequests();
app.UseResponseWrapper();
app.UseMvc();
}
{
"_id" : "75a90cc9-5d80-4eb8-aae1-70a3611fe8ff",
"RequestId" : "98be1d85-9941-4a17-a73a-5f0a38bd7703",
"ClientSessionId" : null,
"RequestStartTime" : ISODate("2019-09-11T15:22:05.802-07:00"),
"LogLevel" : "Information",
"AccessProfile" : "Sample",
"ApiClientIpAddress" : "0.0.0.0",
"ApiClientGeoData" : null,
"OriginatingIpAddress" : "0.0.0.0",
"OriginatingGeoData" : null,
"StatusCode" : 200,
"IsError" : false,
"Errors" : [],
"Warnings" : [],
"TotalExecutionTimeInMs" : NumberLong(115),
"ResponseSizeInBytes" : NumberLong(0),
"TotalMySqlSpCalss" : NumberLong(0),
"DbConnectionTimeInMs" : NumberLong(3),
"DbCallTimeInMs" : NumberLong(0),
"OverheadTimeInMs" : NumberLong(0),
"UriHost" : "www.sampleapi.com",
"UriPath" : "/api/Samples",
"SearchRequest" : null,
"Referrer" : null,
"UserAgent" : null,
"SearchType" : "Sample",
"ExecutionHistory" : [
{
"Description" : "HTTP Request Start",
"Index" : 1,
"StartTime" : NumberLong(0),
"ExecutionTimeInMs" : NumberLong(0)
},
{
"Description" : "Sample Search Controller",
"Index" : 2,
"StartTime" : NumberLong(0),
"ExecutionTimeInMs" : NumberLong(115)
},
{
"Description" : "Sample Search Service",
"Index" : 3,
"StartTime" : NumberLong(0),
"ExecutionTimeInMs" : NumberLong(115)
},
{
"Description" : "DB Connection",
"Index" : 4,
"StartTime" : NumberLong(0),
"ExecutionTimeInMs" : NumberLong(3)
},
{
"Description" : "Sample DB Call",
"Index" : 5,
"StartTime" : NumberLong(3),
"ExecutionTimeInMs" : NumberLong(112)
}
],
"CreatedDate" : ISODate("2019-09-11T15:22:05.918-07:00"),
"CreatedBy" : "Server"}
关于entity-framework - 使用 EF Core 记录查询持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767700/
我有这些实体(这只是我为这篇文章创建的抽象): 语言 区 说明 这些是它们之间的引用: 区 * - 1 语言 说明 * - 1 语言 区 1 - 1 说明 如果我这样取: var myFetch =
经过大量谷歌搜索后,除了降级 hibernate 版本之外,我没有找到问题的答案。但我在 2003 年类似的帖子中遇到了这种情况。 问题是什么: //in the first session I d
我听说过 linq to entities 。 Entity Framework 是利用linq to entities吗? 最佳答案 LINQ to Entities 是 Entity Framew
我是 Entity Framework 和 ASP.Net MVC 的新手,主要从教程中学习,对任何一个都没有深入了解。 (我确实有 .Net 2.0、ADO.Net 和 WebForms 方面的经验
如果我编写 LINQ to Entities 查询,该查询是否会转换为提供程序理解的 native 查询(即 SqlClient)? 或者 它是否会转换为实体 SQL,然后 Entity Framew
这个问题已经有答案了: EF: Include with where clause [duplicate] (5 个回答) 已关闭 2 年前。 看来我无法从数据库中获取父级及其子级的子集。 例如...
我开始在一家新公司工作,我必须在一个旧项目上使用 C++ 工作。所以,我忘记了一些 C++ 本身的代码结构。在一个函数中,我在一个函数中有双冒号::,但我不知道如何理解它。 例如,我知道如果我有 EN
我写了一个方法来允许为 orderby 子句传递一个表达式,但我遇到了这个问题。 Unable to cast the type 'System.DateTime' to type 'System.I
简单的问题:LINQ to Entities 和 Entity Framework 有什么区别?到目前为止,我认为这两个名称是用来描述同一个查询的,但我开始觉得事实并非如此。 最佳答案 Entity
我想使用 Entity Framework 。但是,我还要求允许我的用户在我们的系统中定义自定义字段。我想仍然使用 Entity Framework ,而不是使用具有哈希表属性的分部类。 下面是我想到
我正在阅读这个 E.F. 团队博客的这个系列 http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-featu
我正在使用 EF6 开发插件应用程序,代码优先。 我有一个名为 User 的实体的主要上下文。 : public class MainDataContext : DbContext { pub
当我得到最后的 .edmx 时,我遇到了问题。 我收到一条消息说 错误 11007:未映射实体类型“pl_Micro”。 查看设计器 View ,我确实看到该表确实存在。 我怎样才能克服这个消息? 最
我已阅读与使用 Entity Framework 时在 Linq to Entities (.NET 3.5) 中实现等效的 LEFT OUTER JOIN 相关的所有帖子,但尚未找到解决以下问题的方
使用 WCF RIA 服务和 Entity Framework 4. 我有 3 个 DTO:学校、州、区。 州 DTO 有一个地区属性(property),其构成。学校 DTO 有一个国家属性(pro
我有一个 Employee 实体,它继承自一个继承自 Resource 实体(Employee -> Person -> Resource)的 Person 实体。是否可以通过编程方式获取 Emplo
我有一个使用 JPA 的 java 应用程序。 假设我有一个名为 Product 的实体与 name和 price属性(所有实体都有一个 id 属性)。 自然我可以得到一个List相当容易(来自查询或
我有一个 Entity Framework 类,其中有两个指向另一个对象的引用 public class Review { [Key] public int Id {get;s
我是 Symfony 2 的新手,我想知道一些事情: 假设我的项目中有 2 个 bundle 。我想在两个包中使用从我的数据库生成的实体。 我应该在哪里生成实体? (对我来说,最好的方法是在 bund
我想在具有方法和属性的部分类中扩展 EF 实体。我经常这样做。 但是现在我需要将来自该实体的数据与来自其他实体的数据结合起来。因此,我需要能够访问实体 objectcontext(如果附加)来进行这些
我是一名优秀的程序员,十分优秀!