Net.Like.Xue.Tokyo/Assets/BITKit/Unity/Scripts/LoggerForUnity.cs

76 lines
2.4 KiB
C#
Raw Normal View History

2024-11-03 16:42:23 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using UnityEngine;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace BITKit
{
2024-12-28 23:19:55 +08:00
public abstract class UnityLogger:ILogger
2024-11-03 16:42:23 +08:00
{
2024-12-28 23:19:55 +08:00
[HideInCallstack]
2024-11-03 16:42:23 +08:00
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
switch (logLevel)
{
case LogLevel.Critical:
case LogLevel.Error:
if (exception is not null)
{
Debug.LogException(exception);
}
else
{
Debug.LogError($"{CurrentScope}:{state.ToString()}");
}
break;
default:
Debug.Log($"{CurrentScope}:{state.ToString()}");
break;
}
}
public bool IsEnabled(LogLevel logLevel) => true;
private string CurrentScope { get; set; }
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
CurrentScope = typeof(TState).Name;
return null;
}
}
2024-12-28 23:19:55 +08:00
public sealed class UnityLogger<T>:ILogger<T>
2024-11-03 16:42:23 +08:00
{
2024-12-28 23:19:55 +08:00
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
2024-11-03 16:42:23 +08:00
{
2024-12-28 23:19:55 +08:00
switch (logLevel)
{
case LogLevel.Critical:
case LogLevel.Error:
if (exception is not null)
{
Debug.LogException(exception);
}
else
{
Debug.LogError($"{typeof(T).Name}:{state.ToString()}");
}
break;
default:
Debug.Log($"<color=cyan>{typeof(T).Name}</color>:{state.ToString()}");
break;
}
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
2024-11-03 16:42:23 +08:00
}
2024-12-28 23:19:55 +08:00
public IDisposable BeginScope<TState>(TState state) where TState : notnull
2024-11-03 16:42:23 +08:00
{
2024-12-28 23:19:55 +08:00
return null;
2024-11-03 16:42:23 +08:00
}
}
}