Jeff.Log
0.2.4
dotnet add package Jeff.Log --version 0.2.4
NuGet\Install-Package Jeff.Log -Version 0.2.4
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Jeff.Log" Version="0.2.4" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Jeff.Log" Version="0.2.4" />
<PackageReference Include="Jeff.Log" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Jeff.Log --version 0.2.4
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Jeff.Log, 0.2.4"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Jeff.Log@0.2.4
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Jeff.Log&version=0.2.4
#tool nuget:?package=Jeff.Log&version=0.2.4
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
概述
简单的日志提供程序, 简化自定义日志处理, 支持系统日志和 Http 日志。
本类库不包含内置输出目标, 必须添加自定义目标。
快速开始
系统日志
builder.Logging.ClearProviders();
builder.Logging.AddJeffLogger(cfg =>
{
//自定义输出到控制台
cfg.AddTarget("console", (log, serviceProvider) =>
{
Console.WriteLine($"{log.TimeStamp:yyyyMMdd} [{log.LogLevel}] {log.Message}");
});
//自定义输出到数据库
cfg.AddTarget("database", (log, serviceProvider) =>
{
using var scope = serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<LogContext>();
db.Log.Add(new Log
{
Time = log.TimeStamp,
Level = log.LogLevel?.ToString(),
Message = log.Message
});
db.SaveChanges();
});
//自定义输出到文件
SpinLock logToFileLock = new();
cfg.AddTarget("file", (log, serviceProvider) =>
{
bool lockTaken = false;
try
{
logToFileLock.Enter(ref lockTaken);
var filePath = Path.Combine(AppContext.BaseDirectory, "logs", $"log_{DateTime.Today:yyyyMMdd}.log");
using StreamWriter sw = new(filePath, true);
sw.WriteLine($"{log.TimeStamp:yyyyMMdd} [{log.LogLevel}] {log.Message}");
}
finally
{
if (lockTaken) logToFileLock.Exit();
}
});
});
//警告,日志数据库上下文操作不产生日志,以防无限循环
builder.Services.AddDbContext<LogContext>(opt =>
{
opt.UseMySql(builder.Configuration.GetConnectionString("log"), ServerVersion.Parse("8.0"));
opt.UseLoggerFactory(NullLoggerFactory.Instance);
});
HTTP 日志
appsettings.json
//添加 Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware 行
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
Program.cs
// Http日志中的"接口描述(ApiDescription)", 基于 Swagger 的 Xml Comments, 可选。
builder.Services.AddSwaggerGen(opt =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
opt.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
builder.Logging.AddJeffLogger(cfg =>
{
//自定义 HTTP 日志输出, 只记录POST/DELETE/PUT请求
cfg.HttpLog.AddTarget("http", (log, serviceProvider, httpContext) =>
{
Console.WriteLine($"{log.RequestMethod} {log.RequestPath}: {log.ApiDescription}");
}, ["post","delete","put"]);
cfg.HttpLog.SensitiveRequestPaths = [@"^/login/.+$"];
});
var app = builder.Build();
app.UseHttpLogging(); //使用Http日志必须添加此中间件
app.UseSwagger();
app.UseSwaggerUI();
LogLevel 配置
可以通过配置文件为 target 指定不同的日志级别。用于系统日志。
注意:
Target 的 LogLevel 必须在 "Jeff:LogLevel" 的范围之内。
任何 Target 记录的日志, 都是在 "Jeff:LogLevel" 基础的进一步筛选。Target 的 LogLevel 如果超过 "Jeff:LogLevel" 也不会生效。
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information",
"Microsoft.AspNetCore": "Warning"
},
"Jeff": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information",
"Microsoft.EntityFrameworkCore": "Warning"
},
"Targets": [
{
"Name": "console",
"LogLevel": {
"Default": "Warning",
"Microsoft.Hosting": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
},
{
"Name": "file",
"LogLevel": {
"Default": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
}
]
}
}
其他
HttpLog
public class HttpLog
{
public DateTime TimeStamp { get; set; }
public string? TraceId { get; set; }
public string? RequestMethod { get; set; }
public string? RequestQuery { get; set; }
public string? RequestPath { get; set; }
public string? RequestBody { get; set; }
public int? ResponseStatusCode { get; set; }
public string? ResponseBody { get; set; }
/// <summary>
/// 持续时间
/// </summary>
public float? Duration { get; set; }
/// <summary>
/// 远程IP
/// </summary>
public string? RemoteIP { get; set; }
/// <summary>
/// API描述, 基于 Swagger
/// </summary>
public string? ApiDescription { get; set; }
}
SystemLog
public class SystemLog
{
public DateTime TimeStamp { get; set; }
public string? Catalog { get; set; }
public string? LogLevel { get; set; }
public string? LogEvent { get; set; }
public string? TraceId { get; set; }
public string? Message { get; set; }
public string? Exception { get; set; }
}
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- Microsoft.AspNetCore.Http.Abstractions (>= 2.3.0)
- Microsoft.Extensions.Logging.Configuration (>= 8.0.1)
- Swashbuckle.AspNetCore.SwaggerGen (>= 8.1.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.