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 { }
}
注意をこの関数で使用される構造体を使用します。
すべてのパッケージがASP.NETコアと互換性があるように更新されているわけではありません。 ElmahとASP.NETスタックの間で必要とされる統合のレベルを考えると、Elmahはまだ更新されていないと言えます。 – mason
[ELMAH on ASP.NET vNext?]の複製がありますか?(http://stackoverflow.com/questions/28907017/elmah-on-asp-net-vnext) – blowdart