
using System;
using Hotline.Logger.Models;
using Hotline.Share.Tools;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;

namespace HotPot.Mvc.Filters
{
    /// <summary>
    /// 异常拦截处理
    /// </summary>
    public class ErrorHandlingFilter : IExceptionFilter
    {
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly Serilog.ILogger _logger;

        private readonly IConfiguration _configuration;

        public ErrorHandlingFilter(ILogger logger, IConfiguration configuration)
        {
            _configuration = configuration;
            _logger = new LoggerConfiguration()
                .WriteTo.Logger(configure => configure
                .MinimumLevel.Debug()
                .WriteTo.RollingFile(
                    Path.Combine("logs", "err-log-{Date}.txt"),
                    retainedFileCountLimit: 7,
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
                ))
                .CreateLogger();

        }

        /// <summary>
        /// 异常拦截处理
        /// </summary>
        /// <param name="context">异常</param>
        public void OnException(ExceptionContext context)
        {
            if (_configuration.GetSection("AccLog").Get<bool>() == false) return;
            var exceptionModel = new ExceptionModel();
            try
            {

                context.HttpContext.Items.TryAdd("ErrorId", exceptionModel.Id);
                exceptionModel.Context = context.Exception.ToJson();
                exceptionModel.Method = context.HttpContext.Request.Path;
                exceptionModel.Message = context.Exception.Message;
                _logger.Error(exceptionModel.ToJson());
            }
            catch
            {
                // ignore
            }
        }
    }
}

