using Swan.Logging; using System; namespace Swan.Lite.Logging { /// /// Use this class for text-based logger. /// public abstract class TextLogger { /// /// Gets or sets the logging time format. /// set to null or empty to prevent output. /// /// /// The logging time format. /// public static String LoggingTimeFormat { get; set; } = "HH:mm:ss.fff"; /// /// Gets the color of the output of the message (the output message has a new line char in the end). /// /// The instance containing the event data. /// /// The output message formatted and the color of the console to be used. /// protected (String outputMessage, ConsoleColor color) GetOutputAndColor(LogMessageReceivedEventArgs logEvent) { (String prefix, ConsoleColor color) = GetConsoleColorAndPrefix(logEvent.MessageType); String loggerMessage = String.IsNullOrWhiteSpace(logEvent.Message) ? String.Empty : logEvent.Message.RemoveControlCharsExcept('\n'); String outputMessage = CreateOutputMessage(logEvent.Source, loggerMessage, prefix, logEvent.UtcDate); // Further format the output in the case there is an exception being logged if(logEvent.MessageType == LogLevel.Error && logEvent.Exception != null) { try { outputMessage += $"{logEvent.Exception.Stringify().Indent()}{Environment.NewLine}"; } catch { // Ignore } } return (outputMessage, color); } private static (String Prefix, ConsoleColor color) GetConsoleColorAndPrefix(LogLevel messageType) => messageType switch { LogLevel.Debug => (ConsoleLogger.DebugPrefix, ConsoleLogger.DebugColor), LogLevel.Error => (ConsoleLogger.ErrorPrefix, ConsoleLogger.ErrorColor), LogLevel.Info => (ConsoleLogger.InfoPrefix, ConsoleLogger.InfoColor), LogLevel.Trace => (ConsoleLogger.TracePrefix, ConsoleLogger.TraceColor), LogLevel.Warning => (ConsoleLogger.WarnPrefix, ConsoleLogger.WarnColor), LogLevel.Fatal => (ConsoleLogger.FatalPrefix, ConsoleLogger.FatalColor), _ => (new String(' ', ConsoleLogger.InfoPrefix.Length), Terminal.Settings.DefaultColor), }; private static String CreateOutputMessage(String sourceName, String loggerMessage, String prefix, DateTime date) { String friendlySourceName = String.IsNullOrWhiteSpace(sourceName) ? String.Empty : sourceName.SliceLength(sourceName.LastIndexOf('.') + 1, sourceName.Length); String outputMessage = String.IsNullOrWhiteSpace(sourceName) ? loggerMessage : $"[{friendlySourceName}] {loggerMessage}"; return String.IsNullOrWhiteSpace(LoggingTimeFormat) ? $" {prefix} >> {outputMessage}{Environment.NewLine}" : $" {date.ToLocalTime().ToString(LoggingTimeFormat)} {prefix} >> {outputMessage}{Environment.NewLine}"; } } }