一、今日学习目标
- 掌握 .NET 配置系统(appsettings.json)
- 学会 IOptions 强类型绑定
- 集成 Serilog 高性能日志(取代默认 ConsoleLog)
- 日志级别、文件输出、控制台输出
- 完成:配置读取 + Serilog 集成实战练习
二、必背面试题 + 标准答案
1. .NET 配置来源有哪些?加载顺序?
答案:
- 来源:appsettings.json → 环境变量 → 命令行 → 用户机密
- 后加载的配置覆盖先加载的
- 开发用
appsettings.json,生产用环境变量
2. IOptions、IOptionsSnapshot、IOptionsMonitor 区别?
答案:
- IOptions<T> :单例,不热更新
- IOptionsSnapshot<T> :Scoped,作用域内热更新
- IOptionsMonitor<T> :单例,实时热更新
- 日常用 IOptionsSnapshot 最安全
3. 为什么要用 Serilog,而不用默认日志?
答案:
- 结构化日志,方便排查
- 支持文件、控制台、ES、MQ 等多种输出
- 性能高、社区主流
- 企业 100% 使用 Serilog
4. 日志级别(从低到高)
Verbose → Debug → Information → Warning → Error → Fatal
- 开发:Debug/Information
- 生产:Information/Warning/Error
5. appsettings.json 为什么要有两个?
appsettings.json:公共配置appsettings.Development.json:开发环境覆盖配置
6. 配置绑定的好处?
- 强类型、安全、智能提示
- 避免魔法字符串
三、安装 NuGet 包(必须先装)
cs
Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.File
Install-Package Serilog.Sinks.Console
Install-Package Microsoft.Extensions.Hosting
四、核心语法速记(.NET8 极简版)
1. 配置绑定
步骤 1: 创建配置类
首先,定义一个配置类(例如AppConfig),该类中的属性将对应于配置文件中的键。
cs
public class AppConfig
{
public string AppName { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public bool IsDebug { get; set; }
}
步骤 2: 配置 appsettings.json
在项目的根目录下创建或编辑appsettings.json文件,添加你的配置项。例如:
bash
"AppSettings": { //任意起名
"AppName": "MyNet8App",
"Version": "1.0.0",
"IsDebug": true
}
步骤 3: 注册配置类
在ASP.NET Core Web API应用程序中,你需要在Program.cs中注册配置类:
cs
//注册
builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppSettings"));
步骤 4: 使用配置类
现在你可以在应用程序的任何地方通过依赖注入来使用这个配置类了。例如,在服务类中使用:
cs
private readonly AppConfig _config; //使用配置类
// 构造函数注入: 配置
public AppService(IOptions<AppConfig> config)
{
_config = config.Value;
}
2. Serilog 注册
步骤 1: 配置 appsettings.json
cs
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
},
步骤 2: 注册Serilog
cs
builder.Host.UseSerilog((ctx, cfg) =>
{
// 从 appsettings.json 读取日志配置
cfg.ReadFrom.Configuration(ctx.Configuration);
});
步骤 3: 使用Serilog
cs
private readonly ILogger<AppService> _logger;
// 构造函数注入:日志
public AppService(ILogger<AppService> logger,IOptions<AppConfig> config)
{
_logger = logger;
}
四、Day9 实战练习:集成 Serilog + 配置读取
练习需求(.NET8 控制台)
- 创建 appsettings.json(属性:复制到输出目录 - 如果较新则复制)
- 配置 Serilog 输出到:
- 控制台
- 文件(按天分割)
- 定义一个配置类
AppConfig,绑定配置文件 - 注入日志
ILogger<T> - 输出不同级别日志:Debug、Info、Warn、Error
- 读取并打印配置
五、练习完整代码
AppConfig.cs
cs
public class AppConfig
{
public string AppName { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public bool IsDebug { get; set; }
}
appsettings.json
cs
//公共配置
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
//
//添加 Serilog 配置
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
},
//配置绑定
"AppSettings": { //任意起名
"AppName": "MyNet8App",
"Version": "1.0.0",
"IsDebug": true
}
}
AppService.cs
cs
public class AppService
{
private readonly ILogger<AppService> _logger;
private readonly AppConfig _config; //使用配置类
// 构造函数注入:日志 + 配置
public AppService(
ILogger<AppService> logger,
IOptions<AppConfig> config)
{
_logger = logger;
_config = config.Value;
}
public async Task RunAsync()
{
await Task.Delay(100);
// 输出不同级别日志
_logger.LogDebug("调试日志:服务启动成功");
_logger.LogInformation("信息日志:当前配置已加载");
_logger.LogWarning("警告日志:这是一条测试警告");
_logger.LogError("错误日志:这是一条测试错误");
// 读取配置
_logger.LogInformation("==================================");
_logger.LogInformation("应用名称:{Name}", _config.AppName);
_logger.LogInformation("版本号:{Ver}", _config.Version);
_logger.LogInformation("是否调试模式:{Debug}", _config.IsDebug);
_logger.LogInformation("==================================");
}
}
Program.cs
cs
//// ==========================================
//// .NET 8 主机 + Serilog 日志 + 配置系统
//// ==========================================
var builder = WebApplication.CreateBuilder(args);
// 1. 绑定配置文件 → 强类型类
builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppSettings"));
// 2. 注册测试服务
builder.Services.AddTransient<AppService>(); //生命周期:Transient
//Serilog 注册
builder.Host.UseSerilog((ctx, cfg) =>
{
// 从 appsettings.json 读取日志配置
cfg.ReadFrom.Configuration(ctx.Configuration);
});
// 启动服务(通过IServiceProvider获取服务的实例) .Services.GetRequiredService<AppService>();
var app = builder.Build().Services.GetRequiredService<AppService>();
await app.RunAsync();
Log.Information("程序运行结束");
Log.CloseAndFlush(); // 确保日志写入