public static void WriteAndResetColor(ConsoleColor color, AbstractConsole console, string text) { var resetPoint = CreateColorResetPoint(console); console.ForegroundColor = color; console.WriteLine(text); resetPoint(); }
public TraceConsole(AbstractConsole console, ICommand command) { Console = console; Command = command; _disposables = new List<IDisposable>(); TraceableCommand = command as ITraceableCommand; if (TraceableCommand != null) { Trace.AutoFlush = true; TraceSource = new TraceSource(command.Name) { Switch = new SourceSwitch(Command.Name) { Level = SourceLevels.All } }; if (!string.IsNullOrEmpty(TraceableCommand.WriteFile)) { var fileName = string.Format(TraceableCommand.WriteFile.Replace("{", "{0:"),DateTime.Now); var fileInfo = new FileInfo(fileName); if (fileInfo.Directory != null && !fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } var listener = new TimestampedTextWriterTraceListener(fileName); listener.Filter = new EventTypeFilter(!TraceableCommand.FileLogLevel.Any() ? GetLevel(TraceableCommand.LogLevel) : GetLevel(TraceableCommand.FileLogLevel)); TraceSource.Listeners.Add(listener); _disposables.Add(listener); } if (TraceableCommand.WriteEventLog) { var listener = new EventLogTraceListener(Command.Name); listener.Filter = new EventTypeFilter(!TraceableCommand.EventLogLevel.Any() ? GetLevel(TraceableCommand.LogLevel) : GetLevel(TraceableCommand.EventLogLevel)); TraceSource.Listeners.Add(listener); _disposables.Add(listener); } } }
private void LogException(AbstractConsole console, Exception exception, ICommand command) { if (console == null) console = Console; var traceconsole = console as TraceConsole; var stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Unexpected error happended while proceeding the command: " + command.Name); var exceptionWalker = new ExceptionWalker(exception); foreach (var message in exceptionWalker.GetExceptionMessages()) { stringBuilder.AppendLine(message); } if(traceconsole != null) { //If we have a TraceConsole, trace as error, otherwise use the default Console try { traceconsole.TraceEvent(TraceEventType.Error, 0, stringBuilder.ToString()); } catch (Exception ex) { //In case of any errors regardings the tracing (e.g. missing FileWrite rights) use //the default console and log this exception as well ConsoleHelper.WriteLineInRed(Console, stringBuilder.ToString()); LogException(Console, ex, command); } } else { ConsoleHelper.WriteLineInRed(Console, stringBuilder.ToString()); } }
public static Action CreateColorResetPoint(AbstractConsole console) { var currentColor = console.ForegroundColor; return () => console.ForegroundColor = currentColor; }
public static void WriteLineInGreen(AbstractConsole console, string text) { WriteAndResetColor(ConsoleColor.Green, console, text); }
public static void WriteLineInRed(AbstractConsole console, string text) { WriteAndResetColor(ConsoleColor.Red, console, text); }