Skip to content

Commit d17c554

Browse files
committed
feat(logger): 添加 MongoDB 日志存储支持和日志输出模板配置
添加 Serilog.Sinks.MongoDB 依赖支持将日志写入 MongoDB 新增 LogOptions 配置项:IsWriteToMongoDb、DatabaseUrl、CappedMaxSizeMb、CappedMaxDocuments 支持自定义控制台和文件日志输出模板格式 优化日志输出显示方式,使用 LogHelper.ShowOption 替代直接 Console.WriteLine
1 parent cd52c01 commit d17c554

3 files changed

Lines changed: 99 additions & 6 deletions

File tree

GameFrameX.Foundation.Logger/GameFrameX.Foundation.Logger.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,11 @@
5050
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
5151
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0"/>
5252
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="8.3.1" />
53+
<PackageReference Include="Serilog.Sinks.MongoDB" Version="7.2.0" />
5354
</ItemGroup>
5455

5556
<ItemGroup>
57+
<ProjectReference Include="..\GameFrameX.Foundation.Extensions\GameFrameX.Foundation.Extensions.csproj" />
5658
<ProjectReference Include="..\GameFrameX.Foundation.Json\GameFrameX.Foundation.Json.csproj" />
5759
</ItemGroup>
5860

GameFrameX.Foundation.Logger/LogHandler.cs

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
66

77
using System.IO.Compression;
8+
using GameFrameX.Foundation.Extensions;
89
using Serilog;
910
using Serilog.Events;
1011
using Serilog.Sinks.Grafana.Loki;
@@ -79,18 +80,24 @@ public static ILogger Create(LogOptions logOptions, bool isDefault = true, Actio
7980
Directory.CreateDirectory(logFolderPath);
8081
}
8182

82-
Console.WriteLine("the following is the log configuration information");
83-
Console.WriteLine("╔═════════════════════════════════════════════════════════╗");
84-
Console.WriteLine(logOptions);
85-
Console.WriteLine("╚═════════════════════════════════════════════════════════╝");
83+
84+
// Console.WriteLine("the following is the log configuration information");
85+
if (isDefault)
86+
{
87+
LogHelper.ShowOption("log configuration information", logOptions);
88+
}
89+
90+
// Console.WriteLine("╔═════════════════════════════════════════════════════════╗");
91+
// Console.WriteLine(logOptions);
92+
// Console.WriteLine("╚═════════════════════════════════════════════════════════╝");
8693
Console.WriteLine();
8794
var logger = CreateLoggerConfiguration().Enrich.WithProperty("AppType", logOptions.LogType ?? AppDomain.CurrentDomain.FriendlyName);
8895
if (!string.IsNullOrEmpty(logOptions.LogTagName))
8996
{
9097
logger.Enrich.WithProperty("TagName", logOptions.LogTagName ?? "");
9198
}
9299

93-
logger.WriteTo.File(logPath, rollingInterval: logOptions.RollingInterval, rollOnFileSizeLimit: logOptions.IsFileSizeLimit, fileSizeLimitBytes: logOptions.FileSizeLimitBytes, retainedFileCountLimit: logOptions.RetainedFileCountLimit);
100+
94101
if (logOptions.IsGrafanaLoki)
95102
{
96103
var grafanaLokiLabels = new List<LokiLabel>();
@@ -149,6 +156,31 @@ public static ILogger Create(LogOptions logOptions, bool isDefault = true, Actio
149156
}
150157

151158
configurationAction?.Invoke(logger);
159+
160+
string consoleOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}][{TagName}]{Message:lj}{NewLine}{Exception}";
161+
string fileOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}][{FriendlyName}] {Message:lj}{NewLine}{Exception}";
162+
163+
if (logOptions.ConsoleOutputTemplate.IsNotNullOrEmptyOrWhiteSpace())
164+
{
165+
consoleOutputTemplate = logOptions.ConsoleOutputTemplate;
166+
}
167+
168+
if (logOptions.FileOutputTemplate.IsNotNullOrEmptyOrWhiteSpace())
169+
{
170+
fileOutputTemplate = logOptions.FileOutputTemplate;
171+
}
172+
if (logOptions.IsWriteToFile)
173+
{
174+
logger.WriteTo.File(logPath,
175+
shared: true,
176+
restrictedToMinimumLevel: logOptions.LogEventLevel,
177+
outputTemplate: fileOutputTemplate,
178+
rollingInterval: logOptions.RollingInterval,
179+
rollOnFileSizeLimit: logOptions.FileSizeLimitBytes > 0,
180+
fileSizeLimitBytes: logOptions.FileSizeLimitBytes
181+
);
182+
}
183+
152184
switch (logOptions.LogEventLevel)
153185
{
154186
case LogEventLevel.Verbose:
@@ -185,7 +217,9 @@ public static ILogger Create(LogOptions logOptions, bool isDefault = true, Actio
185217

186218
if (logOptions.IsConsole)
187219
{
188-
logger.WriteTo.Console();
220+
logger.WriteTo.Console(outputTemplate: consoleOutputTemplate,
221+
restrictedToMinimumLevel: logOptions.LogEventLevel,
222+
theme: Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme.Literate);
189223
}
190224

191225
var serilog = logger.CreateLogger();

GameFrameX.Foundation.Logger/LogOptions.cs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ public LogOptions(string logPathName = "logs")
3434
/// </remarks>
3535
public static readonly LogOptions Default = new LogOptions();
3636

37+
/// <summary>
38+
/// 是否写入文件,默认为 true。
39+
/// </summary>
40+
public bool IsWriteToFile { get; set; } = true;
41+
3742
/// <summary>
3843
/// 服务器类型,用于标识日志来源的服务器类型。
3944
/// </summary>
@@ -50,6 +55,29 @@ public LogOptions(string logPathName = "logs")
5055
/// </remarks>
5156
public string LogTagName { get; set; } = "";
5257

58+
/// <summary>
59+
/// 是否写入数据库,默认为 false。
60+
/// </summary>
61+
public bool IsWriteToMongoDb { get; set; } = false;
62+
63+
/// <summary>
64+
/// mongodb 地址 用于保存日志
65+
/// </summary>
66+
/// <remarks>
67+
/// 如果配置了Type = Db 必须要配置 databaseUrl
68+
/// </remarks>
69+
public string DatabaseUrl { get; set; } = "mongodb://127.0.0.1:27017/gameserver?authSource=admin";
70+
71+
/// <summary>
72+
/// mongodb 创建的上限集合的最大总大小(MB)
73+
/// </summary>
74+
public int CappedMaxSizeMb { get; set; } = 50;
75+
76+
/// <summary>
77+
/// mongodb 创建的上限集合的最大文档数。
78+
/// </summary>
79+
public int CappedMaxDocuments { get; set; } = 50000;
80+
5381
/// <summary>
5482
/// 日志存储路径,为 应用程序运行目录下的子目录/logs。
5583
/// </summary>
@@ -146,6 +174,35 @@ public LogOptions(string logPathName = "logs")
146174
/// </remarks>
147175
public int? RetainedFileCountLimit { get; set; } = 31;
148176

177+
178+
/// <summary>
179+
/// 控制台日志输出格式模板,默认格式为 "[时:分:秒 级别][标签名]消息内容"。
180+
/// </summary>
181+
/// <remarks>
182+
/// 支持的占位符包括:
183+
/// - {Timestamp:HH:mm:ss} - 时间戳(时:分:秒格式)
184+
/// - {Level:u3} - 日志级别(3个字符大写)
185+
/// - {TagName} - 日志标签名称
186+
/// - {Message:lj} - 日志消息内容(左对齐)
187+
/// - {NewLine} - 换行符
188+
/// - {Exception} - 异常信息
189+
/// </remarks>
190+
public string ConsoleOutputTemplate { get; set; } = "[{Timestamp:HH:mm:ss} {Level:u3}][{TagName}]{Message:lj}{NewLine}{Exception}";
191+
192+
/// <summary>
193+
/// 文件日志输出格式模板,默认格式为 "完整时间戳 [级别][友好名称] 消息内容"。
194+
/// </summary>
195+
/// <remarks>
196+
/// 支持的占位符包括:
197+
/// - {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} - 完整时间戳(包含毫秒和时区)
198+
/// - {Level:u3} - 日志级别(3个字符大写)
199+
/// - {FriendlyName} - 友好名称
200+
/// - {Message:lj} - 日志消息内容(左对齐)
201+
/// - {NewLine} - 换行符
202+
/// - {Exception} - 异常信息
203+
/// </remarks>
204+
public string FileOutputTemplate { get; set; } = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}][{FriendlyName}] {Message:lj}{NewLine}{Exception}";
205+
149206
/// <summary>
150207
/// 返回日志配置对象的 JSON 字符串表示形式。
151208
/// </summary>

0 commit comments

Comments
 (0)