.Net Core6.0 WebAPI项目框架搭建十:log4net完美实现全局异常日志记录

 完整框架项目源码地址:https://download.csdn.net/download/yigu4011/87788956?spm=1001.2014.3001.5503在

在Web.Core.API下新建 Log4Net 文件夹内,新建 ILoggerHelper.cs

/// 
    /// 日志接口
    /// 
    public interface ILoggerHelper
    {

        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        void Debug(object source, string message);
        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        /// ps
        void Debug(object source, string message, params object[] ps);
        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        void Debug(Type source, string message);
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        void Info(object source, object message);
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        void Info(Type source, object message);
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        void Warn(object source, object message);
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        void Warn(Type source, object message);
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        void Error(object source, object message);
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        void Error(Type source, object message);
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        void Fatal(object source, object message);
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        void Fatal(Type source, object message);

        /* Log a message object and exception */

        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        /// ex
        void Debug(object source, object message, Exception exception);
        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        /// ex
        void Debug(Type source, object message, Exception exception);
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        /// ex
        void Info(object source, object message, Exception exception);
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        /// ex
        void Info(Type source, object message, Exception exception);
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        /// ex
        void Warn(object source, object message, Exception exception);
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        /// ex
        void Warn(Type source, object message, Exception exception);
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        /// ex
        void Error(object source, object message, Exception exception);
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        /// ex
        void Error(Type source, object message, Exception exception);
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        /// ex
        void Fatal(object source, object message, Exception exception);
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        /// ex
        void Fatal(Type source, object message, Exception exception);
    }

nuget引入log4net

.Net Core6.0 WebAPI项目框架搭建十:log4net完美实现全局异常日志记录_第1张图片

在 Log4Net 文件夹下新建 LogHelper.cs

/// 
    /// 日志帮助实现类
    /// 
    public class LogHelper : ILoggerHelper
    {
        private readonly ConcurrentDictionary Loggers = new ConcurrentDictionary();

        private static ILog logger;

        public LogHelper()
        {
            if (logger == null)
            {
                var repository = LogManager.CreateRepository("NETCoreRepository");
                //log4net從log4net.config文件中讀取配置信息
                XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
                logger = LogManager.GetLogger(repository.Name, "Logger");
            }
        }

        /// 
        /// 获取记录器
        /// 
        /// soruce
        /// 
        private ILog GetLogger(Type source)
        {
            if (Loggers.ContainsKey(source))
            {
                return Loggers[source];
            }
            else
            {
                Loggers.TryAdd(source, logger);
                return logger;
            }
        }

        /* Log a message object */
        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        public void Debug(object source, string message)
        {
            Debug(source.GetType(), message);
        }
        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        /// ps
        public void Debug(object source, string message, params object[] ps)
        {
            Debug(source.GetType(), string.Format(message, ps));
        }
        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        public void Debug(Type source, string message)
        {
            logger = GetLogger(source);
            if (logger.IsDebugEnabled)
            {
                logger.Debug(message);
            }
        }
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        public void Info(object source, object message)
        {
            Info(source.GetType(), message);
        }
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        public void Info(Type source, object message)
        {
            logger = GetLogger(source);
            if (logger.IsInfoEnabled)
            {
                logger.Info(message);
            }
        }
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        public void Warn(object source, object message)
        {
            Warn(source.GetType(), message);
        }
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        public void Warn(Type source, object message)
        {
            logger = GetLogger(source);
            if (logger.IsWarnEnabled)
            {
                logger.Warn(message);
            }
        }
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        public void Error(object source, object message)
        {
            Error(source.GetType(), message);
        }
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        public void Error(Type source, object message)
        {
            logger = GetLogger(source);
            if (logger.IsErrorEnabled)
            {
                logger.Error(message);
            }
        }
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        public void Fatal(object source, object message)
        {
            Fatal(source.GetType(), message);
        }
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        public void Fatal(Type source, object message)
        {
            logger = GetLogger(source);
            if (logger.IsFatalEnabled)
            {
                logger.Fatal(message);
            }
        }
        /* Log a message object and exception */

        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        /// ex
        public void Debug(object source, object message, Exception exception)
        {
            Debug(source.GetType(), message, exception);
        }
        /// 
        /// 调试信息
        /// 
        /// source
        /// message
        /// ex
        public void Debug(Type source, object message, Exception exception)
        {
            GetLogger(source).Debug(message, exception);
        }
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        /// ex
        public void Info(object source, object message, Exception exception)
        {
            Info(source.GetType(), message, exception);
        }
        /// 
        /// 关键信息
        /// 
        /// source
        /// message
        /// ex
        public void Info(Type source, object message, Exception exception)
        {
            GetLogger(source).Info(message, exception);
        }
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        /// ex
        public void Warn(object source, object message, Exception exception)
        {
            Warn(source.GetType(), message, exception);
        }
        /// 
        /// 警告信息
        /// 
        /// source
        /// message
        /// ex
        public void Warn(Type source, object message, Exception exception)
        {
            GetLogger(source).Warn(message, exception);
        }
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        /// ex
        public void Error(object source, object message, Exception exception)
        {
            Error(source.GetType(), message, exception);
        }
        /// 
        /// 错误信息
        /// 
        /// source
        /// message
        /// ex
        public void Error(Type source, object message, Exception exception)
        {
            GetLogger(source).Error(message, exception);
        }
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        /// ex
        public void Fatal(object source, object message, Exception exception)
        {
            Fatal(source.GetType(), message, exception);
        }
        /// 
        /// 失败信息
        /// 
        /// source
        /// message
        /// ex
        public void Fatal(Type source, object message, Exception exception)
        {
            GetLogger(source).Fatal(message, exception);
        }
    }

配置 log4net.config 文件,在 Web.Core.API 根目录下,添加 Log4net.config



  
    

.Net Core6.0 WebAPI项目框架搭建十:log4net完美实现全局异常日志记录_第2张图片

 接下来是定义全局异常过滤器

在program.cs中注入日志服务

//log日志注入
builder.Services.AddSingleton();

Web.Core.API 新建Filter 文件夹,添加 GlobalExceptionFilter.cs

/// 
    /// 全局异常错误日志
    /// 
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILoggerHelper _loggerHelper;
        public GlobalExceptionsFilter(IWebHostEnvironment env, ILoggerHelper loggerHelper)
        {
            _env = env;
            _loggerHelper = loggerHelper;
        }
        public void OnException(ExceptionContext context)
        {
            var json = new JsonErrorResponse();
            json.Message = context.Exception.Message;//错误信息
            if (_env.IsDevelopment())
            {
                json.DevelopmentMessage = context.Exception.StackTrace;//堆栈信息
            }
            context.Result = new InternalServerErrorObjectResult(json);

            //采用log4net 进行错误日志记录
            _loggerHelper.Error(json.Message, WriteLog(json.Message, context.Exception));

        }

        /// 
        /// 自定义返回格式
        /// 
        /// 
        /// 
        /// 
        public string WriteLog(string throwMsg, Exception ex)
        {
            return string.Format("【自定义错误】:{0} \r\n【异常类型】:{1} \r\n【异常信息】:{2} \r\n【堆栈调用】:{3}", new object[] { throwMsg,
                ex.GetType().Name, ex.Message, ex.StackTrace });
        }

    }
    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
    //返回错误信息
    public class JsonErrorResponse
    {
        /// 
        /// 生产环境的消息
        /// 
        public string Message { get; set; }
        /// 
        /// 开发环境的消息
        /// 
        public string DevelopmentMessage { get; set; }
    }

在program.cs中注入全局异常捕获:

builder.Services.AddControllers(options =>
{
    options.SuppressAsyncSuffixInActionNames = false;
    options.Filters.Add(typeof(GlobalExceptionsFilter));
})

将appsettings.json中数据库字符串故意写错,测试异常记录.Net Core6.0 WebAPI项目框架搭建十:log4net完美实现全局异常日志记录_第3张图片

 错误日志会记录到异常文件夹下.Net Core6.0 WebAPI项目框架搭建十:log4net完美实现全局异常日志记录_第4张图片

你可能感兴趣的:(.netcore,.netcore)