原文作者:老張的哲學(xué)
一、添加日志接口類
在 Blog.core 下的 Log 文件夾內(nèi)哮内,新建 ILoggerHelper.cs
更新:這個(gè)接口其實(shí)也沒必要奄容,你可以直接參考官方提供的ILogger康聂,然后注入就行踊东,當(dāng)然看個(gè)人習(xí)慣吧北滥,如果一定要自己設(shè)計(jì),可按照我的方法設(shè)計(jì)接口
using System;
namespace Blog.Core.API.Log
{
/// <summary>
/// 日志接口
/// </summary>
public interface ILoggerHelper
{
/// <summary>
/// 調(diào)試信息
/// </summary>
/// <param name="source"></param>
/// <param name="message"></param>
void Debug(object source, string message);
/// <summary>
/// 調(diào)試信息
/// </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>
/// 調(diào)試信息
/// </summary>
/// <param name="source">source</param>
/// <param name="message">message</param>
void Debug(Type source, string message);
/// <summary>
/// 關(guān)鍵信息
/// </summary>
/// <param name="source">source</param>
/// <param name="message">message</param>
void Info(object source, object message);
/// <summary>
/// 關(guān)鍵信息
/// </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>
/// 錯(cuò)誤信息
/// </summary>
/// <param name="source">source</param>
/// <param name="message">message</param>
void Error(object source, object message);
/// <summary>
/// 錯(cuò)誤信息
/// </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>
/// 調(diào)試信息
/// </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>
/// 調(diào)試信息
/// </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>
/// 關(guān)鍵信息
/// </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>
/// 關(guān)鍵信息
/// </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>
/// 錯(cuò)誤信息
/// </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>
/// 錯(cuò)誤信息
/// </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);
}
}
二闸翅、實(shí)現(xiàn)日志幫助類再芋,引入 log4net
1、在 Log 文件夾下新建 LogHelper.cs
using log4net;
using System;
using System.Collections.Concurrent;
namespace Blog.Core.API.Log
{
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>
/// 調(diào)試信息
/// </summary>
/// <param name="source">source</param>
/// <param name="message">message</param>
public void Debug(object source, string message)
{
Debug(source.GetType(), message);
}
/// <summary>
/// 調(diào)試信息
/// </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>
/// 調(diào)試信息
/// </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>
/// 關(guān)鍵信息
/// </summary>
/// <param name="source">source</param>
/// <param name="message">message</param>
public void Info(object source, object message)
{
Info(source.GetType(), message);
}
/// <summary>
/// 關(guān)鍵信息
/// </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>
/// 錯(cuò)誤信息
/// </summary>
/// <param name="source">source</param>
/// <param name="message">message</param>
public void Error(object source, object message)
{
Error(source.GetType(), message);
}
/// <summary>
/// 錯(cuò)誤信息
/// </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>
/// 調(diào)試信息
/// </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>
/// 調(diào)試信息
/// </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>
/// 關(guān)鍵信息
/// </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>
/// 關(guān)鍵信息
/// </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>
/// 錯(cuò)誤信息
/// </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>
/// 錯(cuò)誤信息
/// </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);
}
}
}
2坚冀、引用 nuget 包
這個(gè)時(shí)候济赎,你會(huì)發(fā)現(xiàn)還有一個(gè)錯(cuò)誤 , 不過別慌,請(qǐng)往下看司训。
1构捡、在啟動(dòng)文件中添加 Loger 日志倉庫
這個(gè)具體深入的概念,我還在研究中壳猜,有時(shí)間補(bǔ)充下勾徽,這里大概了解用法以及概念,留一個(gè)坑
/// <summary>
/// log4net 倉儲(chǔ)庫
/// </summary>
public static ILoggerRepository repository { get; set; }
Repository可以說成基于一個(gè)log4net配置節(jié)創(chuàng)建的log4net容器蓖谢,它根據(jù)log4net配置節(jié)的指示創(chuàng)建其他所有對(duì)象(Logger/Appender/Filter/Layout等等)并保有他們的實(shí)例捂蕴,隨時(shí)為你所用譬涡。
每個(gè)Repository都有自己唯一的名字闪幽,如 root。
一般而言一個(gè)AppDomain(或者說一個(gè)進(jìn)程)有一個(gè)Repository涡匀,該AppDomain下所有程序集Assembly都可以使用這個(gè)Repository盯腌。Repository需要實(shí)現(xiàn)ILoggerRepository,log4net中l(wèi)og4net.Repository.Hierarchy.Hierarchy就通過繼承LoggerRepositorySkeleton實(shí)現(xiàn)了ILoggerRepository陨瘩,它也是log4net中唯一實(shí)現(xiàn)ILoggerRepository的類腕够。
2、在 Startup.cs 啟動(dòng)文件的 構(gòu)造函數(shù)中舌劳,添加日志啟動(dòng)
//log4net
repository = LogManager.CreateRepository("");//需要獲取日志的倉庫名帚湘,也就是你的當(dāng)然項(xiàng)目名
//指定配置文件,如果這里你遇到問題甚淡,應(yīng)該是使用了InProcess模式大诸,請(qǐng)查看Blog.Core.csproj,并刪之
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));//配置文件
3、配置 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">
<!-- 日志文件存放位置,可以為絕對(duì)路徑也可以為相對(duì)路徑 -->
<file value="C:\Logs\" />
<!-- 將日志信息追加到已有的日志文件中-->
<appendToFile value="true" />
<!-- 最小鎖定模式撵割,以允許多個(gè)進(jìn)程可以寫入同一個(gè)文件 -->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!-- 指定按日期切分日志文件 -->
<rollingStyle value="Date" />
<!-- 日志文件的命名規(guī)則 -->
<datePattern value=""UtilLogs_"yyyyMMdd".log"" />
<!-- 當(dāng)將日期作為日志文件的名字時(shí)贿堰,必須將staticLogFileName的值設(shè)置為false -->
<staticLogFileName value="false" />
<!-- 日志顯示模板 -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="【異常時(shí)間】:%date %newline%message%newline--------------------------------------------------------------------%newline" />
</layout>
</appender>
<root>
<!-- 控制級(jí)別,由低到高:ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF -->
<!-- 比如定義級(jí)別為INFO啡彬,則INFO級(jí)別向下的級(jí)別羹与,比如DEBUG日志將不會(huì)被記錄 -->
<!-- 如果沒有定義LEVEL的值,則缺省為DEBUG -->
<level value="ALL" />
<!-- 按日期切分日志文件庶灿,并將日期作為日志文件的名字 -->
<appender-ref ref="RollingFileAppenderNameByDate" />
</root>
</log4net>
</configuration>
最終的結(jié)構(gòu)是
這個(gè)時(shí)候纵搁,我們已經(jīng)把日志添加好了,可以在任何需用用的地方去使用了跳仿,你會(huì)問了诡渴,不是全局么,總不能每個(gè)方法都寫 try catch 吧,有想法妄辩,請(qǐng)往下看惑灵。
四、定義全局異常過濾器
1眼耀、日志接口進(jìn)行注入
在 啟動(dòng)文件的 ConfigureServices方法中英支,添加服務(wù)注入
//log日志注入
services.AddSingleton<ILoggerHelper, LogHelper>();
2、Blog.core 新建Filter 文件夾哮伟,添加 GlobalExceptionFilter.cs
using Blog.Core.API.Log;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
namespace Blog.Core.API.Filter
{
/// <summary>
/// 全局異常錯(cuò)誤日志
/// </summary>
public class GlobalExceptionFilter
{
private readonly IHostingEnvironment _env;
private readonly ILoggerHelper _loggerHelper;
public GlobalExceptionFilter(IHostingEnvironment env,ILoggerHelper loggerHelper)
{
_env = env;
_loggerHelper = loggerHelper;
}
public void OnException(ExceptionContext context)
{
var json = new JsonErrorResponse();
json.Message = context.Exception.Message;//錯(cuò)誤信息
if (_env.IsDevelopment())
{
json.DevelopmentMessage = context.Exception.StackTrace;//堆棧信息
}
context.Result = new InternalServerErrorObjectResult(json);
//采用log4net 進(jìn)行錯(cuò)誤日志記錄
_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("【自定義錯(cuò)誤】:{0} \r\n【異常類型】:{1} \r\n【異常信息】:{2} \r\n【堆棧調(diào)用】:{3}", new object[] { throwMsg,
ex.GetType().Name, ex.Message, ex.StackTrace });
}
public class InternalServerErrorObjectResult : ObjectResult
{
public InternalServerErrorObjectResult(object value) : base(value)
{
StatusCode = StatusCodes.Status500InternalServerError;
}
}
//返回錯(cuò)誤信息
public class JsonErrorResponse
{
/// <summary>
/// 生產(chǎn)環(huán)境的消息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 開發(fā)環(huán)境的消息
/// </summary>
public string DevelopmentMessage { get; set; }
}
}
}
3干花、在啟動(dòng)服務(wù)中,注入全局異常
//注入全局異常捕獲
services.AddMvc(o =>
{
o.Filters.Add(typeof(GlobalExceptionsFilter));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
結(jié)構(gòu)是這樣的
4楞黄、自定義錯(cuò)誤進(jìn)行測試
我故意寫錯(cuò)數(shù)據(jù)庫連接字符串池凄,看看 swagger 如何報(bào)錯(cuò)
看看日志是如何記錄的
五、結(jié)語
今天是不定期更新系列鬼廓,也是群里小伙伴提出來的想法肿仑,我自己簡單搞搞,這里希望大家可以積極提意見喲碎税,如果技術(shù)不錯(cuò)尤慰,我會(huì)把你的個(gè)人主頁和Git放到文章中,也算是鼓勵(lì)大家的一個(gè)方式了雷蹂。