.Net6 Core Web API 配置 log4net + MySQL

目录

一、导入NuGet 包

二、添加配置文件  log4net.config 

三、创建MySQL表格

四、Program全局配置

五、帮助类编写

六、效果展示


小编没有使用依赖注入的方式。

一、导入NuGet 包

        ----  log4net        基础包   
        ----  Microsoft.Extensions.Logging.Log4Net.AspNetCore          扩展包
        ----  MySql.Data        数据库包

二、添加配置文件  log4net.config 

.Net6 Core Web API 配置 log4net + MySQL_第1张图片

需改数据库的字符串



	
		
		

三、创建MySQL表格

CREATE TABLE `log4net` (
`log_datetime` datetime DEFAULT NULL,
`log_thread` varchar(255) DEFAULT NULL,
`log_level` varchar(255) DEFAULT NULL,
`log_logger` varchar(255) DEFAULT NULL,
`log_message` varchar(4000) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

四、Program全局配置

// 全局配置 log4net
ILoggerRepository repository = LogManager.CreateRepository("LogRepository");
// 读取配置文件
XmlConfigurator.Configure(repository, new FileInfo("Log4/log4net.config"));
// log错误日志配置
builder.Services.AddControllers(options =>
{
    options.SuppressAsyncSuffixInActionNames = false;
    options.Filters.Add(typeof(GlobalExceptionsFilter));
});

五、帮助类编写

/// 
/// 日志帮助实现类
/// 
public class LoggerHelper
{
    private static readonly ILog Log = LogManager.GetLogger("LogRepository", typeof(TClass));

    
    public static void Debug(string msg) => Log.Debug(msg);
    
    public static void Info(string msg) => Log.Info(msg);
    
    public static void Warn(string msg) => Log.Warn(msg);
    
    public static void Error(string msg) => Log.Error(msg);
    
    public static void Fatal(string msg) => Log.Fatal(msg);
}
/// 
/// 全局异常错误日志
/// // log错误日志配置
/// builder.Services.AddControllers(options =>
/// {
///     options.SuppressAsyncSuffixInActionNames = false;
///     options.Filters.Add(typeof(GlobalExceptionsFilter));
/// });
/// 
public class GlobalExceptionsFilter : IExceptionFilter
{
    private readonly IWebHostEnvironment _env;
 
    public GlobalExceptionsFilter(IWebHostEnvironment env)
    {
        _env = env;
    }
    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(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; }
}

六、效果展示

/// 
/// 测试代码
/// 
[HttpGet]
public string Index()
{
    LoggerHelper.Info("WWWWWWW");
    LoggerHelper.Info("PPPP");
    throw new Exception("RRRRRRRR");
    return "OK";
}

.Net6 Core Web API 配置 log4net + MySQL_第2张图片


\bin\Debug\net6.0\Log.Net6 Core Web API 配置 log4net + MySQL_第3张图片

如有错误,烦请批评指正

你可能感兴趣的:(c#,.net,mysql)