using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Serilog;
namespace ExceptionSample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .WriteTo.Console()
                .WriteTo.File("Logs\\APPNAME.txt", rollingInterval: RollingInterval.Day )
                .CreateLogger();
            try
            {
                CreateWebHostBuilder(args).Build().Run();
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using System;   
namespace ExceptionSample.Controllers
{
    public class ErrorController : Controller
    {
        [Route("api/error")]
        public IActionResult LogError()
        {
            //Get hold of the exceptiom that occured
            var exFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
            if(exFeature != null)
            {
                //Get the path where the eroor occured
                string path = exFeature.Path;
                //Get the Exception
                Exception ex = exFeature.Error;
                //Log in a flat fire or other storage
                Log.Error(ex, path);
                var error = new { ErrorMessage = ex.Message, ErrorPath = path };
                return BadRequest(error);
            }
            return BadRequest();
        }
    }
}
Yorumlar
Yorum Gönder