哈嘍我是不按期更新的平常,昨天羣裏小夥伴問到了記錄日誌,固然,之前我也挖過這個坑,後來一直沒有來得及填上,也想着 swagger 一直又有錯誤信息展現的功能,就遲遲沒有添加這個功能,不過昨天夜裏想了想,仍是須要增長上,旨在提升框架的高效性。不按期平常就直接上代碼了,我有一個小想法,就是但願你們有好的想法,能夠給我說,我會整理下,添加到框架裏,並在文章頭裏寫上html
投稿做者:這裏重點說明下,是參考羣裏小夥伴 Hello World! 的相關內容,並在他的基礎上更新,添加了注入和全局,你們能夠看看他的文章,支持開源,棒棒噠。git
廢話很少,直接來看,最終的效果是這樣的:github
一、感謝網友@夢亦曉的意見,目前是在 .net core api 中能夠捕獲,至於 mvc 的view視圖中的錯誤是否能夠,熱心觀衆能夠試試,感激涕零。數據庫
二、@易墨 提出了中間件的方法,在評論席裏,我感受也不錯,你們能夠看看,中間件更偏重非業務操做,只不過須要注意中間件的順序。json
三、感謝@blackheart 從官方教程中,提出指正,其實官方已經內置了接口ILogger,固然你能夠直接用 官方地址api
四、關於日誌記錄,還有 NLog日誌、Exceptionless分佈式日誌、官方的Logging等等均可以用,看我的喜愛吧。甚至能夠本身寫一個loghepler,可是必定要儘可能使用接口,不只能夠依賴注入,還能夠之後方便替換,不會到時候破壞底層框架。mvc
在 Blog.core 下的 Log 文件夾內,新建 ILoggerHelper.cs app
更新:這個接口其實也不必,你能夠直接參考官方提供的ILogger,而後注入就行,固然看我的習慣吧,若是必定要本身設計,可按照個人方法設計接口框架
namespace Blog.Core.Log { /// <summary> /// 日誌接口 /// </summary> public interface ILoggerHelper { /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Debug(object source, string message); /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="ps">ps</param> void Debug(object source, string message, params object[] ps); /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Debug(Type source, string message); /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Info(object source, object message); /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Info(Type source, object message); /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Warn(object source, object message); /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Warn(Type source, object message); /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Error(object source, object message); /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Error(Type source, object message); /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Fatal(object source, object message); /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> void Fatal(Type source, object message); /* Log a message object and exception */ /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Debug(object source, object message, Exception exception); /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Debug(Type source, object message, Exception exception); /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Info(object source, object message, Exception exception); /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Info(Type source, object message, Exception exception); /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Warn(object source, object message, Exception exception); /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Warn(Type source, object message, Exception exception); /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Error(object source, object message, Exception exception); /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Error(Type source, object message, Exception exception); /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Fatal(object source, object message, Exception exception); /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> void Fatal(Type source, object message, Exception exception); } }
namespace Blog.Core.Log { /// <summary> /// 日誌幫助實現類 /// </summary> public class LogHelper : ILoggerHelper { private readonly ConcurrentDictionary<Type, ILog> Loggers = new ConcurrentDictionary<Type, ILog>(); /// <summary> /// 獲取記錄器 /// </summary> /// <param name="source">soruce</param> /// <returns></returns> private ILog GetLogger(Type source) { if (Loggers.ContainsKey(source)) { return Loggers[source]; } else { ILog logger = LogManager.GetLogger(Startup.repository.Name, source); Loggers.TryAdd(source, logger); return logger; } } /* Log a message object */ /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Debug(object source, string message) { Debug(source.GetType(), message); } /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="ps">ps</param> public void Debug(object source, string message, params object[] ps) { Debug(source.GetType(), string.Format(message, ps)); } /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Debug(Type source, string message) { ILog logger = GetLogger(source); if (logger.IsDebugEnabled) { logger.Debug(message); } } /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Info(object source, object message) { Info(source.GetType(), message); } /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Info(Type source, object message) { ILog logger = GetLogger(source); if (logger.IsInfoEnabled) { logger.Info(message); } } /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Warn(object source, object message) { Warn(source.GetType(), message); } /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Warn(Type source, object message) { ILog logger = GetLogger(source); if (logger.IsWarnEnabled) { logger.Warn(message); } } /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Error(object source, object message) { Error(source.GetType(), message); } /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Error(Type source, object message) { ILog logger = GetLogger(source); if (logger.IsErrorEnabled) { logger.Error(message); } } /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Fatal(object source, object message) { Fatal(source.GetType(), message); } /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> public void Fatal(Type source, object message) { ILog logger = GetLogger(source); if (logger.IsFatalEnabled) { logger.Fatal(message); } } /* Log a message object and exception */ /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Debug(object source, object message, Exception exception) { Debug(source.GetType(), message, exception); } /// <summary> /// 調試信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Debug(Type source, object message, Exception exception) { GetLogger(source).Debug(message, exception); } /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Info(object source, object message, Exception exception) { Info(source.GetType(), message, exception); } /// <summary> /// 關鍵信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Info(Type source, object message, Exception exception) { GetLogger(source).Info(message, exception); } /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Warn(object source, object message, Exception exception) { Warn(source.GetType(), message, exception); } /// <summary> /// 警告信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Warn(Type source, object message, Exception exception) { GetLogger(source).Warn(message, exception); } /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Error(object source, object message, Exception exception) { Error(source.GetType(), message, exception); } /// <summary> /// 錯誤信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Error(Type source, object message, Exception exception) { GetLogger(source).Error(message, exception); } /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Fatal(object source, object message, Exception exception) { Fatal(source.GetType(), message, exception); } /// <summary> /// 失敗信息 /// </summary> /// <param name="source">source</param> /// <param name="message">message</param> /// <param name="exception">ex</param> public void Fatal(Type source, object message, Exception exception) { GetLogger(source).Fatal(message, exception); } } }
這個時候,你會發現還有一個錯誤 , 不過別慌,請往下看。less
這個具體深刻的概念,我還在研究中,有時間補充下,這裏大概瞭解用法以及概念,留一個坑
/// <summary> /// log4net 倉儲庫 /// </summary> public static ILoggerRepository repository { get; set; }
Repository能夠說成基於一個log4net配置節建立的log4net容器,它根據log4net配置節的指示建立其餘全部對象(Logger/Appender/Filter/Layout等等)並保有他們的實例,隨時爲你所用。
每一個Repository都有本身惟一的名字,如 root。
通常而言一個AppDomain(或者說一個進程)有一個Repository,該AppDomain下全部程序集Assembly均可以使用這個Repository。Repository須要實現ILoggerRepository,log4net中log4net.Repository.Hierarchy.Hierarchy就經過繼承LoggerRepositorySkeleton實現了ILoggerRepository,它也是log4net中惟一實現ILoggerRepository的類。
//log4net repository = LogManager.CreateRepository("");//須要獲取日誌的倉庫名,也就是你的固然項目名
//指定配置文件,若是這裏你遇到問題,應該是使用了InProcess模式,請查看Blog.Core.csproj,並刪之
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));//配置文件
在 Blog.core 根目錄下,添加 Log4net.config
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!-- 將日誌以回滾文件的形式寫到文件中 --> <!-- 按日期切分日誌文件,並將日期做爲日誌文件的名字 --> <appender name="RollingFileAppenderNameByDate" type="log4net.Appender.RollingFileAppender"> <!-- 日誌文件存放位置,能夠爲絕對路徑也能夠爲相對路徑 --> <file value="C:\Logs\" /> <!-- 將日誌信息追加到已有的日誌文件中--> <appendToFile value="true" /> <!-- 最小鎖定模式,以容許多個進程能夠寫入同一個文件 --> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <!-- 指定按日期切分日誌文件 --> <rollingStyle value="Date" /> <!-- 日誌文件的命名規則 --> <datePattern value=""UtilLogs_"yyyyMMdd".log"" /> <!-- 當將日期做爲日誌文件的名字時,必須將staticLogFileName的值設置爲false --> <staticLogFileName value="false" /> <!-- 日誌顯示模板 --> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="【異常時間】:%date %newline%message%newline--------------------------------------------------------------------%newline" /> </layout> </appender> <root> <!-- 控制級別,由低到高:ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF --> <!-- 好比定義級別爲INFO,則INFO級別向下的級別,好比DEBUG日誌將不會被記錄 --> <!-- 若是沒有定義LEVEL的值,則缺省爲DEBUG --> <level value="ALL" /> <!-- 按日期切分日誌文件,並將日期做爲日誌文件的名字 --> <appender-ref ref="RollingFileAppenderNameByDate" /> </root> </log4net> </configuration>
最終的結構是
這個時候,咱們已經把日誌添加好了,能夠在任何需用用的地方去使用了,你會問了,不是全局麼,總不能每一個方法都寫 try catch 吧,有想法,請往下看。
提醒下:
一、下邊的全局處理中,網友@夢亦曉:IExceptionFilter只能抓取Action執行過程當中出現的未處理的異常。若是想捕獲view中的異常須要在startup中的Configure中 實現app.UseExceptionHandler();
在 啓動文件的 ConfigureServices方法中,添加服務注入
//log日誌注入 services.AddSingleton<ILoggerHelper, LogHelper>();
namespace Blog.Core.Filter { /// <summary> /// 全局異常錯誤日誌 /// </summary> public class GlobalExceptionsFilter : IExceptionFilter { private readonly IHostingEnvironment _env; private readonly ILoggerHelper _loggerHelper; public GlobalExceptionsFilter(IHostingEnvironment 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)); } /// <summary> /// 自定義返回格式 /// </summary> /// <param name="throwMsg"></param> /// <param name="ex"></param> /// <returns></returns> 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 { /// <summary> /// 生產環境的消息 /// </summary> public string Message { get; set; } /// <summary> /// 開發環境的消息 /// </summary> public string DevelopmentMessage { get; set; } } }
//注入全局異常捕獲 services.AddMvc(o => { o.Filters.Add(typeof(GlobalExceptionsFilter)); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
結構是這樣的
我故意寫錯數據庫鏈接字符串,看看 swagger 如何報錯
看看日誌是如何記錄的
今天是不按期更新系列,也是羣裏小夥伴提出來的想法,我本身簡單搞搞,這裏但願你們能夠積極提意見喲,若是技術不錯,我會把你的我的主頁和Git放到文章中,也算是鼓勵你們的一個方式了。