// Constructs a LogSwitch. A LogSwitch is used to categorize log messages. // // All switches (except for the global LogSwitch) have a parent LogSwitch. // /// <include file='doc\LogSwitch.uex' path='docs/doc[@for="LogSwitch.LogSwitch"]/*' /> public LogSwitch(String name, String description, LogSwitch parent) { if ((name != null) && (parent != null) ) { if (name.Length == 0) throw new ArgumentOutOfRangeException ( "Name", Environment.GetResourceString( "Namelength_0")); strName = name; strDescription = description; iLevel = LoggingLevels.ErrorLevel; iOldLevel = iLevel; // update the parent switch to reflect this child switch parent.AddChildSwitch (this); ParentSwitch = parent; ChildSwitch = null; iNumChildren = 0; iChildArraySize = 0; Log.m_Hashtable.Add (strName, this); // Call into the EE to let it know about the creation of // this switch Log.AddLogSwitch (this); // update switch count Log.iNumOfSwitches++; } else throw new ArgumentNullException ((name==null ? "name" : "parent")); }
/// <summary> /// /// </summary> /// <param name="level">Current logging level</param> /// <param name="exception">The exception that should be logged</param> /// <returns>Guid that identifies the error incident.</returns> private static Guid LogWrite(LoggingLevels level, LoggingEvent loggingEvent) { Guid incidentId = Guid.Empty; if (s_appenders != null && s_appenders.Count > 0) { foreach (ILogAppender appender in s_appenders) { try { if (appender != null && appender.LoggingLevel != LoggingLevels.None && appender.LoggingLevel >= level) { appender.Append(level, loggingEvent); } } catch { //Do nothing... } } } else { Log.Failover.Append(level, loggingEvent); } return incidentId; }
/// <summary> /// Initializes a new instance of the <see cref="TraceLogger" /> class. /// </summary> /// <param name="name">The logger name.</param> /// <param name="validLevels">The valid log levels.</param> /// <param name="format">The format.</param> public TraceLogger( [NotNull] string name, [CanBeNull] FormatBuilder format = null, LoggingLevels validLevels = LoggingLevels.All) : base(name, TraceTextWriter.Default, format, false, validLevels) { }
/// <summary> /// Initializes a new instance of the <see cref="SqlLogger" /> class. /// </summary> /// <param name="name">The name.</param> /// <param name="connectionString">The connection string.</param> /// <param name="validLevels">The valid levels.</param> public SqlLogger( [NotNull]string name, [NotNull]string connectionString, LoggingLevels validLevels = LoggingLevels.All) : base(name, false, true, validLevels) { }
/// <summary> /// Initializes a new instance of the <see cref="TraceLogger" /> class. /// </summary> /// <param name="name">The logger name.</param> /// <param name="writer">The writer.</param> /// <param name="format">The format.</param> /// <param name="validLevels">The valid log levels.</param> public TextWriterLogger( [NotNull] string name, [NotNull] TextWriter writer, [CanBeNull] FormatBuilder format = null, LoggingLevels validLevels = LoggingLevels.All) : this(name, writer, format, true, validLevels) { }
public override void Append(LoggingLevels level, LoggingEvent loggingEvent) { if (loggingEvent != null) { string details = String.IsNullOrEmpty(loggingEvent.ExceptionDescription) ? "" : String.Format(CultureInfo.InvariantCulture, " - Details: {0}", loggingEvent.ExceptionDescription); Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0}{1}", loggingEvent.UserMessage, details)); } }
internal static void InvokeLogSwitchLevelHandlers(LogSwitch ls, LoggingLevels newLevel) { LogSwitchLevelHandler handler = _LogSwitchLevelHandler; if (handler != null) { handler(ls, newLevel); } }
/// <summary> /// Initializes a new instance of the <see cref="ConsoleLogger"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="format">The format.</param> /// <param name="validLevels">The valid levels.</param> /// <remarks> /// <para>Along with the <see cref="T:WebApplications.Utilities.Logging.Log.ToString(string, IFormatProvider)">standard formats supported by the logger</see>, also supports colouration using colour formats.</para> /// <para>To change colour use a '+' or '-' followed by a <see cref="ConsoleColor"/> e.g. <code>{+White}</code>. '+' indicates a foreground colour change, whilst /// '-' will change the background colour.</para> /// <para>The '?' colour will pick a colour based on the current log level, e.g. <code>{+?}</code> for an <see cref="LoggingLevel.Error">error</see> will /// change the foreground colour to red.</para> /// <para>The '_' colour will use the current consoles default foreground or background colour (depending on whether it is preceeded with '+' or '-').</para> /// </remarks> public ConsoleLogger( [NotNull] string name, [CanBeNull] FormatBuilder format = null, LoggingLevels validLevels = LoggingLevels.All) : base(name, ConsoleTextWriter.Default, format, false, validLevels) { if (!ConsoleHelper.IsConsole) throw new InvalidOperationException(Resources.ConsoleLogger_NotConsole); Format = format ?? Log.VerboseFormat; }
/// <summary> /// Initializes a new instance of the <see cref="LoggerBase" /> class. /// </summary> /// <param name="name">The name.</param> /// <param name="allowMultiple">if set to <see langword="true" /> the logger supports multiple instances.</param> /// <param name="validLevels">The valid levels.</param> protected LoggerBase( [NotNull] string name, bool allowMultiple = true, LoggingLevels validLevels = LoggingLevels.All) { if (name == null) throw new ArgumentNullException("name"); _name = name; _allowMultiple = allowMultiple; ValidLevels = validLevels; }
public virtual bool CheckLevel(LoggingLevels level) { if (this.iLevel <= level) { return true; } if (this.ParentSwitch == null) { return false; } return this.ParentSwitch.CheckLevel(level); }
/// <summary> /// Initializes a new instance of the <see cref="TextWriterLogger" /> class. /// </summary> /// <param name="name">The logger name.</param> /// <param name="writer">The writer.</param> /// <param name="format">The format.</param> /// <param name="allowMultiple">if set to <see langword="true" /> the logger supports multiple instances.</param> /// <param name="validLevels">The valid log levels.</param> protected TextWriterLogger( [NotNull] string name, [NotNull] TextWriter writer, [CanBeNull] FormatBuilder format, bool allowMultiple, LoggingLevels validLevels) : base(name, allowMultiple, validLevels) { if (writer == null) throw new ArgumentNullException("writer"); Format = format; _writer = writer; }
internal LogSwitch(string name, string description) { this.strName = name; this.strDescription = description; this.iLevel = LoggingLevels.ErrorLevel; this.iOldLevel = this.iLevel; this.ParentSwitch = null; this.ChildSwitch = null; this.iNumChildren = 0; this.iChildArraySize = 0; Log.m_Hashtable.Add(this.strName, this); Log.AddLogSwitch(this); Log.iNumOfSwitches++; }
[System.Security.SecuritySafeCritical] // auto-generated internal LogSwitch(String name, String description) { strName = name; strDescription = description; iLevel = LoggingLevels.ErrorLevel; iOldLevel = iLevel; ParentSwitch = null; Log.m_Hashtable.Add (strName, this); // Call into the EE to let it know about the creation of // this switch Log.AddLogSwitch (this); }
/// <summary> /// Initializes a new instance of the <see cref="EventLogger" /> class. /// </summary> /// <param name="name">The name of the logger.</param> /// <param name="eventLog"><para>The <see cref="System.Diagnostics.EventLog.Log">name</see> of the <see cref="EventLog">event log</see> to read/write to.</para> /// <para>By default this is set to "Application".</para></param> /// <param name="validLevels"><para>The valid log levels.</para> /// <para>By default this is set to <see cref="LoggingLevels">LogLevels.AtLeastInformation</see>.</para></param> /// <param name="format">The format.</param> /// <param name="machineName">Name of the machine.</param> public EventLogger( [NotNull] string name, [NotNull] string eventLog = "Application", LoggingLevels validLevels = LoggingLevels.AtLeastInformation, [CanBeNull] FormatBuilder format = null, [NotNull] string machineName = ".") : base(name, false, validLevels) { if (string.IsNullOrWhiteSpace(eventLog)) throw new ArgumentNullException("eventLog", Resources.EventLogger_EventLogCannotBeNull); if (string.IsNullOrWhiteSpace(machineName)) throw new ArgumentNullException("machineName", Resources.EventLogger_MachineNameCannotBeNull); _eventLog = eventLog; _machineName = machineName; Format = format ?? Log.VerboseFormat; }
// Checks if the given level is "on" for this switch or one of its parents. // /// <include file='doc\LogSwitch.uex' path='docs/doc[@for="LogSwitch.CheckLevel"]/*' /> public virtual bool CheckLevel(LoggingLevels level) { if (iLevel > level) { // recurse through the list till parent is hit. if (this.ParentSwitch == null) { return(false); } else { return(this.ParentSwitch.CheckLevel(level)); } } else { return(true); } }
//-------------------------------------------------------------------------------------------------// public static void Write(LoggingLevels loggingLevel, string message) { if (message != null && loggingLevel <= logLevel) { // // Add timestamp to message // DateTime now = DateTime.Now; message = now.ToString(STRLOG_TimestampFormat) + STRLOG_TimestampSpacer + message; //Trace.WriteLine(message); if (running == true) { // // Add the message to the queue // lock (logfileQueue.SyncRoot) { logfileQueue.Enqueue(message); } } else { try { // // Write the message to the log file // string filename = CreateDatedFilename(logfilePath); string fullpath = Path.GetFullPath(filename); StreamWriter sw = new StreamWriter(filename, true); sw.WriteLine(message); sw.Close(); } catch { // Message not written to log file } } } }
internal LogSwitch(String name, String description) { strName = name; strDescription = description; iLevel = LoggingLevels.ErrorLevel; iOldLevel = iLevel; ParentSwitch = null; ChildSwitch = null; iNumChildren = 0; iChildArraySize = 0; Log.m_Hashtable.Add(strName, this); // Call into the EE to let it know about the creation of // this switch Log.AddLogSwitch(this); // update switch count Log.iNumOfSwitches++; }
[System.Security.SecuritySafeCritical] // auto-generated internal LogSwitch(String name, String description) { strName = name; strDescription = description; iLevel = LoggingLevels.ErrorLevel; iOldLevel = iLevel; ParentSwitch = null; ChildSwitch = null; iNumChildren = 0; iChildArraySize = 0; Log.m_Hashtable.Add (strName, this); // Call into the EE to let it know about the creation of // this switch Log.AddLogSwitch (this); // update switch count Log.iNumOfSwitches++; }
public static SeverityLevel ToSeverityLevel(this LoggingLevels level) { switch (level) { case LoggingLevels.Critical: return(SeverityLevel.Critical); case LoggingLevels.Error: return(SeverityLevel.Error); case LoggingLevels.Information: return(SeverityLevel.Information); case LoggingLevels.Warning: return(SeverityLevel.Warning); default: throw new ArgumentException("Not a valid logging level"); } }
/** * Initializes a new instance of the OnionLogger class. * @param filepath Path to the logfile. * @param indentChar Character used for indentation. * @param indentSize The number of times to repeat indentChar for each * indentation. * @param loggingLevel The lowest level messages to log, where: * TRACE < DEBUG < INFO < WARN < ERROR < FATAL */ public OnionLogger(string filepath, char indentChar, uint indentSize, LoggingLevels loggingLevel) { this.indentChar = indentChar; this.indentSize = indentSize; this.LoggingLevel = loggingLevel; StringBuilder indentationSb = new StringBuilder(); for (uint i = 0; i < indentSize; ++i) { indentationSb.Append(indentChar); } this.indentationString = indentationSb.ToString(); stack = new Stack <LogLayer>(); writer = new StreamWriter(filepath); }
public static void LogMessage(LoggingLevels level, LogSwitch logswitch, string message) { if (logswitch == null) { throw new ArgumentNullException("LogSwitch"); } if (level < LoggingLevels.TraceLevel0) { throw new ArgumentOutOfRangeException("level", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (!logswitch.CheckLevel(level)) { return; } Debugger.Log((int)level, logswitch.strName, message); if (!Log.m_fConsoleDeviceEnabled) { return; } Console.Write(message); }
public override void Append(LoggingLevels level, LoggingEvent loggingEvent) { try { lock (FileAppender.s_syncObject) { using (FileStream stream = this.PrepeareAndCreateFileStream()) { using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine("{0:dd.MM.yyyy HH:mm:ss} [{1,-8}]: {2}", DateTime.Now, level, this.FormatMessage(level, loggingEvent)); writer.Flush(); } } } } catch (Exception e) { Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "Exception occured when writing to logfile. Details: {0}", e.ToString())); } }
/// <summary> /// Initializes a new instance of the <see cref="EventLogger" /> class. /// </summary> /// <param name="name">The name of the logger.</param> /// <param name="eventLog"><para>The <see cref="System.Diagnostics.EventLog.Log">name</see> of the <see cref="EventLog">event log</see> to read/write to.</para> /// <para>By default this is set to "Application".</para></param> /// <param name="validLevels"><para>The valid log levels.</para> /// <para>By default this is set to <see cref="LoggingLevels">LogLevels.AtLeastInformation</see>.</para></param> /// <param name="format">The format.</param> /// <param name="machineName">Name of the machine.</param> public EventLogger( [NotNull] string name, [NotNull] string eventLog = "Application", LoggingLevels validLevels = LoggingLevels.AtLeastInformation, [CanBeNull] FormatBuilder format = null, [NotNull] string machineName = ".") : base(name, false, validLevels) { if (string.IsNullOrWhiteSpace(eventLog)) { throw new ArgumentNullException("eventLog", Resources.EventLogger_EventLogCannotBeNull); } if (string.IsNullOrWhiteSpace(machineName)) { throw new ArgumentNullException("machineName", Resources.EventLogger_MachineNameCannotBeNull); } _eventLog = eventLog; _machineName = machineName; Format = format ?? Log.VerboseFormat; }
/// <summary> /// Logs the message to the configured log action <see cref="DoLogging"/>. /// </summary> /// <param name="callingMethodName">The name of the calling method.</param> /// <param name="e">The expception details, if any..</param> /// <param name="message">The message to write to the output window.</param> /// <param name="args">The arguments to format the message with.</param> private void LogMessage(string callingMethodName, Exception e = null, string message = null, params object[] args) { if (string.IsNullOrWhiteSpace(callingMethodName)) { throw new ArgumentNullException(nameof(callingMethodName), "No calling method name was supplied to the logger. Cannot determine the correct logging level."); } // covert the calling method name to a logging level - they must be identical // or this won't work. LoggingLevels callerLoggingLevel = LoggingLevels.Trace; bool parsed = Enum.TryParse(callingMethodName, ignoreCase: true, result: out callerLoggingLevel); if (!parsed) { // always log if we're not sure callerLoggingLevel = MinimumLoggingLevel; } if (callerLoggingLevel < MinimumLoggingLevel) { // we don't need to log anything return; } // apply message formatting if (args != null && args.Length > 0) { message = string.Format(message, args); } if (e != null) { message += $"{Environment.NewLine}{e}"; } // make note of the logging level and write the details _doLogging?.Invoke(callerLoggingLevel, message); }
// Constructs a LogSwitch. A LogSwitch is used to categorize log messages. // // All switches (except for the global LogSwitch) have a parent LogSwitch. // /// <include file='doc\LogSwitch.uex' path='docs/doc[@for="LogSwitch.LogSwitch"]/*' /> public LogSwitch(String name, String description, LogSwitch parent) { if ((name != null) && (parent != null)) { if (name.Length == 0) { throw new ArgumentOutOfRangeException( "Name", Environment.GetResourceString( "Namelength_0")); } strName = name; strDescription = description; iLevel = LoggingLevels.ErrorLevel; iOldLevel = iLevel; // update the parent switch to reflect this child switch parent.AddChildSwitch(this); ParentSwitch = parent; ChildSwitch = null; iNumChildren = 0; iChildArraySize = 0; Log.m_Hashtable.Add(strName, this); // Call into the EE to let it know about the creation of // this switch Log.AddLogSwitch(this); // update switch count Log.iNumOfSwitches++; } else { throw new ArgumentNullException((name == null ? "name" : "parent")); } }
//-------------------------------------------------------------------------------------------------// public static void WriteCompleted(LoggingLevels logLevel, string className, string methodName, string logMessage) { string message = null; if (methodName != null) { message = methodName; } if (className != null && methodName != null) { message = className + "." + message; } if (message != null) { message = message + STRLOG_Completed; if (logMessage != null) { message = STRLOG_CompletedMarker + logMessage + STRLOG_NewLine + STRLOG_TimestampEmpty + message; } Write(logLevel, message); } }
public IList<LogEntry> Find(DateTime fromDate, DateTime toDate, string username, LoggingLevels? severity) { using (var db = DbFactory.GetDataContext()) { var logEntries = from log in db.Logs where log.Timestamp >= fromDate && log.Timestamp <= toDate orderby log.Timestamp descending select log; IList<LogEntry> logs = new List<LogEntry>(); foreach (var log in logEntries) { var entity = log.CreateEntity(); if (!string.IsNullOrEmpty(username) && entity.Username != username) continue; if (severity.HasValue && entity.Level != severity.Value) continue; logs.Add(entity); } return logs; } }
public LogSwitch(string name, string description, LogSwitch parent) { if ((name != null) && (name.Length == 0)) { throw new ArgumentOutOfRangeException("Name", Environment.GetResourceString("Argument_StringZeroLength")); } if ((name == null) || (parent == null)) { throw new ArgumentNullException((name == null) ? "name" : "parent"); } this.strName = name; this.strDescription = description; this.iLevel = LoggingLevels.ErrorLevel; this.iOldLevel = this.iLevel; parent.AddChildSwitch(this); this.ParentSwitch = parent; this.ChildSwitch = null; this.iNumChildren = 0; this.iChildArraySize = 0; Log.m_Hashtable.Add(this.strName, this); Log.AddLogSwitch(this); Log.iNumOfSwitches++; }
public Boolean LogMessage(LoggingLevels loglevel, String Message, String Module = "", String Version = "") { NpgsqlConnection conn = new NpgsqlConnection(ConnectionString); try { conn.Open(); NpgsqlCommand command = conn.CreateCommand(); string sql = String.Format("INSERT INTO {0} (level, module, message, version) values('{1}', '{2}', '{3}', '{4}')", SystemSetup.DBLog_SchemaTableName, loglevel.ToString(), Module, Message, Version); command.CommandText = sql; var rows = command.ExecuteNonQuery(); conn.Close(); return(rows == 1); } catch (Exception exp) { return(false); } }
[System.Security.SecuritySafeCritical] // auto-generated public LogSwitch(String name, String description, LogSwitch parent) { if (name != null && name.Length == 0) throw new ArgumentOutOfRangeException("Name", Environment.GetResourceString("Argument_StringZeroLength")); Contract.EndContractBlock(); if ((name != null) && (parent != null)) { strName = name; strDescription = description; iLevel = LoggingLevels.ErrorLevel; iOldLevel = iLevel; ParentSwitch = parent; Log.m_Hashtable.Add (strName, this); // Call into the EE to let it know about the creation of // this switch Log.AddLogSwitch (this); } else throw new ArgumentNullException ((name==null ? "name" : "parent")); }
///// <summary> ///// Returns a formatted message that contains both the message and the exception details. ///// </summary> ///// <param name="message">The message to format</param> ///// <param name="exception">The exception to format</param> ///// <returns>The combined message</returns> public virtual string FormatMessage(LoggingLevels level, LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } if (!String.IsNullOrEmpty(loggingEvent.UserMessage) && !String.IsNullOrEmpty(loggingEvent.ExceptionDescription)) { return String.Format(CultureInfo.InvariantCulture,"{0} - Details: {1}", loggingEvent.UserMessage, loggingEvent.ExceptionDescription); } else if (!String.IsNullOrEmpty(loggingEvent.UserMessage)) { return loggingEvent.UserMessage; } else if (!String.IsNullOrEmpty(loggingEvent.ExceptionDescription)) { return loggingEvent.ExceptionDescription; } else { return loggingEvent.ToString(); } }
///// <summary> ///// Returns a formatted message that contains both the message and the exception details. ///// </summary> ///// <param name="message">The message to format</param> ///// <param name="exception">The exception to format</param> ///// <returns>The combined message</returns> public virtual string FormatMessage(LoggingLevels level, LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } if (!String.IsNullOrEmpty(loggingEvent.UserMessage) && !String.IsNullOrEmpty(loggingEvent.ExceptionDescription)) { return(String.Format(CultureInfo.InvariantCulture, "{0} - Details: {1}", loggingEvent.UserMessage, loggingEvent.ExceptionDescription)); } else if (!String.IsNullOrEmpty(loggingEvent.UserMessage)) { return(loggingEvent.UserMessage); } else if (!String.IsNullOrEmpty(loggingEvent.ExceptionDescription)) { return(loggingEvent.ExceptionDescription); } else { return(loggingEvent.ToString()); } }
// Generates a log message. If its switch (or a parent switch) allows the // level for the message, it is "broadcast" to all of the log // devices. // /// <include file='doc\log.uex' path='docs/doc[@for="Log.LogMessage1"]/*' /> public static void LogMessage(LoggingLevels level, LogSwitch logswitch, String message) { if (logswitch == null) { throw new ArgumentNullException("LogSwitch"); } if (level < 0) { throw new ArgumentOutOfRangeException("level", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } // Is logging for this level for this switch enabled? if (logswitch.CheckLevel(level) == true) { // Send message for logging // first send it to the debugger // @COOLPORT: Why This cast? Debugger.Log((int)level, logswitch.strName, message); // Send to the console device if (m_fConsoleDeviceEnabled) { Console.Write(message); } // Send it to the streams for (int i = 0; i < m_iNumOfStreamDevices; i++) { StreamWriter sw = new StreamWriter(m_rgStream[i]); sw.Write(message); sw.Flush(); } } }
//-------------------------------------------------------------------------------------------------// public static void WriteCompleted(LoggingLevels logLevel, string className, string methodName) { WriteCompleted(logLevel, className, methodName, null); }
//-------------------------------------------------------------------------------------------------// public static void SetLoggingLevel(LoggingLevels loggingLevel) { if (loggingLevel >= LoggingLevels.Minimum && loggingLevel <= LoggingLevels.Debug) { logLevel = loggingLevel; Write(STRLOG_LogLevel + logLevel.ToString()); } }
protected LogAppender(LoggingLevels loggingLevel, LoggingLevels minLoggingLevel) { this.MinLoggingLevel = minLoggingLevel; this.LoggingLevel = loggingLevel; }
protected LogAppender(LoggingLevels loggingLevel) : this(loggingLevel, LoggingLevels.None) { }
/// <summary> /// Writes a trace line to the instrumentation log. The instrmentation log is primarily /// used for deeper understanding what has happened during the stress run. /// </summary> /// <param name="level"></param> /// <param name="str"></param> public void WriteToInstrumentationLog(ReliabilityTestSet curTestSet, LoggingLevels level, string str) { if (curTestSet == null || (curTestSet.LoggingLevel & level) != 0) { str = String.Format("[{0} {2}] {1}\r\n", DateTime.Now.ToString(), str, Thread.CurrentThread.ManagedThreadId); try { lock (instrumentationMessageQueue) { instrumentationMessageQueue.Enqueue(str); } } catch (IOException) { /*Eat exceptions for IO */ } catch (InvalidOperationException) { /*Eat exceptions if we can't queue */} } }
//public abstract void WriteLine(LoggingLevels level, string message, Exception exception); public abstract void Append(LoggingLevels level, LoggingEvent loggingEvent);
/** * Instantiate a LogLayer. * @param name The name to identify this LogLayer. * @param loggingLevel The level at which to log the push/pop messages * for this LogLayer. */ public LogLayer(string name, LoggingLevels loggingLevel) { this.logLevel = loggingLevel; this.name = name; this.stopwatch = new Stopwatch(); }
/** * Instantiate a LogLayer, with the default LoggingLevel INFO. * @param name The name to identify this LogLayer. */ public LogLayer(string name) { this.logLevel = LoggingLevels.INFO; this.name = name; this.stopwatch = new Stopwatch(); }
/// <summary> /// Instantiates a ProdLoggingAttribute /// </summary> /// <param name="logLevel">The LoggingLevel of messages to output to the log</param> /// <remarks> /// If a LoggingVerbosity is not specified, it will default to minimum /// </remarks> public ProdLoggingAttribute(LoggingLevels logLevel) { LogLevel = logLevel; }
public void SetMask(LoggingLevels mask) { }
// Generates a log message. If its switch (or a parent switch) allows the // level for the message, it is "broadcast" to all of the log // devices. // /// <include file='doc\log.uex' path='docs/doc[@for="Log.LogMessage"]/*' /> public static void LogMessage(LoggingLevels level, String message) { LogMessage(level, GlobalSwitch, message); }
/// <summary> /// Initializes a new instance of the TraceAppender class with the specified logging level. /// </summary> public TraceAppender(LoggingLevels level) : base(level, LoggingLevels.Trace) { }
/// <summary> /// Prevents a default instance of the <see cref="ConsoleConnection"/> class from being created. /// </summary> // ReSharper disable once CodeAnnotationAnalyzer private ConsoleConnection( FormatBuilder defaultLogFormat, LoggingLevels defaultLoggingLevels, CancellationToken token) { if (!ConsoleHelper.IsConsole) throw new InvalidOperationException(CommonResources.Not_In_Console); _defaultLogFormat = defaultLogFormat; _defaultLoggingLevels = defaultLoggingLevels; _cancellationTokenSource = token.CanBeCanceled // ReSharper disable once PossiblyMistakenUseOfParamsMethod ? CancellationTokenSource.CreateLinkedTokenSource(token) : new CancellationTokenSource(); }
public Logger(string dirPath, LoggingLevels logLevel) { this._dirPath = dirPath; this.loggingLevel = logLevel; Initilization(); }
/// <summary> /// Runs the specified service using the command console as a user interface. /// </summary> /// <param name="service">The service.</param> /// <param name="runMode">The run mode.</param> /// <param name="defaultLogFormat">The default log format.</param> /// <param name="defaultLoggingLevels">The default logging levels.</param> /// <param name="token">The token.</param> /// <returns> /// An awaitable task. /// </returns> // ReSharper disable once CodeAnnotationAnalyzer public static async Task RunAsync( [NotNull] BaseService service, RunMode runMode = RunMode.Default, [CanBeNull] FormatBuilder defaultLogFormat = null, LoggingLevels defaultLoggingLevels = LoggingLevels.All, CancellationToken token = default(CancellationToken)) { if (service == null) throw new ArgumentNullException("service"); if (!ConsoleHelper.IsConsole) return; Console.Clear(); Log.SetTrace(validLevels: LoggingLevels.None); Log.SetConsole(defaultLogFormat ?? Log.ShortFormat, defaultLoggingLevels); await Log.Flush(token).ConfigureAwait(false); Impersonator impersonator = null; try { if (runMode.HasFlag(RunMode.Prompt)) { Debug.Assert(service.ServiceName != null); // Whether we start will depend on the selected option in prompt. runMode = runMode.Clear(RunMode.Start, true); Console.Title = ServiceResources.ConsoleConnection_RunAsync_ConfigureTitle + service.ServiceName; bool done = false; do { if (token.IsCancellationRequested) return; Dictionary<string, string> options = new Dictionary<string, string> { { "I", ServiceResources.ConsoleConnection_RunAsync_OptionInstall }, { "U", ServiceResources.ConsoleConnection_RunAsync_OptionUninstall }, { "S", ServiceResources.ConsoleConnection_RunAsync_OptionStart }, { "R", ServiceResources.ConsoleConnection_RunAsync_OptionRestart }, { "T", ServiceResources.ConsoleConnection_RunAsync_OptionStop }, { "P", ServiceResources.ConsoleConnection_RunAsync_OptionPause }, { "C", ServiceResources.ConsoleConnection_RunAsync_OptionContinue }, { "Y", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmd }, { "V", ServiceResources.ConsoleConnection_RunAsync_OptionStartCmd }, { "W", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmdNewCredentials }, { "Z", ServiceResources.ConsoleConnection_RunAsync_OptionRunNoInteraction }, { "X", ServiceResources.ConsoleConnection_RunAsync_OptionExit } }; if (!runMode.HasFlag(RunMode.Interactive)) { options.Remove("V"); options.Remove("Y"); options.Remove("W"); } bool isAdmin; string currentUser; try { WindowsIdentity identity = WindowsIdentity.GetCurrent(); currentUser = identity.Name; Debug.Assert(identity != null); WindowsPrincipal principal = new WindowsPrincipal(identity); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } catch { isAdmin = false; currentUser = null; } if (!string.IsNullOrEmpty(currentUser)) { FormatBuilder fb = new FormatBuilder() .AppendForegroundColor(ConsoleColor.Cyan) .Append("Current User: "******" [Admin]"); fb.AppendLine().WriteToConsole(); } if (!isAdmin) { options.Remove("I"); options.Remove("U"); } if (Controller.ServiceIsInstalled(service.ServiceName)) { ServiceControllerStatus state = Controller.GetServiceStatus(service.ServiceName); new FormatBuilder() .AppendForegroundColor(ConsoleColor.White) .AppendFormatLine( ServiceResources.ConsoleConnection_RunAsync_ServiceInstalledState, service.ServiceName, state) .AppendResetForegroundColor() .WriteToConsole(); options.Remove("I"); switch (state) { case ServiceControllerStatus.StopPending: case ServiceControllerStatus.Stopped: // Service is stopped or stopping. options.Remove("C"); options.Remove("R"); options.Remove("T"); break; case ServiceControllerStatus.StartPending: case ServiceControllerStatus.ContinuePending: case ServiceControllerStatus.Running: // Service is starting or running. options.Remove("S"); options.Remove("C"); break; case ServiceControllerStatus.PausePending: case ServiceControllerStatus.Paused: // Service is paused or pausing. options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("P"); break; default: // Service is not installed - shouldn't happen. options.Remove("U"); options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("C"); options.Remove("P"); break; } options.Remove("V"); options.Remove("Y"); options.Remove("Z"); } else { // No service installed. options.Remove("U"); options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("P"); options.Remove("C"); } _promptInstall.WriteToConsole( null, // ReSharper disable once PossibleNullReferenceException (_, c) => !string.Equals(c.Tag, "options", StringComparison.CurrentCultureIgnoreCase) ? Resolution.Unknown : options); string key; do { key = Char.ToUpperInvariant(Console.ReadKey(true).KeyChar) .ToString(CultureInfo.InvariantCulture); } while (!options.ContainsKey(key)); try { string userName; string password; switch (key) { case "I": GetUserNamePassword(out userName, out password); service.Install(ConsoleTextWriter.Default, userName, password); Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitInstall); while (!Controller.ServiceIsInstalled(service.ServiceName)) { await Task.Delay(250, token).ConfigureAwait(false); Console.Write('.'); } Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "U": await service.Uninstall(ConsoleTextWriter.Default, token).ConfigureAwait(false); Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitUninstall); while (Controller.ServiceIsInstalled(service.ServiceName)) { await Task.Delay(250, token).ConfigureAwait(false); Console.Write('.'); } Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "R": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop); await Controller.StopService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart); await Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "S": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart); await Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "T": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop); await Controller.StopService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "P": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingPause); await Controller.PauseService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); break; case "C": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingContinue); await Controller.ContinueService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "V": runMode = runMode.Set(RunMode.Start, true).Set(RunMode.Interactive, true); done = true; break; case "Y": runMode = runMode.Set(RunMode.Interactive, true); done = true; break; case "W": GetUserNamePassword(out userName, out password); if (userName == null) break; Debug.Assert(password != null); Impersonator ei = impersonator; impersonator = null; if (ei != null) ei.Dispose(); // Run in new security context. impersonator = new Impersonator(userName, password); break; case "Z": runMode = runMode.Set(RunMode.Start, true).Clear(RunMode.Interactive, true); done = true; Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive); Console.WriteLine( ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive2); Console.WriteLine(); break; default: return; } } catch (TaskCanceledException) { return; } catch (Exception e) { if (!token.IsCancellationRequested) Log.Add(e); } } while (!done); } else if (!runMode.HasFlag(RunMode.Interactive)) // If we don't show prompt and we're not interactive we should always start the service. runMode = runMode.Set(RunMode.Start, true); // Create connection Console.Title = ServiceResources.ConsoleConnection_RunAsync_RunningTitle + service.ServiceName; ConsoleConnection connection = new ConsoleConnection(defaultLogFormat, defaultLoggingLevels, token); Guid id = service.Connect(connection); // Combined cancellation tokens. ITokenSource tSource = token.CreateLinked(connection._cancellationTokenSource.Token); try { CancellationToken t = tSource.Token; if (t.IsCancellationRequested) return; if (runMode.HasFlag(RunMode.Start)) { // Start the service await service.StartService(ConsoleTextWriter.Default, null, t).ConfigureAwait(false); if (t.IsCancellationRequested) return; } if (!runMode.HasFlag(RunMode.Interactive)) { // Wait to be cancelled as nothing to do. await t.WaitHandle; return; } do { // Flush logs await Log.Flush(t).ConfigureAwait(false); if (t.IsCancellationRequested) break; WritePrompt(service); try { string commandLine = await Console.In.ReadLineAsync().ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(commandLine)) { bool completed = false; ICancelableTokenSource commandCancellationSource = t.ToCancelable(); CancellationToken commandToken = commandCancellationSource.Token; #pragma warning disable 4014 service.ExecuteAsync(id, commandLine, ConsoleTextWriter.Default, commandToken) .ContinueWith( task => { Debug.Assert(task != null); completed = true; if (task.IsCompleted || task.IsCanceled) return; if (task.IsFaulted) { Debug.Assert(task.Exception != null); _errorFormat.WriteToConsoleInstance(null, task.Exception); } }, TaskContinuationOptions.ExecuteSynchronously); #pragma warning restore 4014 while (!completed) { if (!commandCancellationSource.IsCancellationRequested && Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { // Cancel command Console.Write(ServiceResources.ConsoleConnection_RunAsync_Cancelling); commandCancellationSource.Cancel(); break; } await Task.Delay(100, token).ConfigureAwait(false); } } } catch (TaskCanceledException) { throw; } catch (Exception e) { if (!t.IsCancellationRequested) _errorFormat.WriteToConsoleInstance(null, e); } // Let any async stuff done by the command have a bit of time, also throttle commands. await Task.Delay(500, t).ConfigureAwait(false); } while (!t.IsCancellationRequested); } catch (TaskCanceledException) { } finally { tSource.Dispose(); // ReSharper disable MethodSupportsCancellation Log.Flush().Wait(); // ReSharper restore MethodSupportsCancellation service.Disconnect(id); Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_PressKeyToExit); Console.ReadKey(true); } } finally { if (impersonator != null) impersonator.Dispose(); } }
/// <summary> /// Initializes a new instance of the TraceAppender class with the specified logging level. /// </summary> public TraceAppender(LoggingLevels level, LoggingLevels minLoggingLevel) : base(level, minLoggingLevel) { }
public Logger(string dirPath) { this._dirPath = dirPath; this.LoggingLevel = LoggingLevels.INFO; Initilization(); }
public LoggerLevels(LoggingLevels level, bool enabled) { Level = level; Enabled = enabled; }
// Generates a log message. If its switch (or a parent switch) allows the // level for the message, it is "broadcast" to all of the log // devices. // public static void LogMessage(LoggingLevels level, LogSwitch logswitch, String message) { if (logswitch == null) throw new ArgumentNullException ("LogSwitch"); if (level < 0) throw new ArgumentOutOfRangeException("level", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Is logging for this level for this switch enabled? if (logswitch.CheckLevel (level) == true) { // Send message for logging // first send it to the debugger Debugger.Log ((int) level, logswitch.strName, message); // Send to the console device if (m_fConsoleDeviceEnabled) { Console.Write(message); } } }
/// <summary> /// Runs the specified service using the command console as a user interface. /// </summary> /// <param name="service">The service.</param> /// <param name="runMode">The run mode.</param> /// <param name="defaultLogFormat">The default log format.</param> /// <param name="defaultLoggingLevels">The default logging levels.</param> /// <param name="token">The token.</param> /// <returns> /// An awaitable task. /// </returns> // ReSharper disable once CodeAnnotationAnalyzer public static async Task RunAsync( [NotNull] BaseService service, RunMode runMode = RunMode.Default, [CanBeNull] FormatBuilder defaultLogFormat = null, LoggingLevels defaultLoggingLevels = LoggingLevels.All, CancellationToken token = default(CancellationToken)) { if (service == null) { throw new ArgumentNullException("service"); } if (!ConsoleHelper.IsConsole) { return; } Console.Clear(); Log.SetTrace(validLevels: LoggingLevels.None); Log.SetConsole(defaultLogFormat ?? _logFormatBuilder, defaultLoggingLevels); await Log.Flush(token).ConfigureAwait(false); Impersonator impersonator = null; try { if (runMode.HasFlag(RunMode.Prompt)) { Debug.Assert(service.ServiceName != null); // Whether we start will depend on the selected option in prompt. runMode = runMode.Clear(RunMode.Start, true); Console.Title = ServiceResources.ConsoleConnection_RunAsync_ConfigureTitle + service.ServiceName; bool done = false; do { if (token.IsCancellationRequested) { return; } Dictionary <string, string> options = new Dictionary <string, string> { { "I", ServiceResources.ConsoleConnection_RunAsync_OptionInstall }, { "U", ServiceResources.ConsoleConnection_RunAsync_OptionUninstall }, { "S", ServiceResources.ConsoleConnection_RunAsync_OptionStart }, { "R", ServiceResources.ConsoleConnection_RunAsync_OptionRestart }, { "T", ServiceResources.ConsoleConnection_RunAsync_OptionStop }, { "P", ServiceResources.ConsoleConnection_RunAsync_OptionPause }, { "C", ServiceResources.ConsoleConnection_RunAsync_OptionContinue }, { "Y", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmd }, { "V", ServiceResources.ConsoleConnection_RunAsync_OptionStartCmd }, { "W", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmdNewCredentials }, { "Z", ServiceResources.ConsoleConnection_RunAsync_OptionRunNoInteraction }, { "X", ServiceResources.ConsoleConnection_RunAsync_OptionExit } }; if (!runMode.HasFlag(RunMode.Interactive)) { options.Remove("V"); options.Remove("Y"); options.Remove("W"); } bool isAdmin; string currentUser; try { WindowsIdentity identity = WindowsIdentity.GetCurrent(); currentUser = identity.Name; Debug.Assert(identity != null); WindowsPrincipal principal = new WindowsPrincipal(identity); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } catch { isAdmin = false; currentUser = null; } if (!string.IsNullOrEmpty(currentUser)) { FormatBuilder fb = new FormatBuilder() .AppendForegroundColor(ConsoleColor.Cyan) .Append("Current User: "******" [Admin]"); } fb.AppendLine().WriteToConsole(); } if (!isAdmin) { options.Remove("I"); options.Remove("U"); } if (Controller.ServiceIsInstalled(service.ServiceName)) { ServiceControllerStatus state = Controller.GetServiceStatus(service.ServiceName); new FormatBuilder() .AppendForegroundColor(ConsoleColor.White) .AppendFormatLine( ServiceResources.ConsoleConnection_RunAsync_ServiceInstalledState, service.ServiceName, state) .AppendResetForegroundColor() .WriteToConsole(); options.Remove("I"); switch (state) { case ServiceControllerStatus.StopPending: case ServiceControllerStatus.Stopped: // Service is stopped or stopping. options.Remove("C"); options.Remove("R"); options.Remove("T"); break; case ServiceControllerStatus.StartPending: case ServiceControllerStatus.ContinuePending: case ServiceControllerStatus.Running: // Service is starting or running. options.Remove("S"); options.Remove("C"); break; case ServiceControllerStatus.PausePending: case ServiceControllerStatus.Paused: // Service is paused or pausing. options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("P"); break; default: // Service is not installed - shouldn't happen. options.Remove("U"); options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("C"); options.Remove("P"); break; } options.Remove("V"); options.Remove("Y"); options.Remove("Z"); } else { // No service installed. options.Remove("U"); options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("P"); options.Remove("C"); } _promptInstall.WriteToConsole( null, // ReSharper disable once PossibleNullReferenceException (_, c) => !string.Equals(c.Tag, "options", StringComparison.CurrentCultureIgnoreCase) ? Resolution.Unknown : options); string key; do { key = Char.ToUpperInvariant(Console.ReadKey(true).KeyChar) .ToString(CultureInfo.InvariantCulture); } while (!options.ContainsKey(key)); try { string userName; string password; switch (key) { case "I": GetUserNamePassword(out userName, out password); service.Install(ConsoleTextWriter.Default, userName, password); Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitInstall); while (!Controller.ServiceIsInstalled(service.ServiceName)) { await Task.Delay(250, token).ConfigureAwait(false); Console.Write('.'); } Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "U": await service.Uninstall(ConsoleTextWriter.Default, token).ConfigureAwait(false); Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitUninstall); while (Controller.ServiceIsInstalled(service.ServiceName)) { await Task.Delay(250, token).ConfigureAwait(false); Console.Write('.'); } Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "R": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop); await Controller.StopService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart); await Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "S": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart); await Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "T": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop); await Controller.StopService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "P": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingPause); await Controller.PauseService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); break; case "C": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingContinue); await Controller.ContinueService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "V": runMode = runMode.Set(RunMode.Start, true).Set(RunMode.Interactive, true); done = true; break; case "Y": runMode = runMode.Set(RunMode.Interactive, true); done = true; break; case "W": GetUserNamePassword(out userName, out password); if (userName == null) { break; } Debug.Assert(password != null); Impersonator ei = impersonator; impersonator = null; if (ei != null) { ei.Dispose(); } // Run in new security context. impersonator = new Impersonator(userName, password); break; case "Z": runMode = runMode.Set(RunMode.Start, true).Clear(RunMode.Interactive, true); done = true; Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive); Console.WriteLine( ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive2); Console.WriteLine(); break; default: return; } } catch (TaskCanceledException) { return; } catch (Exception e) { if (!token.IsCancellationRequested) { Log.Add(e); } } } while (!done); } else if (!runMode.HasFlag(RunMode.Interactive)) { // If we don't show prompt and we're not interactive we should always start the service. runMode = runMode.Set(RunMode.Start, true); } // Create connection Console.Title = ServiceResources.ConsoleConnection_RunAsync_RunningTitle + service.ServiceName; ConsoleConnection connection = new ConsoleConnection(defaultLogFormat, defaultLoggingLevels, token); Guid id = service.Connect(connection); // Combined cancellation tokens. ITokenSource tSource = token.CreateLinked(connection._cancellationTokenSource.Token); try { CancellationToken t = tSource.Token; if (t.IsCancellationRequested) { return; } if (runMode.HasFlag(RunMode.Start)) { // Start the service await service.StartService(ConsoleTextWriter.Default, null, t).ConfigureAwait(false); if (t.IsCancellationRequested) { return; } } if (!runMode.HasFlag(RunMode.Interactive)) { // Wait to be cancelled as nothing to do. await t.WaitHandle; return; } do { // Flush logs await Log.Flush(t).ConfigureAwait(false); if (t.IsCancellationRequested) { break; } WritePrompt(service); try { string commandLine = await Console.In.ReadLineAsync().ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(commandLine)) { bool completed = false; ICancelableTokenSource commandCancellationSource = t.ToCancelable(); CancellationToken commandToken = commandCancellationSource.Token; #pragma warning disable 4014 service.ExecuteAsync(id, commandLine, ConsoleTextWriter.Default, commandToken) .ContinueWith( task => { Debug.Assert(task != null); completed = true; if (task.IsCompleted || task.IsCanceled) { return; } if (task.IsFaulted) { Debug.Assert(task.Exception != null); _errorFormat.WriteToConsoleInstance(null, task.Exception); } }, TaskContinuationOptions.ExecuteSynchronously); #pragma warning restore 4014 while (!completed) { if (!commandCancellationSource.IsCancellationRequested && Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { // Cancel command Console.Write(ServiceResources.ConsoleConnection_RunAsync_Cancelling); commandCancellationSource.Cancel(); break; } await Task.Delay(100, token).ConfigureAwait(false); } } } catch (TaskCanceledException) { throw; } catch (Exception e) { if (!t.IsCancellationRequested) { _errorFormat.WriteToConsoleInstance(null, e); } } // Let any async stuff done by the command have a bit of time, also throttle commands. await Task.Delay(500, t).ConfigureAwait(false); } while (!t.IsCancellationRequested); } catch (TaskCanceledException) { } finally { tSource.Dispose(); // ReSharper disable MethodSupportsCancellation Log.Flush().Wait(); // ReSharper restore MethodSupportsCancellation service.Disconnect(id); Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_PressKeyToExit); Console.ReadKey(true); } } finally { if (impersonator != null) { impersonator.Dispose(); } } }