evershade/Assets/Scripts/Utils/GameLogger.cs

59 lines
2.1 KiB
C#

using System;
using System.IO;
using System.Runtime.CompilerServices;
using UnityEngine;
namespace Utils
{
public static class GameLogger
{
private static readonly string _logFilePath;
static GameLogger()
{
_logFilePath = Path.Combine(Application.persistentDataPath, "game_log.txt");
}
public static void Log(string message, LogType type = LogType.Log,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
var className = Path.GetFileNameWithoutExtension(sourceFilePath);
var logMessage =
$"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{type}] [{className}.{memberName}:{sourceLineNumber}] {message}";
Debug.unityLogger.Log(type, logMessage);
try
{
File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
}
catch (Exception e)
{
Debug.LogError($"Failed to write to log file: {e.Message}");
}
}
public static void LogInfo(string message, [CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Log(message, LogType.Log, memberName, sourceFilePath, sourceLineNumber);
}
public static void LogWarning(string message, [CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Log(message, LogType.Warning, memberName, sourceFilePath, sourceLineNumber);
}
public static void LogError(string message, [CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Log(message, LogType.Error, memberName, sourceFilePath, sourceLineNumber);
}
}
}