com.alicizax.unity.tuyoogam.../Editor/AssetBundleBuilder/BuildSystem/BuildLogger.cs

101 lines
2.9 KiB
C#
Raw Normal View History

2025-01-09 11:31:04 +08:00
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
2025-05-13 10:40:30 +08:00
using System.Text;
2025-01-09 11:31:04 +08:00
namespace YooAsset.Editor
{
internal static class BuildLogger
{
2025-05-13 10:40:30 +08:00
private const int MAX_LOG_BUFFER_SIZE = 1024 * 1024 * 2; //2MB
2025-01-09 11:31:04 +08:00
private static bool _enableLog = true;
2025-05-13 10:40:30 +08:00
private static string _logFilePath;
private static readonly object _lockObj = new object();
private static readonly StringBuilder _logBuilder = new StringBuilder(MAX_LOG_BUFFER_SIZE);
2025-01-09 11:31:04 +08:00
2025-05-13 10:40:30 +08:00
/// <summary>
/// 初始化日志系统
/// </summary>
public static void InitLogger(bool enableLog, string logFilePath)
2025-01-09 11:31:04 +08:00
{
_enableLog = enableLog;
2025-05-13 10:40:30 +08:00
_logFilePath = logFilePath;
_logBuilder.Clear();
if (_enableLog)
{
if (string.IsNullOrEmpty(_logFilePath))
throw new Exception("Log file path is null or empty !");
Debug.Log($"Logger initialized at {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
}
}
/// <summary>
/// 关闭日志系统
/// </summary>
public static void Shuntdown()
{
if (_enableLog)
{
lock (_lockObj)
{
try
{
if (File.Exists(_logFilePath))
File.Delete(_logFilePath);
FileUtility.CreateFileDirectory(_logFilePath);
File.WriteAllText(_logFilePath, _logBuilder.ToString(), Encoding.UTF8);
_logBuilder.Clear();
}
catch (Exception ex)
{
Debug.LogError($"Failed to write log file: {ex.Message}");
}
}
}
2025-01-09 11:31:04 +08:00
}
public static void Log(string message)
{
if (_enableLog)
{
2025-05-13 10:40:30 +08:00
WriteLog("INFO", message);
2025-01-09 11:31:04 +08:00
Debug.Log(message);
}
}
public static void Warning(string message)
{
2025-05-13 10:40:30 +08:00
if (_enableLog)
{
WriteLog("WARN", message);
Debug.LogWarning(message);
}
2025-01-09 11:31:04 +08:00
}
public static void Error(string message)
{
2025-05-13 10:40:30 +08:00
if (_enableLog)
{
WriteLog("ERROR", message);
Debug.LogError(message);
}
2025-01-09 11:31:04 +08:00
}
public static string GetErrorMessage(ErrorCode code, string message)
{
return $"[ErrorCode{(int)code}] {message}";
}
2025-05-13 10:40:30 +08:00
private static void WriteLog(string level, string message)
{
lock (_lockObj)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}";
_logBuilder.AppendLine(logEntry);
}
}
2025-01-09 11:31:04 +08:00
}
}