[英]How does one use Elmah in ASP.NET 5/vNext/Core?
我對如何在ASP.NET 5 / MVC 6項目中使用Elmah感到有點困惑。 我從nuget獲得了包,它在project.json中添加了"Elmah.Mvc": "2.1.2"
到依賴項。
我不知道從哪里開始 - 在當天,nuget會在web.config中添加條目,現在已經不見了。 我似乎無法在他們的github或其他地方找到任何例子。
我錯過了一些簡單的事嗎?
而不是使用ELMAH,手動實現錯誤記錄並不困難。 此過程將捕獲項目中發生的任何異常並將其記錄到數據庫表中。 為此,請將以下內容添加到Startup.cs中的Configure方法
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var error = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>();
if (error != null)
{
LogException(error.Error, context);
await context.Response.WriteAsync("<h2>An error has occured in the website.</h2>").ConfigureAwait(false);
}
});
});
}
也包括在Startup.cs中:
private void LogException(Exception error, HttpContext context)
{
try
{
var connectionStr = Configuration["ConnectionString"];
using (var connection = new System.Data.SqlClient.SqlConnection(connectionStr))
{
var command = connection.CreateCommand();
command.CommandText = @"INSERT INTO ErrorLog (Application, Host, Type, Source, Path, Method, Message, StackTrace, [User], WhenOccured)
VALUES (@Application, @Host, @Type, @Source, @Path, @Method, @Message, @StackTrace, @User, @WhenOccured)";
connection.Open();
if (error.InnerException != null)
error = error.InnerException;
command.Parameters.AddWithValue("@Application", this.GetType().Namespace);
command.Parameters.AddWithValue("@Host", Environment.MachineName);
command.Parameters.AddWithValue("@Type", error.GetType().FullName);
command.Parameters.AddWithValue("@Source", error.Source);
command.Parameters.AddWithValue("@Path", context.Request.Path.Value);
command.Parameters.AddWithValue("@Method", context.Request.Method);
command.Parameters.AddWithValue("@Message", error.Message);
command.Parameters.AddWithValue("@StackTrace", error.StackTrace);
var user = context.User.Identity?.Name;
if (user == null)
command.Parameters.AddWithValue("@User", DBNull.Value);
else
command.Parameters.AddWithValue("@User", user);
command.Parameters.AddWithValue("@WhenOccured", DateTime.Now);
command.ExecuteNonQuery();
}
}
catch { }
}
請注意,您必須使用此函數中使用的結構在數據庫中創建表。
ELMAH尚未更新以支持ASP.NET Core。 Atif Aziz做了一些工作,構建了一個名為Bootstrapper的web.config免費配置模塊。 Bootstrapper不支持ASP.NET Core(據我所知)。 但我很確定支持新版本的工作將在我們接近RTM時立即開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.