[TOC] 上個月換工作,新項目又要重新搭建基礎框架,把日誌實現部分單獨記錄下來方便以後參考。 # 自定義日誌類 代碼大部分使用ChatGPT生成,人工進行了測試和優化,主要特點: * 線程安全,日誌非同步寫入文件不影響業務邏輯 * 支持過期文件自動清理,也可自定義清理邏輯 * 緩存隊列有記憶體上限防呆 ...
目錄
上個月換工作,新項目又要重新搭建基礎框架,把日誌實現部分單獨記錄下來方便以後參考。
自定義日誌類
代碼大部分使用ChatGPT生成,人工進行了測試和優化,主要特點:
- 線程安全,日誌非同步寫入文件不影響業務邏輯
- 支持過期文件自動清理,也可自定義清理邏輯
- 緩存隊列有記憶體上限防呆,防止異常情況下記憶體爆滿
- 提供預設的靜態日誌記錄器,也支持自定義多個日誌記錄器
- 通過委托方法支持日誌文件名、日誌記錄格式的自定義,更加自由
使用方法:
//正常寫入日誌
LogManager.Info("This is an info message: {0}", "TestInfo");
LogManager.Debug("This is a debug message: {0}", "TestDebug");
LogManager.Warn("This is an warning message: {0}", "TestInfo");
LogManager.Error("This is a error message: {0}", "TestDebug");
//自定義寫入日誌,一般情況下使用枚舉定義日誌記錄器的名稱
var logger = LogManager.GetLogger("測試日誌");
logger.Info("This is an info message: {0}", "TestInfo");
logger.Debug("This is a debug message: {0}", "TestDebug");
logger.Warn("This is an warning message: {0}", "TestInfo");
logger.Error("This is a error message: {0}", "TestDebug");
// 在程式退出前關閉所有日誌記錄器,預設超時時間是3秒
LogManager.Close(5);
//調試時偶爾使用
if (LogManager.LastException != null)
{
Console.WriteLine("日誌異常:" + LogManager.LastException);
}
配置方法(一般情況下使用預設配置即可):
//自定義日誌保存路徑,預設保存到程式啟動目錄下的Log文件夾
LogManager.CustomLogPath = () => AppDomain.CurrentDomain.BaseDirectory + "\\CustomLogs";
//自定義日誌文件名稱,預設文件名為 DateTime.Now.ToString("yyyy-MM-dd") + ".log"
LogManager.CustomLogFileName = () => "MyLog_" + DateTime.Now.ToString("yyyyMMdd") + ".log";
//日誌保存天數,預設30天
LogManager.SaveDays = 10;
//日誌記錄的格式,預設為 $"[{Time:yyyy-MM-dd HH:mm:ss ffff}] [{Level.ToString().ToUpper()}] [{ThreadId}] {Message}"
LogManager.LogFormatter = (item) =>
{
//可以在這裡做日誌等級篩選,如果返回string.Empty這該條日誌不會記錄到文件
return $"{item.Time:yyyy/MM/dd HH:mm:ss.fff} | {item.Level} | T{item.ThreadId:0000} | {item.Message}";
};
//日誌回調,可用於界面實時顯示日誌或日誌保存其它存儲介質
LogManager.OnWriteLog = (item) => Console.WriteLine("An event was logged: " + item.ToString());
日誌類完整代碼:
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// 日誌組件,內部維護了一個靜態日誌記錄類
/// </summary>
public static class LogManager
{
/// <summary>
/// 日誌等級
/// </summary>
public enum LogLevel
{ Debug, Info, Warn, Error, Fatal }
/// <summary>
/// 日誌數據
/// </summary>
public class LogItem
{
public LogItem(LogLevel level, string message)
{
Level = level;
Message = message;
Time = DateTime.Now;
ThreadId = Thread.CurrentThread.ManagedThreadId;
}
public DateTime Time { get; private set; }
public LogLevel Level { get; private set; }
public int ThreadId { get; private set; }
public string Message { get; private set; }
public override string ToString()
{
return $"[{Time:yyyy-MM-dd HH:mm:ss ffff}] [{Level.ToString().ToUpper()}] [{ThreadId}] {Message}";
}
}
/// <summary>
/// 線程安全非同步日誌基礎類,預設緩存10000條日誌,超出時日誌會阻塞
/// </summary>
public class Logger
{
/// <summary>
/// 日誌文件存儲路徑的委托
/// </summary>
public Func<string> CustomLogPath { get; set; }
/// <summary>
/// 日誌文件名的委托,文件擴展名必須是log,否則會影響日誌文件的自動清理(可以自定義清理的方法)
/// </summary>
public Func<string> CustomLogFileName { get; set; }
/// <summary>
/// 日誌文件保存時間
/// </summary>
public int SaveDays { get; set; } = 30;
/// <summary>
/// 日誌格式化委托實例
/// </summary>
public Func<LogItem, string> LogFormatter { get; set; }
/// <summary>
/// 寫日誌事件
/// </summary>
public Action<LogItem> OnWriteLog { get; set; }
/// <summary>
/// 日誌清理委托實例,傳入日誌保存時間
/// </summary>
public Action<int> LogCleanup { get; set; }
/// <summary>
/// 最後一次異常(僅調試時用,不用於正常業務流程)
/// </summary>
public Exception LastException { get; set; }
// 線程安全的日誌隊列
private BlockingCollection<string> logQueue = new BlockingCollection<string>(10000);
// 標識是否允許寫入新日誌
private bool allowNewLogs = true;
public Logger()
{
Task.Factory.StartNew(WriteToFile, TaskCreationOptions.LongRunning);
}
// 添加日誌至隊列方法
public void EnqueueLog(LogLevel level, string message)
{
if (!allowNewLogs) return;
LogItem item = new LogItem(level, message);
string logMessage;
if (LogFormatter != null)
{
logMessage = LogFormatter(item);
}
else
{
logMessage = item.ToString();
}
if (!string.IsNullOrWhiteSpace(logMessage))
{
logQueue.Add(logMessage);
}
OnWriteLog?.Invoke(item);
}
// 迴圈寫入寫日誌到文件
private void WriteToFile()
{
string logPath = CustomLogPath?.Invoke() ?? AppDomain.CurrentDomain.BaseDirectory + "\\Log";
DirectoryInfo logDir = Directory.CreateDirectory(logPath);
while (true)
{
try
{
if (!allowNewLogs && logQueue.Count == 0) break;
string logMessage;
if (logQueue.TryTake(out logMessage, TimeSpan.FromSeconds(1)))
{
string fileName = CustomLogFileName?.Invoke() ?? DateTime.Now.ToString("yyyy-MM-dd") + ".log";
if (!File.Exists(fileName))
{
// 清理舊日誌
if (LogCleanup != null)
{
LogCleanup(SaveDays);
}
else
{
CleanUpOldLogs(logDir, SaveDays);
}
}
File.AppendAllText(Path.Combine(logPath, fileName), logMessage + Environment.NewLine);
}
}
catch (Exception ex)
{
LastException = ex;
Console.WriteLine("Logger Exception - WriteToFile : " + ex.Message);
}
}
}
/// <summary>
/// 關閉日誌器方法,指定超時時間(秒)
/// </summary>
/// <param name="waitTimeInSeconds">等待時間</param>
public void Close(int waitTimeInSeconds = 3)
{
allowNewLogs = false;
CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(waitTimeInSeconds));
try
{
CancellationToken token = cts.Token;
// 標識隊列已完成添加
logQueue.CompleteAdding();
while (!token.IsCancellationRequested)
{
if (logQueue.Count == 0) break; // 提前退出
// 短暫休眠以降低 CPU 占用
Task.Delay(100, token).Wait();
}
}
catch (OperationCanceledException)
{
// 等待時間到,退出方法,不傳播異常
}
catch (Exception ex)
{
Console.WriteLine("An unexpected exception occurred in the Close method: " + ex.Message);
}
}
/// <summary>
/// 預設的清理過期日誌的方法
/// </summary>
/// <param name="logDir"></param>
/// <param name="saveDays"></param>
public static void CleanUpOldLogs(DirectoryInfo logDir, int saveDays)
{
FileInfo[] logFiles = logDir.GetFiles("*.log");
foreach (FileInfo file in logFiles)
{
if (DateTime.Now - file.CreationTime >= TimeSpan.FromDays(saveDays))
{
file.Delete();
}
}
}
/// <summary>
/// 記錄Info等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public void Info(string message, params object[] args)
{
EnqueueLog(LogLevel.Info, string.Format(message, args));
}
/// <summary>
/// 記錄Debug等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public void Debug(string message, params object[] args)
{
EnqueueLog(LogLevel.Debug, string.Format(message, args));
}
/// <summary>
/// 記錄Warning等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public void Warn(string message, params object[] args)
{
EnqueueLog(LogLevel.Warn, string.Format(message, args));
}
/// <summary>
/// 記錄Error等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public void Error(string message, params object[] args)
{
EnqueueLog(LogLevel.Error, string.Format(message, args));
}
/// <summary>
/// 記錄Fatal等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public void Fatal(string message, params object[] args)
{
EnqueueLog(LogLevel.Fatal, string.Format(message, args));
}
}
private static Logger logger = new Logger();
private static ConcurrentDictionary<string, Logger> logDic = new ConcurrentDictionary<string, Logger>();
/// <summary>
/// 獲取自定義的日誌記錄類
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Logger GetLogger(string name)
{
return logDic.GetOrAdd(name, key =>
{
var log = new Logger();
log.CustomLogPath = () => AppDomain.CurrentDomain.BaseDirectory + "\\Log\\" + key;
return log;
});
}
/// <summary>
/// 日誌文件存儲路徑的委托
/// </summary>
public static Func<string> CustomLogPath
{
get => logger.CustomLogPath;
set => logger.CustomLogPath = value;
}
/// <summary>
/// 日誌文件名的委托,文件擴展名必須是log,否則會影響日誌文件的自動清理(可以自定義清理的方法)
/// </summary>
public static Func<string> CustomLogFileName
{
get => logger.CustomLogFileName;
set => logger.CustomLogFileName = value;
}
/// <summary>
/// 日誌文件保存時間
/// </summary>
public static int SaveDays
{
get => logger.SaveDays;
set => logger.SaveDays = value;
}
/// <summary>
/// 日誌格式化委托實例
/// </summary>
public static Func<LogItem, string> LogFormatter
{
get => logger.LogFormatter;
set => logger.LogFormatter = value;
}
/// <summary>
/// 寫日誌事件
/// </summary>
public static Action<LogItem> OnWriteLog
{
get => logger.OnWriteLog;
set => logger.OnWriteLog = value;
}
/// <summary>
/// 日誌清理委托實例,傳入日誌保存時間
/// </summary>
public static Action<int> LogCleanup
{
get => logger.LogCleanup;
set => logger.LogCleanup = value;
}
/// <summary>
/// 最後一次異常(僅調試時用,不用於正常業務流程)
/// </summary>
public static Exception LastException
{
get => logger.LastException;
set => logger.LastException = value;
}
/// <summary>
/// 關閉所有日誌記錄器,指定超時時間(秒),日誌記錄器較多時可能耗時較久
/// </summary>
/// <param name="waitTimeInSeconds">等待時間</param>
public static void Close(int waitTimeInSeconds = 3)
{
logger.Close(waitTimeInSeconds);
foreach (var item in logDic.Values)
{
item.Close(waitTimeInSeconds);
}
}
/// <summary>
/// 記錄Info等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Info(string message, params object[] args)
{
logger.EnqueueLog(LogLevel.Info, string.Format(message, args));
}
/// <summary>
/// 記錄Debug等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Debug(string message, params object[] args)
{
logger.EnqueueLog(LogLevel.Debug, string.Format(message, args));
}
/// <summary>
/// 記錄Warning等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Warn(string message, params object[] args)
{
logger.EnqueueLog(LogLevel.Warn, string.Format(message, args));
}
/// <summary>
/// 記錄Error等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Error(string message, params object[] args)
{
logger.EnqueueLog(LogLevel.Error, string.Format(message, args));
}
/// <summary>
/// 記錄Fatal等級日誌
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Fatal(string message, params object[] args)
{
logger.EnqueueLog(LogLevel.Fatal, string.Format(message, args));
}
}
NLog版本的日誌類
有時候因為公司或團隊原因必須使用NLog日誌庫,這裡提供一個簡單的NLog版本的日誌類,日誌規則基本和上面的自定義類一致。
使用方法如下:
//可以指定日誌保存天數,預設30天
Logger.Init();
//訂閱寫日誌事件
Logger.GetLogEventTarget().LogReceived += Logger_LogWrite;
//記錄日誌
Logger.Info("軟體啟動");
NLog版本的日誌類只是對NLog的常用配置做一個封裝,如果需要自定義日誌格式或存儲位置需要自己改封裝部分的代碼。
完整代碼:
using NLog;
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System;
/// <summary>
/// 全局日誌類
/// </summary>
public static class Logger
{
#region 私有欄位方法
private static ILogger logger;
private static void ConfigureNLog(int saveDays = 30)
{
var config = new LoggingConfiguration();
// 創建目標(這裡是 FileTarget 用於寫入文件)
var fileTarget = new FileTarget("logfile")
{
FileName = "${basedir}/Log/${date:format=yyyy-MM-dd}.log",
Layout = "${longdate} ${uppercase:${level}} ${message} ${exception:format=tostring}",
ArchiveOldFileOnStartup = true,
ArchiveEvery = FileArchivePeriod.Day,
MaxArchiveFiles = saveDays,
};
// 使用 AsyncTargetWrapper 實現非同步寫日誌
var asyncFileTarget = new AsyncTargetWrapper(fileTarget, 1000, AsyncTargetWrapperOverflowAction.Discard);
// 設置規則
var rule = new LoggingRule("*", LogLevel.Debug, asyncFileTarget);
config.LoggingRules.Add(rule);
// 創建自定義Target
var logEventTarget = new LogEventTarget
{
Name = "logEvent",
MessageLayout = "${longdate} ${uppercase:${level}} ${message} ${exception:format=tostring}"
};
config.AddTarget(logEventTarget);
// 添加規則
var eventRule = new LoggingRule("*", LogLevel.Debug, logEventTarget);
config.LoggingRules.Add(eventRule);
// 應用配置
LogManager.Configuration = config;
}
#endregion 私有欄位方法
#region 公共欄位方法
/// <summary>
/// 初始化日誌,程式初始化時啟動
/// </summary>
/// <param name="saveDays"></param>
public static void Init(int saveDays = 30)
{
ConfigureNLog(saveDays);
logger = LogManager.GetCurrentClassLogger();
}
/// <summary>
/// 獲取日誌回調Target
/// </summary>
/// <returns></returns>
public static LogEventTarget GetLogEventTarget()
{
return (LogEventTarget)LogManager.Configuration.FindTargetByName("logEvent");
}
/// <summary>
/// 關閉日誌,程式退出時調用
/// </summary>
public static void Close()
{
LogManager.Flush();
LogManager.Shutdown();
}
#endregion 公共欄位方法
#region 日誌介面
/// <summary>
/// 跟蹤日誌級別:最詳細的級別,用於開發,很少用於生產。
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Trace(string message, params object[] args)
{
logger.Trace(message, args);
}
/// <summary>
/// 調試日誌級別:根據感興趣的內部事件調試應用程式行為。
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Debug(string message, params object[] args)
{
logger.Debug(message, args);
}
/// <summary>
/// 信息日誌級別:突出顯示進度或應用程式生存期事件的信息。
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Info(string message, params object[] args)
{
logger.Info(message, args);
}
/// <summary>
/// 警告日誌級別:關於可以恢復的驗證問題或臨時故障的警告。
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Warn(string message, params object[] args)
{
logger.Warn(message, args);
}
/// <summary>
/// 錯誤日誌級別:功能失敗或捕捉到System.Exception的錯誤。
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Error(string message, params object?[] args)
{
logger.Error(message, args);
}
/// <summary>
/// 致命日誌級別:最關鍵級別,應用程式即將中止。
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Fatal(string message, params object[] args)
{
logger.Fatal(message, args);
}
#endregion 日誌介面
}
/// <summary>
/// 日誌事件目標
/// </summary>
public class LogEventTarget : Target
{
/// <summary>
/// 日誌事件
/// </summary>
public event EventHandler<string> LogReceived;
/// <summary>
/// 日誌佈局
/// </summary>
[RequiredParameter]
public Layout MessageLayout { get; set; }
protected override void Write(LogEventInfo logEvent)
{
string logMessage = MessageLayout.Render(logEvent);
OnLogReceived(logMessage);
}
private void OnLogReceived(string message)
{
LogReceived?.Invoke(this, message);
}
}