Skip to content

Commit 4ec6692

Browse files
committed
refactor(Logger): 优化日志配置和MongoDB相关属性命名
- 重命名MongoDB相关属性以增加一致性 - 提取日志输出模板为常量 - 改进日志路径处理逻辑 - 优化属性初始化方式 - 更新XML文档注释以提供更详细的MongoDB连接说明
1 parent b65b410 commit 4ec6692

2 files changed

Lines changed: 55 additions & 25 deletions

File tree

GameFrameX.Foundation.Logger/LogHandler.cs

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ namespace GameFrameX.Foundation.Logger;
1818
/// </summary>
1919
public static class LogHandler
2020
{
21-
private static bool _isInitSerilogDiagnosis = false;
21+
private static bool _isInitSerilogDiagnosis;
2222

2323
/// <summary>
2424
/// 启用 Serilog 的自动诊断
@@ -54,6 +54,16 @@ public static LoggerConfiguration CreateLoggerConfiguration()
5454
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning);
5555
}
5656

57+
/// <summary>
58+
/// 控制台输出模板,用于格式化控制台日志输出。
59+
/// </summary>
60+
const string ConsoleOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}][{LogType}-{TagName}]{Message:lj}{NewLine}{Exception}";
61+
62+
/// <summary>
63+
/// 文件输出模板,用于格式化文件日志输出。
64+
/// </summary>
65+
const string FileOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}][{LogType}-{TagName}] {Message:lj}{NewLine}{Exception}";
66+
5767
/// <summary>
5868
/// 启动并配置日志系统
5969
/// </summary>
@@ -68,9 +78,20 @@ public static ILogger Create(LogOptions logOptions, bool isDefault = true, Actio
6878
SerilogDiagnosis();
6979
try
7080
{
71-
// 日志文件存储的路径
81+
// 文件名
7282
var logFileName = $"{(logOptions.LogType ?? AppDomain.CurrentDomain.FriendlyName).ToLower()}_.log";
83+
// 日志文件存储的路径
7384
var logSavePath = logOptions.LogSavePath ?? "./logs/";
85+
if (!logSavePath.EndsWithFast("/"))
86+
{
87+
logSavePath += "/";
88+
}
89+
90+
if (!string.IsNullOrEmpty(logOptions.LogTagName))
91+
{
92+
logSavePath += logOptions.LogTagName + "/";
93+
}
94+
7495
// 计算最终日志文件路径
7596
var logPath = Path.Combine(logSavePath, logFileName);
7697
// 兼容可能的层级目录:始终创建文件所在的目录
@@ -80,23 +101,15 @@ public static ILogger Create(LogOptions logOptions, bool isDefault = true, Actio
80101
Directory.CreateDirectory(logFolderPath);
81102
}
82103

83-
84-
// Console.WriteLine("the following is the log configuration information");
85104
if (isDefault)
86105
{
87106
LogHelper.ShowOption("log configuration information", logOptions);
88107
}
89108

90-
// Console.WriteLine("╔═════════════════════════════════════════════════════════╗");
91-
// Console.WriteLine(logOptions);
92-
// Console.WriteLine("╚═════════════════════════════════════════════════════════╝");
93-
Console.WriteLine();
94-
var logger = CreateLoggerConfiguration().Enrich.WithProperty("AppType", logOptions.LogType ?? AppDomain.CurrentDomain.FriendlyName);
95-
if (!string.IsNullOrEmpty(logOptions.LogTagName))
96-
{
97-
logger.Enrich.WithProperty("TagName", logOptions.LogTagName ?? "");
98-
}
99-
109+
var logger = CreateLoggerConfiguration();
110+
logger.Enrich.WithProperty("LogType", logOptions.LogType);
111+
logger.Enrich.WithProperty("FriendlyName", AppDomain.CurrentDomain.FriendlyName);
112+
logger.Enrich.WithProperty("TagName", logOptions.LogTagName ?? "");
100113

101114
if (logOptions.IsGrafanaLoki)
102115
{
@@ -156,15 +169,14 @@ public static ILogger Create(LogOptions logOptions, bool isDefault = true, Actio
156169
}
157170

158171
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}";
172+
string consoleOutputTemplate = ConsoleOutputTemplate;
162173

163174
if (logOptions.ConsoleOutputTemplate.IsNotNullOrEmptyOrWhiteSpace())
164175
{
165176
consoleOutputTemplate = logOptions.ConsoleOutputTemplate;
166177
}
167178

179+
string fileOutputTemplate = FileOutputTemplate;
168180
if (logOptions.FileOutputTemplate.IsNotNullOrEmptyOrWhiteSpace())
169181
{
170182
fileOutputTemplate = logOptions.FileOutputTemplate;
@@ -225,15 +237,15 @@ public static ILogger Create(LogOptions logOptions, bool isDefault = true, Actio
225237
var serilog = logger.CreateLogger();
226238
if (isDefault)
227239
{
228-
Serilog.Log.Logger = serilog;
240+
Log.Logger = serilog;
229241
LogHelper.SetLogger(serilog);
230242
}
231243

232244
return serilog;
233245
}
234246
catch (Exception e)
235247
{
236-
Serilog.Log.Error($"配置日志系统过程中发生错误,异常:{e}");
248+
Log.Error($"配置日志系统过程中发生错误,异常:{e}");
237249
throw;
238250
}
239251
}

GameFrameX.Foundation.Logger/LogOptions.cs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,22 +61,41 @@ public LogOptions(string logPathName = "logs")
6161
public bool IsWriteToMongoDb { get; set; } = false;
6262

6363
/// <summary>
64-
/// mongodb 地址 用于保存日志
64+
/// MongoDB 数据库连接地址,用于保存日志数据
6565
/// </summary>
6666
/// <remarks>
67-
/// 如果配置了Type = Db 必须要配置 databaseUrl
67+
/// <para>
68+
/// 当 <see cref="IsWriteToMongoDb"/> 设置为 true 时,此属性必须配置有效的 MongoDB 连接字符串。
69+
/// 连接字符串应包含数据库服务器地址、端口、数据库名称和认证信息。
70+
/// </para>
71+
/// <para>
72+
/// 连接字符串格式:mongodb://[username:password@]host[:port]/database[?options]
73+
/// </para>
74+
/// <para>
75+
/// 常用配置示例:
76+
/// <list type="bullet">
77+
/// <item><description>本地无认证:mongodb://localhost:27017/gameserver</description></item>
78+
/// <item><description>本地有认证:mongodb://user:password@localhost:27017/gameserver?authSource=admin</description></item>
79+
/// <item><description>远程服务器:mongodb://user:password@192.168.1.100:27017/gameserver?authSource=admin</description></item>
80+
/// <item><description>副本集:mongodb://user:password@host1:27017,host2:27017/gameserver?replicaSet=rs0&amp;authSource=admin</description></item>
81+
/// </list>
82+
/// </para>
83+
/// <para>
84+
/// 注意:确保 MongoDB 服务器已启动且网络连接正常,否则日志写入将失败。
85+
/// </para>
6886
/// </remarks>
69-
public string DatabaseUrl { get; set; } = "mongodb://127.0.0.1:27017/gameserver?authSource=admin";
87+
/// <value>默认值为本地 MongoDB 实例:mongodb://127.0.0.1:27017/gameserver?authSource=admin</value>
88+
public string MongoDbDatabaseUrl { get; set; } = "mongodb://127.0.0.1:27017/gameserver?authSource=admin";
7089

7190
/// <summary>
7291
/// mongodb 创建的上限集合的最大总大小(MB)
7392
/// </summary>
74-
public int CappedMaxSizeMb { get; set; } = 50;
93+
public int MongoDbCappedMaxSizeMb { get; set; } = 50;
7594

7695
/// <summary>
7796
/// mongodb 创建的上限集合的最大文档数。
7897
/// </summary>
79-
public int CappedMaxDocuments { get; set; } = 50000;
98+
public int MongoDbCappedMaxDocuments { get; set; } = 50000;
8099

81100
/// <summary>
82101
/// 日志存储路径,为 应用程序运行目录下的子目录/logs。
@@ -174,7 +193,6 @@ public LogOptions(string logPathName = "logs")
174193
/// </remarks>
175194
public int? RetainedFileCountLimit { get; set; } = 31;
176195

177-
178196
/// <summary>
179197
/// 控制台日志输出格式模板,默认格式为 "[时:分:秒 级别][标签名]消息内容"。
180198
/// </summary>

0 commit comments

Comments
 (0)