What are the ways to log all application errors in ASP.NET Core?

What are the ways to log all application errors in ASP.NET Core? For example, I would like to save all exceptions with the call stack to text files or something like that (automatic, not in the exception handler). If incorrect data was received in the controller, we would like to add information about the incorrect request to the log.

Ideally, I would like to have a tool that, for example, would send an SMS with a message that the database is not responding, the Internet fell off, users send the wrong data to a specific method of a specific controller, and so on.

Author: Kunoichi, 2017-11-22

2 answers

Add to Startup Middleware:

public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<ExceptionHandlerMiddleware>();
}

In Middleware , you define your own pre-execution and post-execution query processing, as well as error handling.

Implementation of ExceptionHandlerMiddleware (don't forget to register ILogger in the container):

public sealed class ExceptionHandlerMiddleware
{
    private readonly ILogger _logger;
    private readonly RequestDelegate _next;

    public ExceptionHandlerMiddleware(RequestDelegate next, ILogger logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception exp)
        {
            _logger.LogError(context, exp);
            await HandleExceptionAsync(context, exp.GetBaseException());
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exp)
    {
        var code = HttpStatusCode.InternalServerError; // 500 if unexpected
        var result = JsonConvert.SerializeObject(new { Code = code, Message = exp.Message, StackTrace = exp.StackTrace });

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;

        return context.Response.WriteAsync(result);
    }
}

Documentation with Microsoft

 8
Author: Chloroform, 2017-11-22 11:18:14

From the standard ones: Microsoft. Extensions.Logging.

In Startup.Configure:

loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddFile("C:\\log\\Лог.log");
            loggerFactory.AddDebug();

Then we get them via DI, including them in the ILogger constructor.

Next, in the right places, we write Log, processing. In some places (where it was not processed), it may issue an error itself in the file loggerFactory.AddDebug();

Perhaps if you dig around, you can write to the stream, and send the stream to the server, which would send you the messages you need.

P.S. The question above even without a separate server works and it seems to provide more data. Combine our answers and (I think) get what you want. Well, it is worth a little bit to smoke manuals on Microsoft.Extensions.Logging

 5
Author: Arantler, 2017-11-22 09:50:18