You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
3.2 KiB
75 lines
3.2 KiB
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Serilog;
|
|
using Serilog.Events;
|
|
using System;
|
|
using System.IO;
|
|
|
|
namespace AuroraDesk.Infrastructure.Extensions;
|
|
|
|
/// <summary>
|
|
/// HostBuilder 扩展方法(基础设施层)
|
|
/// 用于配置日志记录功能
|
|
/// </summary>
|
|
public static class HostBuilderExtensions
|
|
{
|
|
/// <summary>
|
|
/// 配置文件日志记录
|
|
/// </summary>
|
|
/// <param name="hostBuilder">HostBuilder</param>
|
|
/// <returns>HostBuilder</returns>
|
|
/// <remarks>
|
|
/// 配置优先级说明:
|
|
/// 1. 代码中的配置(WriteTo.Console、WriteTo.File)优先级最高,会覆盖配置文件中的相同配置
|
|
/// 2. serilog.json 文件中的 "Serilog" 节点配置次之,会被 ReadFrom.Configuration 读取
|
|
///
|
|
/// 注意:Serilog 配置已提取到独立的 serilog.json 文件中,便于管理和维护
|
|
/// </remarks>
|
|
public static IHostBuilder ConfigureFileLogging(this IHostBuilder hostBuilder)
|
|
{
|
|
return hostBuilder.UseSerilog((context, services, configuration) =>
|
|
{
|
|
var environment = context.HostingEnvironment;
|
|
|
|
// 配置日志目录
|
|
var logDirectory = Path.Combine(
|
|
Directory.GetCurrentDirectory(),
|
|
"logs"
|
|
);
|
|
|
|
// 确保日志目录存在
|
|
if (!Directory.Exists(logDirectory))
|
|
{
|
|
Directory.CreateDirectory(logDirectory);
|
|
}
|
|
|
|
// 配置 Serilog
|
|
// 注意:ReadFrom.Configuration 会读取 serilog.json 文件中的 "Serilog" 节点
|
|
// 然后代码中的配置会在此基础上添加或覆盖
|
|
configuration
|
|
.ReadFrom.Configuration(context.Configuration) // 读取 serilog.json 中的 "Serilog" 节点
|
|
.ReadFrom.Services(services)
|
|
.Enrich.FromLogContext()
|
|
.Enrich.WithProperty("Environment", environment.EnvironmentName)
|
|
// 以下代码配置会覆盖配置文件中相同类型的配置(如果存在)
|
|
.WriteTo.Console(
|
|
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
|
restrictedToMinimumLevel: LogEventLevel.Information
|
|
)
|
|
.WriteTo.File(
|
|
path: Path.Combine(logDirectory, "auroradesk-.log"),
|
|
rollingInterval: RollingInterval.Day,
|
|
retainedFileCountLimit: 30,
|
|
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}",
|
|
restrictedToMinimumLevel: LogEventLevel.Debug
|
|
)
|
|
.WriteTo.File(
|
|
path: Path.Combine(logDirectory, "auroradesk-error-.log"),
|
|
rollingInterval: RollingInterval.Day,
|
|
retainedFileCountLimit: 60,
|
|
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}",
|
|
restrictedToMinimumLevel: LogEventLevel.Error
|
|
);
|
|
});
|
|
}
|
|
}
|
|
|