欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何在.Net6 web api中記錄每次接口請求的日志

 更新時間:2023年06月28日 08:48:03   作者:颾浪劍客  
.net6有自帶的logging組件,還有很多優(yōu)秀的開源log組件,如NLog,serilog,這里我們使用serilog組件來構(gòu)建日志模塊,這篇文章主要介紹了如何在.Net6 web api中記錄每次接口請求的日志,需要的朋友可以參考下

為什么在軟件設(shè)計中一定要有日志系統(tǒng)?

在軟件設(shè)計中日志模塊是必不可少的一部分,可以幫助開發(fā)人員更好的了解程序的運行情況,提高軟件的可靠性,安全性和性能,日志通常能幫我們解決如下問題:

  • 調(diào)試和故障排查:日志可以記錄程序運行時的各種信息,包括錯誤,異常,警告等,方便開發(fā)人員在出現(xiàn)問題時進行調(diào)試和故障排查。
  • 性能優(yōu)化:日志可以記錄程序的運行時間,資源占用等信息,幫助開發(fā)人員進行性能優(yōu)化。
  • 安全審計:日志可以記錄用戶的操作行為,方便進行安全審計和追蹤。
  • 統(tǒng)計分析:日志可以記錄用戶的訪問情況,使用習慣等信息,方便進行統(tǒng)計分析和用戶行為研究。
  • 業(yè)務(wù)監(jiān)控:日志可以記錄業(yè)務(wù)數(shù)據(jù)的變化情況,方便進行業(yè)務(wù)監(jiān)控和數(shù)據(jù)分析。
  • 數(shù)據(jù)還原:日志記錄每次請求的請求及響應(yīng)數(shù)據(jù),可以在數(shù)據(jù)丟失的情況下還原數(shù)據(jù)。

如何在.net6webapi中添加日志?

1.添加日志組件

.net6有自帶的logging組件,還有很多優(yōu)秀的開源log組件,如NLog,serilog,這里我們使用serilog組件來構(gòu)建日志模塊。

新建.net6,asp net web api項目之后,為其添加如下四個包

dotnet add package Serilog.AspNetCore//核心包
dotnet add package Serilog.Formatting.Compact
dotnet add Serilog.Sinks.File//提供記錄到文件
dotnet add Serilog.Sinks.MSSqlServer//提供記錄到sqlserver

2.新建SeriLogExtend擴展類型,配置日志格式并注入

public static class SeriLogExtend
    {
        public static void AddSerilLog(this ConfigureHostBuilder configureHostBuilder)
        {
            //輸出模板
            string outputTemplate = "{NewLine}【{Level:u3}】{Timestamp:yyyy-MM-dd HH:mm:ss.fff}" +
                                    "{NewLine}#Msg#{Message:lj}" +
                                    "{NewLine}#Pro #{Properties:j}" +
                                    "{NewLine}#Exc#{Exception}" +
                                     new string('-', 50);
            // 配置Serilog
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 排除Microsoft的日志
                .Enrich.FromLogContext() // 注冊日志上下文
                .WriteTo.Console(outputTemplate: outputTemplate) // 輸出到控制臺
                .WriteTo.MSSqlServer("Server=.;Database=testdb;User ID=sa;Password=123;TrustServerCertificate=true", sinkOptions: GetSqlServerSinkOptions(), columnOptions: GetColumnOptions())
                .WriteTo.Logger(configure => configure // 輸出到文件
                            .MinimumLevel.Debug()
                            .WriteTo.File(  //單個日志文件,總?cè)罩荆腥罩敬娴竭@里面
                                $"logs\\log.txt",
                                rollingInterval: RollingInterval.Day,
                                outputTemplate: outputTemplate)
                            .WriteTo.File( //每天生成一個新的日志,按天來存日志
                                "logs\\{Date}-log.txt", //定輸出到滾動日志文件中,每天會創(chuàng)建一個新的日志,按天來存日志
                                retainedFileCountLimit: 7,
                                outputTemplate: outputTemplate
                            ))
                .CreateLogger();
            configureHostBuilder.UseSerilog(Log.Logger); // 注冊serilog
            /// <summary>
            /// 設(shè)置日志sqlserver配置
            /// </summary>
            /// <returns></returns>
            MSSqlServerSinkOptions GetSqlServerSinkOptions()
            {
                var sqlsinkotpions = new MSSqlServerSinkOptions();
                sqlsinkotpions.TableName = "sys_Serilog";//表名稱
                sqlsinkotpions.SchemaName = "dbo";//數(shù)據(jù)庫模式
                sqlsinkotpions.AutoCreateSqlTable = true;//是否自動創(chuàng)建表
                return sqlsinkotpions;
            }
            /// <summary>
            /// 設(shè)置日志sqlserver 列配置
            /// </summary>
            /// <returns></returns>
            ColumnOptions GetColumnOptions()
            {
                var customColumnOptions = new ColumnOptions();
                customColumnOptions.Store.Remove(StandardColumn.MessageTemplate);//刪除多余的這兩列
                customColumnOptions.Store.Remove(StandardColumn.Properties);
                var columlist = new List<SqlColumn>();
                columlist.Add(new SqlColumn("RequestJson", SqlDbType.NVarChar, true, 2000));//添加一列,用于記錄請求參數(shù)string
                columlist.Add(new SqlColumn("ResponseJson", SqlDbType.NVarChar, true, 2000));//添加一列,用于記錄響應(yīng)數(shù)據(jù)
                customColumnOptions.AdditionalColumns = columlist;
                return customColumnOptions;
            }
        }
    }

然后再program.cs中調(diào)用這個擴展方法

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(options =>
{
    options.Filters.Add(typeof(RequestLoggingFilter));
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Host.AddSerilLog();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

這里我設(shè)計的日志信息只包括了

  • Message:日志信息
  • Level:等級
  • TimeStamp:記錄日志時間
  • Exception:異常信息
  • RequestJson:請求參數(shù)json
  • ResponseJson:響應(yīng)結(jié)果json

其中前面四種為日志默認,后兩種為我主動添加,在實際的設(shè)計中還有可能有不同的信息,如:

  • IP:請求日志
  • Action:請求方法
  • Token:請求token
  • User:請求的用戶

日志的設(shè)計應(yīng)該根據(jù)實際的情況而來,其應(yīng)做到足夠詳盡,能幫助開發(fā)者定位,解決問題,而又不能過于重復(fù)臃腫,白白占用系統(tǒng)空間,我這邊的示例僅供大家參考

3.添加RequestLoggingFilter過濾器,用以記錄每次請求的日志

public class RequestLoggingFilter : IActionFilter
    {
        private readonly Serilog.ILogger _logger;//注入serilog
        private Stopwatch _stopwatch;//統(tǒng)計程序耗時
        public RequestLoggingFilter(Serilog.ILogger logger)
        {
            _logger = logger;
            _stopwatch = Stopwatch.StartNew();
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            _stopwatch.Stop();
            var request = context.HttpContext.Request;
            var response = context.HttpContext.Response;
            _logger
                .ForContext("RequestJson",request.QueryString)//請求字符串
                .ForContext("ResponseJson", JsonConvert.SerializeObject(context.Result))//響應(yīng)數(shù)據(jù)json
                .Information("Request {Method} {Path} responded {StatusCode} in {Elapsed:0.0000} ms",//message
                request.Method,
                request.Path,
                response.StatusCode,
                _stopwatch.Elapsed.TotalMilliseconds);
        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
        }
    }

在program.cs中將該過濾器添加進所有控制器之中

builder.Services.AddControllers(options =>
{
    options.Filters.Add(typeof(RequestLoggingFilter));
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Host.AddSerilLog();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

測試效果

在控制器添加一個測試方法并將其調(diào)用一次

[HttpGet]
public dynamic Get123(string model)
{
    return new { name = "123", id = 2 };
}

控制臺輸出

數(shù)據(jù)庫記錄

項目根目錄下logs文件夾中日志文件記錄

到此這篇關(guān)于如何在.Net6 web api中記錄每次接口請求的日志的文章就介紹到這了,更多相關(guān).net記錄每次接口請求的日志內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論