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.
65 lines
2.0 KiB
65 lines
2.0 KiB
1 week ago
|
using Microsoft.Extensions.Configuration;
|
||
|
using Serilog;
|
||
|
using System;
|
||
|
using System.IO;
|
||
|
|
||
|
namespace CoreAgent.Infrastructure.Logging
|
||
|
{
|
||
|
public static class ApplicationLogger
|
||
|
{
|
||
|
private static readonly object _lock = new object();
|
||
|
private static bool _isInitialized;
|
||
|
|
||
|
public static void Initialize(IConfiguration configuration)
|
||
|
{
|
||
|
ArgumentNullException.ThrowIfNull(configuration, nameof(configuration));
|
||
|
|
||
|
if (_isInitialized)
|
||
|
{
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
lock (_lock)
|
||
|
{
|
||
|
if (_isInitialized)
|
||
|
{
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
try
|
||
|
{
|
||
|
// 确保日志目录存在
|
||
|
var logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
|
||
|
Directory.CreateDirectory(logDirectory);
|
||
|
|
||
|
// 从配置文件初始化
|
||
|
Log.Logger = new LoggerConfiguration()
|
||
|
.ReadFrom.Configuration(configuration)
|
||
|
.CreateLogger();
|
||
|
|
||
|
_isInitialized = true;
|
||
|
Log.Information("Logger initialized successfully");
|
||
|
}
|
||
|
catch (Exception ex)
|
||
|
{
|
||
|
// 如果初始化失败,创建一个基本的控制台日志记录器
|
||
|
Log.Logger = new LoggerConfiguration()
|
||
|
.MinimumLevel.Debug()
|
||
|
.WriteTo.Console()
|
||
|
.CreateLogger();
|
||
|
|
||
|
_isInitialized = true;
|
||
|
Log.Error(ex, "Failed to initialize logger with full configuration");
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static void EnsureInitialized()
|
||
|
{
|
||
|
if (!_isInitialized)
|
||
|
{
|
||
|
throw new InvalidOperationException("Logger has not been initialized. Call Initialize() first.");
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|