This commit is contained in:
2026-06-15 18:18:16 +08:00
parent 97c9fba14e
commit 2b9f134e5f
4164 changed files with 386922 additions and 79 deletions

View File

@@ -0,0 +1,77 @@
using System;
using System.IO;
using Best.HTTP.Shared.PlatformSupport.FileSystem;
using Best.HTTP.Shared.PlatformSupport.Memory;
namespace Best.HTTP.Shared.Logger
{
/// <summary>
/// Provides an implementation of <see cref="ILogOutput"/> that writes log messages to a file.
/// </summary>
public sealed class FileOutput : ILogOutput
{
/// <summary>
/// Gets a value indicating whether this log output accepts color codes. Always returns <c>false</c>.
/// </summary>
public bool AcceptColor { get; } = false;
private Stream fileStream;
/// <summary>
/// Initializes a new instance of the FileOutput class with the specified file name.
/// </summary>
/// <param name="fileName">The name of the file to write log messages to.</param>
public FileOutput(string fileName)
{
// Create a buffered stream for writing log messages to the specified file.
this.fileStream = new BufferedStream(HTTPManager.IOService.CreateFileStream(fileName, FileStreamModes.Create), 512 * 1024);
}
/// <summary>
/// Writes a log message to the file.
/// </summary>
/// <param name="level">The log level of the message.</param>
/// <param name="logEntry">The log message to write.</param>
public void Write(Loglevels level, string logEntry)
{
if (this.fileStream != null && !string.IsNullOrEmpty(logEntry))
{
int count = System.Text.Encoding.UTF8.GetByteCount(logEntry) + 2;
var buffer = BufferPool.Get(count, true);
try
{
System.Text.Encoding.UTF8.GetBytes(logEntry, 0, logEntry.Length, buffer, 0);
buffer[count - 2] = (byte)'\r';
buffer[count - 1] = (byte)'\n';
this.fileStream.Write(buffer, 0, count);
}
finally
{
BufferPool.Release(buffer);
}
}
}
/// <summary>
/// Flushes any buffered log messages to the file.
/// </summary>
public void Flush() => this.fileStream?.Flush();
/// <summary>
/// Releases any resources used by the FileOutput instance.
/// </summary>
public void Dispose()
{
if (this.fileStream != null)
{
this.fileStream.Close();
this.fileStream = null;
}
GC.SuppressFinalize(this);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2ad11187a50e381439c128d7d791eb3a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,172 @@
using System;
namespace Best.HTTP.Shared.Logger
{
[HideFromDocumentation]
public sealed class HideFromDocumentation : Attribute
{
}
/// <summary>
/// Available logging levels.
/// </summary>
public enum Loglevels : int
{
/// <summary>
/// All message will be logged.
/// </summary>
All,
/// <summary>
/// Only Informations and above will be logged.
/// </summary>
Information,
/// <summary>
/// Only Warnings and above will be logged.
/// </summary>
Warning,
/// <summary>
/// Only Errors and above will be logged.
/// </summary>
Error,
/// <summary>
/// Only Exceptions will be logged.
/// </summary>
Exception,
/// <summary>
/// No logging will occur.
/// </summary>
None
}
/// <summary>
/// Represents an output target for log messages.
/// </summary>
/// <remarks>
/// <para>
/// This interface defines methods for writing log messages to an output target.
/// Implementations of this interface are used to configure where log messages
/// should be written.
/// </para>
/// <para>
/// Two of its out-of-the-box implementations are
/// <list type="bullet">
/// <item><description><see cref="UnityOutput">UnityOutput</see></description></item>
/// <item><description><see cref="FileOutput">FileOutput</see></description></item>
/// </list>
/// </para>
/// </remarks>
public interface ILogOutput : IDisposable
{
/// <summary>
/// Gets a value indicating whether the log output supports colored text.
/// </summary>
bool AcceptColor { get; }
/// <summary>
/// Writes a log entry to the output.
/// </summary>
/// <param name="level">The logging level of the entry.</param>
/// <param name="logEntry">The log message to write.</param>
void Write(Loglevels level, string logEntry);
/// <summary>
/// Flushes any buffered log entries to the output.
/// </summary>
void Flush();
}
/// <summary>
/// Represents a filter for further sort out what log entries to include in the final log output.
/// </summary>
public interface IFilter
{
/// <summary>
/// Return <c>true</c> if the division must be included in the output.
/// </summary>
bool Include(string division);
}
/// <summary>
/// Represents a logger for recording log messages.
/// </summary>
public interface ILogger
{
/// <summary>
/// Gets or sets the minimum severity level for logging.
/// </summary>
Loglevels Level { get; set; }
/// <summary>
/// Gets or sets the output target for log messages.
/// </summary>
/// <value>
/// The <see cref="ILogOutput"/> instance used to write log messages.
/// </value>
ILogOutput Output { get; set; }
/// <summary>
/// Gets or sets an output filter to decide what messages are included or not.
/// </summary>
/// <value>The <see cref="IFilter"/> instance used for filtering.</value>
IFilter Filter { get; set; }
/// <summary>
/// Property indicating whether the logger's internal queue is empty or not.
/// </summary>
bool IsEmpty { get; }
/// <summary>
/// Gets a value indicating whether diagnostic logging is enabled.
/// </summary>
/// <remarks>
/// Diagnostic logging is enabled when <see cref="Level"/> is set to <see cref="Loglevels.All"/>.
/// </remarks>
bool IsDiagnostic { get; }
/// <summary>
/// Logs a message with <see cref="Loglevels.All"/> level.
/// </summary>
/// <param name="division">The division or category of the log message.</param>
/// <param name="msg">The verbose log message.</param>
/// <param name="context">The optional <see cref="LoggingContext"/> for additional context.</param>
void Verbose(string division, string msg, LoggingContext context = null);
/// <summary>
/// Logs a message with <see cref="Loglevels.Information"/> level.
/// </summary>
/// <param name="division">The division or category of the log message.</param>
/// <param name="msg">The verbose log message.</param>
/// <param name="context">The optional <see cref="LoggingContext"/> for additional context.</param>
void Information(string division, string msg, LoggingContext context = null);
/// <summary>
/// Logs a message with <see cref="Loglevels.Warning"/> level.
/// </summary>
/// <param name="division">The division or category of the log message.</param>
/// <param name="msg">The verbose log message.</param>
/// <param name="context">The optional <see cref="LoggingContext"/> for additional context.</param>
void Warning(string division, string msg, LoggingContext context = null);
/// <summary>
/// Logs a message with <see cref="Loglevels.Error"/> level.
/// </summary>
/// <param name="division">The division or category of the log message.</param>
/// <param name="msg">The verbose log message.</param>
/// <param name="context">The optional <see cref="LoggingContext"/> for additional context.</param>
void Error(string division, string msg, LoggingContext context = null);
/// <summary>
/// Logs a message with <see cref="Loglevels.Exception"/> level.
/// </summary>
/// <param name="division">The division or category of the log message.</param>
/// <param name="msg">The verbose log message.</param>
/// <param name="context">The optional <see cref="LoggingContext"/> for additional context.</param>
void Exception(string division, string msg, Exception ex, LoggingContext context = null);
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 81c5c1596e18e4d46beef29fa682d58d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,205 @@
using System.Collections.Generic;
using System.Linq;
namespace Best.HTTP.Shared.Logger
{
/// <summary>
/// Represents a logging context for categorizing and organizing log messages.
/// </summary>
/// <remarks>
/// The LoggingContext class is used to provide additional context information
/// to log messages, allowing for better categorization and organization of log output. It can be
/// associated with specific objects or situations to enrich log entries with context-specific data.
/// </remarks>
public sealed class LoggingContext
{
/// <summary>
/// Gets the unique hash value of this logging context.
/// </summary>
public string Hash { get; private set; }
public enum LoggingContextFieldType
{
Long,
Bool,
String,
AnotherContext
}
public struct LoggingContextField
{
public string key;
public long longValue;
public bool boolValue;
public string stringValue;
public LoggingContext loggingContextValue;
public LoggingContextFieldType fieldType;
public override string ToString()
{
object value = this.fieldType switch
{
LoggingContextFieldType.Bool => this.boolValue,
LoggingContextFieldType.Long => this.longValue,
LoggingContextFieldType.String => this.stringValue,
_ => this.loggingContextValue
};
return $"[{this.key} => '{value}']";
}
}
public List<LoggingContextField> fields = new List<LoggingContextField>(8);
/// <summary>
/// Initializes a new instance of the LoggingContext class associated with the specified object.
/// </summary>
/// <param name="boundto">The object to associate the context with.</param>
public LoggingContext(object boundto)
{
var name = boundto.GetType().Name;
Add("TypeName", name);
UnityEngine.Hash128 hash = new UnityEngine.Hash128();
hash.Append(name);
hash.Append(boundto.GetHashCode());
hash.Append(this.GetHashCode());
this.Hash = hash.ToString();
Add("Hash", this.Hash);
}
/// <summary>
/// Adds a <c>long</c> value to the logging context.
/// </summary>
/// <param name="key">The key to associate with the value.</param>
/// <param name="value">The <c>long</c> value to add.</param>
public void Add(string key, long value) => Add(new LoggingContextField { fieldType = LoggingContextFieldType.Long, key = key, longValue = value });
/// <summary>
/// Adds a <c>bool</c> value to the logging context.
/// </summary>
/// <param name="key">The key to associate with the value.</param>
/// <param name="value">The <c>bool</c> value to add.</param>
public void Add(string key, bool value) => Add(new LoggingContextField { fieldType = LoggingContextFieldType.Bool, key = key, boolValue = value });
/// <summary>
/// Adds a <c>string</c> value to the logging context.
/// </summary>
/// <param name="key">The key to associate with the value.</param>
/// <param name="value">The <c>string</c> value to add.</param>
public void Add(string key, string value) => Add(new LoggingContextField { fieldType = LoggingContextFieldType.String, key = key, stringValue = value });
/// <summary>
/// Adds a <c>LoggingContext</c> value to the logging context.
/// </summary>
/// <param name="key">The key to associate with the value.</param>
/// <param name="value">The <c>LoggingContext</c> value to add.</param>
public void Add(string key, LoggingContext value) => Add(new LoggingContextField { fieldType = LoggingContextFieldType.AnotherContext, key = key, loggingContextValue = value });
private void Add(LoggingContextField field)
{
Remove(field.key);
this.fields.Add(field);
}
/// <summary>
/// Gets the <c>string</c> field with the specified name from the logging context.
/// </summary>
/// <param name="fieldName">The name of the <c>string</c> field to retrieve.</param>
/// <returns>The value of the <c>string</c> field or <c>null</c> if not found.</returns>
public string GetStringField(string fieldName) => this.fields.FirstOrDefault(f => f.key == fieldName).stringValue;
/// <summary>
/// Removes a field from the logging context by its key.
/// </summary>
/// <param name="key">The key of the field to remove.</param>
public void Remove(string key)
{
for (int i = 0; i < this.fields.Count; i++)
{
var field = this.fields[i];
if (field.key.Equals(key, System.StringComparison.Ordinal))
this.fields.RemoveAt(i--);
}
}
/// <summary>
/// Converts the logging context and its associated fields to a JSON string representation.
/// </summary>
/// <param name="sb">A <see cref="System.Text.StringBuilder"/> instance to which the JSON string is appended.</param>
/// <remarks>
/// This method serializes the logging context and its associated fields into a JSON format
/// for structured logging purposes. The resulting JSON string represents the context and its fields, making it
/// suitable for inclusion in log entries for better analysis and debugging.
/// </remarks>
public void ToJson(System.Text.StringBuilder sb)
{
if (this.fields == null || this.fields.Count == 0)
{
sb.Append("null");
return;
}
sb.Append("{");
for (int i = 0; i < this.fields.Count; ++i)
{
var field = this.fields[i];
if (field.fieldType != LoggingContextFieldType.AnotherContext)
{
if (i > 0)
sb.Append(", ");
sb.AppendFormat("\"{0}\": ", field.key);
}
switch (field.fieldType)
{
case LoggingContextFieldType.Long:
sb.Append(field.longValue);
break;
case LoggingContextFieldType.Bool:
sb.Append(field.boolValue ? "true" : "false");
break;
case LoggingContextFieldType.String:
sb.AppendFormat("\"{0}\"", Escape(field.stringValue));
break;
}
}
sb.Append("}");
for (int i = 0; i < this.fields.Count; ++i)
{
var field = this.fields[i];
if (field.loggingContextValue == null)
continue;
switch (field.fieldType)
{
case LoggingContextFieldType.AnotherContext:
sb.Append(", ");
field.loggingContextValue.ToJson(sb);
break;
}
}
}
public static string Escape(string original)
{
return Best.HTTP.Shared.PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(Best.HTTP.Shared.PlatformSupport.Text.StringBuilderPool.Get(1)
.Append(original)
.Replace("\\", "\\\\")
.Replace("\"", "\\\"")
.Replace("/", "\\/")
.Replace("\b", "\\b")
.Replace("\f", "\\f")
.Replace("\n", "\\n")
.Replace("\r", "\\r")
.Replace("\t", "\\t"));
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 32f8edc3b27d9d24384f41757f618d15
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,409 @@
using System;
using System.Collections.Concurrent;
using System.Text;
using Best.HTTP.Shared.PlatformSupport.Text;
using Best.HTTP.Shared.PlatformSupport.Threading;
namespace Best.HTTP.Shared.Logger
{
/// <summary>
/// <see cref="IFilter"/> implementation to include only one division in the log output.
/// </summary>
public sealed class SingleDivisionFilter : IFilter
{
private string _division;
public SingleDivisionFilter(string division) => this._division = division;
public bool Include(string division) => this._division.Equals(division, StringComparison.Ordinal);
}
/// <summary>
/// <see cref="IFilter"/> implementation to allow filtering for multiple divisions.
/// </summary>
public sealed class MultiDivisionFilter : IFilter
{
private string[] _divisions;
public MultiDivisionFilter(string[] divisions)
{
this._divisions = divisions;
for (int i = 0; i < this._divisions.Length; ++i)
this._divisions[i] = this._divisions[i].Trim();
}
public bool Include(string division)
{
for (int i = 0; i < this._divisions.Length; ++i)
{
ref var div = ref this._divisions[i];
if (div.Equals(division, StringComparison.Ordinal))
return true;
}
return false;
}
}
public sealed class ThreadedLogger : Best.HTTP.Shared.Logger.ILogger, IDisposable
{
public Loglevels Level { get; set; }
public bool IsDiagnostic { get => this.Level == Loglevels.All; }
public ILogOutput Output { get { return this._output; }
set
{
if (this._output != value)
{
if (this._output != null)
this._output.Dispose();
this._output = value;
}
}
}
private ILogOutput _output;
public IFilter Filter { get; set; }
public bool IsEmpty
#if !UNITY_WEBGL || UNITY_EDITOR
=> this.jobs.IsEmpty;
#else
=> true;
#endif
public int InitialStringBufferCapacity = 256;
#if !UNITY_WEBGL || UNITY_EDITOR
public TimeSpan ExitThreadAfterInactivity = TimeSpan.FromMinutes(1);
public int QueuedJobs { get => this.jobs.Count; }
private ConcurrentQueue<LogJob> jobs = new ConcurrentQueue<LogJob>();
private System.Threading.AutoResetEvent newJobEvent = new System.Threading.AutoResetEvent(false);
private volatile int threadCreated;
private volatile bool isDisposed;
#endif
private StringBuilder sb = new StringBuilder(0);
public ThreadedLogger()
{
this.Level = UnityEngine.Debug.isDebugBuild ? Loglevels.Warning : Loglevels.Error;
this.Output = new UnityOutput();
}
public void Verbose(string division, string msg, LoggingContext context) {
AddJob(Loglevels.All, division, msg, null, context);
}
public void Information(string division, string msg, LoggingContext context) {
AddJob(Loglevels.Information, division, msg, null, context);
}
public void Warning(string division, string msg, LoggingContext context) {
AddJob(Loglevels.Warning, division, msg, null, context);
}
public void Error(string division, string msg, LoggingContext context) {
AddJob(Loglevels.Error, division, msg, null, context);
}
public void Exception(string division, string msg, Exception ex, LoggingContext context) {
AddJob(Loglevels.Exception, division, msg, ex, context);
}
private void AddJob(Loglevels level, string div, string msg, Exception ex, LoggingContext context)
{
if (this.Level > level)
return;
var filter = this.Filter;
if (filter != null && !filter.Include(div))
return;
sb.EnsureCapacity(InitialStringBufferCapacity);
#if !UNITY_WEBGL || UNITY_EDITOR
if (this.isDisposed)
return;
#endif
string json = null;
if (context != null)
{
var jsonBuilder = StringBuilderPool.Get(1);
context.ToJson(jsonBuilder);
json = StringBuilderPool.ReleaseAndGrab(jsonBuilder);
}
var job = new LogJob
{
level = level,
division = div,
msg = msg,
ex = ex,
time = DateTime.UtcNow,
threadId = System.Threading.Thread.CurrentThread.ManagedThreadId,
stackTrace = System.Environment.StackTrace,
context = json
};
#if !UNITY_WEBGL || UNITY_EDITOR
// Start the consumer thread before enqueuing to get up and running sooner
if (System.Threading.Interlocked.CompareExchange(ref this.threadCreated, 1, 0) == 0)
Best.HTTP.Shared.PlatformSupport.Threading.ThreadedRunner.RunLongLiving(ThreadFunc);
this.jobs.Enqueue(job);
try
{
this.newJobEvent.Set();
}
catch
{
try
{
this.Output.Write(job.level, job.ToJson(sb, this.Output.AcceptColor));
}
catch
{ }
return;
}
// newJobEvent might timed out between the previous threadCreated check and newJobEvent.Set() calls closing the thread.
// So, here we check threadCreated again and create a new thread if needed.
if (System.Threading.Interlocked.CompareExchange(ref this.threadCreated, 1, 0) == 0)
Best.HTTP.Shared.PlatformSupport.Threading.ThreadedRunner.RunLongLiving(ThreadFunc);
#else
this.Output.Write(job.level, job.ToJson(sb, this.Output.AcceptColor));
#endif
}
#if !UNITY_WEBGL || UNITY_EDITOR
private void ThreadFunc()
{
ThreadedRunner.SetThreadName("Best.HTTP.Logger");
try
{
LogJob job;
/*
LogJob job = new LogJob
{
level = Loglevels.Information,
division = "ThreadFunc",
msg = "Log thread starting!",
ex = null,
time = DateTime.UtcNow,
threadId = System.Threading.Thread.CurrentThread.ManagedThreadId,
stackTrace = null,
context1 = null,
context2 = null,
context3 = null
};
WriteJob(ref job);
*/
do
{
// Waiting for a new log-job timed out
if (!this.newJobEvent.WaitOne(this.ExitThreadAfterInactivity))
{
/*
job = new LogJob
{
level = Loglevels.Information,
division = "ThreadFunc",
msg = "Log thread quitting!",
ex = null,
time = DateTime.UtcNow,
threadId = System.Threading.Thread.CurrentThread.ManagedThreadId,
stackTrace = null,
context1 = null,
context2 = null,
context3 = null
};
WriteJob(ref job);
*/
// clear StringBuilder's inner cache and exit the thread
sb.Length = 0;
sb.Capacity = 0;
System.Threading.Interlocked.Exchange(ref this.threadCreated, 0);
return;
}
try
{
int count = 0;
while (this.jobs.TryDequeue(out job))
{
WriteJob(ref job);
if (++count >= 1000)
this.Output.Flush();
}
}
finally
{
this.Output.Flush();
}
} while (!HTTPManager.IsQuitting);
System.Threading.Interlocked.Exchange(ref this.threadCreated, 0);
// When HTTPManager.IsQuitting is true, there is still logging that will create a new thread after the last one quit
// and always writing a new entry about the exiting thread would be too much overhead.
// It would also hard to know what's the last log entry because some are generated on another thread non-deterministically.
//var lastLog = new LogJob
//{
// level = Loglevels.All,
// division = "ThreadedLogger",
// msg = "Log Processing Thread Quitting!",
// time = DateTime.UtcNow,
// threadId = System.Threading.Thread.CurrentThread.ManagedThreadId,
//};
//
//this.Output.WriteVerbose(lastLog.ToJson(sb));
}
catch
{
System.Threading.Interlocked.Exchange(ref this.threadCreated, 0);
}
}
void WriteJob(ref LogJob job)
{
try
{
this.Output.Write(job.level, job.ToJson(sb, this.Output.AcceptColor));
}
catch
{ }
}
#endif
public void Dispose()
{
#if !UNITY_WEBGL || UNITY_EDITOR
this.isDisposed = true;
if (this.newJobEvent != null)
{
this.newJobEvent.Close();
this.newJobEvent = null;
}
#endif
if (this.Output != null)
{
this.Output.Dispose();
this.Output = new UnityOutput();
}
GC.SuppressFinalize(this);
}
}
[Best.HTTP.Shared.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
public struct LogJob
{
private static string[] LevelStrings = new string[] { "Verbose", "Information", "Warning", "Error", "Exception" };
public Loglevels level;
public string division;
public string msg;
public Exception ex;
public DateTime time;
public int threadId;
public string stackTrace;
public string context;
private static string WrapInColor(string str, string color, bool acceptColor)
{
#if UNITY_EDITOR
return acceptColor ? string.Format("<b><color={1}>{0}</color></b>", str, color) : str;
#else
return str;
#endif
}
public string ToJson(StringBuilder sb, bool acceptColor)
{
sb.Length = 0;
sb.AppendFormat("{{\"tid\":{0},\"div\":\"{1}\",\"msg\":\"{2}\"",
WrapInColor(this.threadId.ToString(), "yellow", acceptColor),
WrapInColor(this.division, "yellow", acceptColor),
WrapInColor(LoggingContext.Escape(this.msg), "yellow", acceptColor));
if (ex != null)
{
sb.Append(",\"ex\": [");
Exception exception = this.ex;
while (exception != null)
{
sb.Append("{\"msg\": \"");
sb.Append(LoggingContext.Escape(exception.Message));
sb.Append("\", \"stack\": \"");
sb.Append(LoggingContext.Escape(exception.StackTrace));
sb.Append("\"}");
exception = exception.InnerException;
if (exception != null)
sb.Append(",");
}
sb.Append("]");
}
if (this.stackTrace != null)
{
sb.Append(",\"stack\":\"");
ProcessStackTrace(sb);
sb.Append("\"");
}
else
sb.Append(",\"stack\":\"\"");
if (this.context != null)
{
sb.Append(",\"ctx\": [");
sb.Append(this.context);
sb.Append("]");
}
else
sb.Append(",\"ctxs\":[]");
sb.AppendFormat(",\"t\":{0},\"ll\":\"{1}\",",
this.time.Ticks.ToString(),
LevelStrings[(int)this.level]);
sb.Append("\"bh\":1}");
return sb.ToString();
}
private void ProcessStackTrace(StringBuilder sb)
{
if (string.IsNullOrEmpty(this.stackTrace))
return;
var lines = this.stackTrace.Split('\n');
// skip top 4 lines that would show the logger.
for (int i = 3; i < lines.Length; ++i)
sb.Append(LoggingContext.Escape(lines[i].Replace("Best.HTTP.", "")));
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 780d670e1b8a6a340a1441f844142390
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,50 @@
using System;
namespace Best.HTTP.Shared.Logger
{
/// <summary>
/// Provides an implementation of <see cref="ILogOutput"/> that writes log messages to the Unity Debug Console.
/// </summary>
public sealed class UnityOutput : ILogOutput
{
/// <summary>
/// Gets a value indicating whether this log output accepts color codes.
/// </summary>
/// <remarks>
/// This property returns <c>true</c> when running in the Unity Editor and <c>false</c> otherwise.
/// </remarks>
public bool AcceptColor { get; } = UnityEngine.Application.isEditor;
/// <summary>
/// Writes a log message to the Unity Debug Console based on the specified log level.
/// </summary>
/// <param name="level">The log level of the message.</param>
/// <param name="logEntry">The log message to write.</param>
public void Write(Loglevels level, string logEntry)
{
switch (level)
{
case Loglevels.All:
case Loglevels.Information:
UnityEngine.Debug.Log(logEntry);
break;
case Loglevels.Warning:
UnityEngine.Debug.LogWarning(logEntry);
break;
case Loglevels.Error:
case Loglevels.Exception:
UnityEngine.Debug.LogError(logEntry);
break;
}
}
/// <summary>
/// This implementation does nothing.
/// </summary>
void ILogOutput.Flush() {}
void IDisposable.Dispose() => GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fd86ab6e6f8fab649b1b2a37452aa80f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: