using System;
using System.IO;
using System.Text;
namespace BepInEx.Logging
{
///
/// The base implementation of a logging class.
///
public abstract class BaseLogger : TextWriter
{
protected BaseLogger()
{
DisplayedLevels = GetDefaultLogLevel();
}
///
/// The encoding that the underlying text writer should use. Defaults to UTF-8 BOM.
///
public override Encoding Encoding { get; } = new UTF8Encoding(true);
///
/// The handler for a entry logged event.
///
/// The text element of the log itself.
/// Whether or not it should be dislpayed to the user.
public delegate void EntryLoggedEventHandler(LogLevel level, object entry);
///
/// The listener event for an entry being logged.
///
public event EntryLoggedEventHandler EntryLogged;
///
/// Retrieves the default log level to use for this logger.
///
/// The default log level to use.
protected virtual LogLevel GetDefaultLogLevel()
{
LogLevel lowest;
try
{
lowest = (LogLevel)Enum.Parse(typeof(LogLevel), Config.GetEntry("logger-displayed-levels", nameof(LogLevel.Info), "BepInEx"));
}
catch
{
return LogLevel.All;
}
if (lowest == LogLevel.None)
return LogLevel.None;
LogLevel value = lowest;
foreach (LogLevel e in Enum.GetValues(typeof(LogLevel)))
{
if (lowest > e)
value |= e;
}
return value;
}
///
/// A filter which is used to specify which log levels are not ignored by the logger.
///
public LogLevel DisplayedLevels { get; set; }
private readonly object logLockObj = new object();
///
/// Logs an entry to the Logger instance.
///
/// The level of the entry.
/// The textual value of the entry.
public virtual void Log(LogLevel level, object entry)
{
if ((DisplayedLevels & level) != LogLevel.None)
{
lock (logLockObj)
{
EntryLogged?.Invoke(level, entry);
WriteLine($"[{level.GetHighestLevel()}] {entry}");
}
}
}
///
/// Logs an entry to the Logger instance, with a of Message.
///
/// The text value of this log entry.
public virtual void Log(object entry)
{
Log(LogLevel.Message, entry);
}
}
}