在软件设计中日志模块是必不可少的一部分,可以帮助开发人员更好的了解程序的运行情况,提高软件的可靠性,安全性和性能,日志通常能帮我们解决如下问题:
.net6有自带的logging组件,还有很多优秀的开源log组件,如NLog,serilog,这里我们使用serilog组件来构建日志模块。
新建.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
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( //单个日志文件,总日志,所有日志存到这里面
$"logs\\\\log.txt",
rollingInterval: RollingInterval.Day,
outputTemplate: outputTemplate)
.WriteTo.File( //每天生成一个新的日志,按天来存日志
"logs\\\\{Date}-log.txt", //定输出到滚动日志文件中,每天会创建一个新的日志,按天来存日志
retainedFileCountLimit: 7,
outputTemplate: outputTemplate
))
.CreateLogger();
configureHostBuilder.UseSerilog(Log.Logger); // 注册serilog
/// <summary>
/// 设置日志sqlserver配置
/// </summary>
/// <returns></returns>
MSSqlServerSinkOptions GetSqlServerSinkOptions()
{
var sqlsinkotpions = new MSSqlServerSinkOptions();
sqlsinkotpions.TableName = "sys\_Serilog";//表名称
sqlsinkotpions.SchemaName = "dbo";//数据库模式
sqlsinkotpions.AutoCreateSqlTable = true;//是否自动创建表
return sqlsinkotpions;
}
/// <summary>
/// 设置日志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));//添加一列,用于记录请求参数string
columlist.Add(new SqlColumn("ResponseJson", SqlDbType.NVarChar, true, 2000));//添加一列,用于记录响应数据
customColumnOptions.AdditionalColumns = columlist;
return customColumnOptions;
}
}
}
然后再program.cs中调用这个扩展方法
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();
这里我设计的日志信息只包括了
其中前面四种为日志默认,后两种为我主动添加,在实际的设计中还有可能有不同的信息,如:
日志的设计应该根据实际的情况而来,其应做到足够详尽,能帮助开发者定位,解决问题,而又不能过于重复臃肿,白白占用系统空间,我这边的示例仅供大家参考
public class RequestLoggingFilter : IActionFilter
{
private readonly Serilog.ILogger \_logger;//注入serilog
private Stopwatch \_stopwatch;//统计程序耗时
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))//响应数据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();
在控制器添加一个测试方法并将其调用一次
[HttpGet]
public dynamic Get123(string model)
{
return new { name = "123", id = 2 };
}
控制台输出
数据库记录
项目根目录下logs文件夹中日志文件记录
手机扫一扫
移动阅读更方便
你可能感兴趣的文章