using System;
using System.Text;
namespace ExtremelySimpleLogger {
///
/// A sink is a way for log messages passed to a to be processed in a certain way.
/// By default, and are available.
///
public abstract class Sink : IDisposable {
///
/// The minimum level that a log message needs to have for it to be processed by this sink.
///
public LogLevel MinimumLevel { get; set; } = LogLevel.Info;
///
/// The with which this message should be formatted.
/// By default, is used.
///
public LogFormatter Formatter { get; set; }
///
/// Initializes a new sink with the default settings.
///
public Sink() {
this.Formatter = this.FormatDefault;
}
///
/// Logs a message in the way specified by the sink's implementation.
///
/// The logger that the message was passed to
/// The importance level of this message
/// The message
/// An optional exception whose stack trace will be appended to the message
public virtual void Log(Logger logger, LogLevel level, object message, Exception e = null) {
this.Log(this.Formatter.Invoke(logger, level, message, e));
}
///
/// Logs the given message, which has already been formatted using .
///
/// The message to log
public abstract void Log(string s);
///
/// The default formatter for logging messages.
/// By default, messages are laid out as follows:
///
/// [Date and time] [Logger name, if set] [Log level] Message
/// Exception, if set
///
///
/// The logger that the message was passed to
/// The importance level of this message
/// The message
/// An optional exception whose stack trace will be appended to the message
/// A formatted string to log
public virtual string FormatDefault(Logger logger, LogLevel level, object message, Exception e = null) {
var builder = new StringBuilder();
// date
builder.Append($"[{DateTime.Now}] ");
// logger name
if (!string.IsNullOrEmpty(logger.Name))
builder.Append($"[{logger.Name}] ");
// log level
builder.Append($"[{level}] ");
// message
builder.Append(message);
// stack trace
if (e != null)
builder.Append($"\n{e}");
return builder.ToString();
}
///
/// A delegate method used by .
///
/// The logger that the message was passed to
/// The importance level of this message
/// The message
/// An optional exception whose stack trace will be appended to the message
public delegate string LogFormatter(Logger logger, LogLevel level, object message, Exception e = null);
///
/// Disposes this sink, freeing all of the resources it uses.
///
public virtual void Dispose() {
}
}
}