using System; using System.Globalization; namespace SweetLib.Utils.Logger.Message { /// /// A which is used to format objects. /// /// This class implements a singleton pattern. public class LogMessageFormatter : ICustomFormatter { private LogMessageFormatter() { } private static object Locker { get; } = new object(); /// /// Accesses the global instance of the . /// private static LogMessageFormatter FormatterInstance { get; set; } public static string DefaultFormatString { get; set; } = $"[{CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern} - {CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern}] (LL): V"; /// /// The default format string which is used to format objects, if no custom format string is provided. /// public static LogMessageFormatter Instance { get { if (FormatterInstance != null) return FormatterInstance; lock (Locker) { if (FormatterInstance != null) return FormatterInstance; FormatterInstance = new LogMessageFormatter(); } return FormatterInstance; } } /// /// Formats a object. /// /// The format string. If , will be used. /// The object to be formatted. /// Optional, an interface to be used while formatting if needed. /// A formatted of the . /// /// If is not a object, it will either be returned the formatted string implemented by the type of , if is implemented by it, or the result." /// public string Format(string format, object arg, IFormatProvider formatProvider) { if (format == null) format = DefaultFormatString; if (arg == null) throw new ArgumentNullException(nameof(arg)); if (arg.GetType() != typeof(LogMessage)) { var formattable = arg as IFormattable; return formattable?.ToString(format, formatProvider) ?? arg.ToString(); } var message = (LogMessage)arg; var result = message.LogDateTime.ToString(format, formatProvider); result = result.Replace("LL", message.LogLevel.ToString()); result = result.Replace("V", message.Message); return result; } } }