Thay vì sử dụng ELMAH, không khó để thực hiện ghi nhật ký lỗi theo cách thủ công. Quá trình này sẽ bắt bất kỳ ngoại lệ nào xảy ra trong dự án và ghi nó vào một bảng cơ sở dữ liệu. Để làm điều này, thêm dòng sau vào phương pháp Configure trong Startup.cs
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);
}
});
});
}
Bao gồm này trong Startup.cs cũng như:
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 { }
}
Lưu ý rằng bạn sẽ phải tạo một bảng trong cơ sở dữ liệu của bạn với cấu trúc được sử dụng trong hàm này.
Không phải tất cả các gói đã được cập nhật để tương thích với ASP.NET Core. Với mức độ tích hợp cần thiết giữa Elmah và ASP.NET stack, tôi sẽ nói Elmah chưa được cập nhật. – mason
Có thể trùng lặp của [ELMAH trên ASP.NET vNext?] (Http://stackoverflow.com/questions/28907017/elmah-on-asp-net-vnext) – blowdart