using System.Diagnostics;
namespace BepInEx.Logging
{
///
/// A source that routes all logs from the inbuilt .NET API to the BepInEx logging system.
///
///
public class TraceLogSource : TraceListener
{
///
/// Whether Trace logs are currently being rerouted.
///
public static bool IsListening { get; protected set; } = false;
private static TraceLogSource traceListener;
///
/// Creates a new trace log source.
///
/// New log source (or already existing one).
public static ILogSource CreateSource()
{
if (traceListener == null)
{
traceListener = new TraceLogSource();
Trace.Listeners.Add(traceListener);
IsListening = true;
}
return traceListener.LogSource;
}
///
/// Internal log source.
///
protected ManualLogSource LogSource { get; }
///
/// Creates a new trace log source.
///
protected TraceLogSource()
{
LogSource = new ManualLogSource("Trace");
}
///
/// Writes a message to the underlying instance.
///
/// The message to write.
public override void Write(string message)
{
LogSource.LogInfo(message);
}
///
/// Writes a message and a newline to the underlying instance.
///
/// The message to write.
public override void WriteLine(string message)
{
LogSource.LogInfo(message);
}
///
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
=> TraceEvent(eventCache, source, eventType, id, string.Format(format, args));
///
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
LogLevel level;
switch (eventType)
{
case TraceEventType.Critical:
level = LogLevel.Fatal;
break;
case TraceEventType.Error:
level = LogLevel.Error;
break;
case TraceEventType.Warning:
level = LogLevel.Warning;
break;
case TraceEventType.Information:
level = LogLevel.Info;
break;
case TraceEventType.Verbose:
default:
level = LogLevel.Debug;
break;
}
LogSource.Log(level, $"{message}".Trim());
}
}
}