Class ExceptionLogger
This Singleton class exposes methods for formatting data from instances of the System.Exception class, and commonly used derived classes, and displaying the formatted data on a console (strictly speaking, on STDOUT, which can be redirected to a file), and recording them in a Windows event log.
Unlike most of the classes defined in this library, this class may be inherited.
All methods of this class are thread-safe. See Remarks.
Inherited Members
Namespace: WizardWrx.DLLConfigurationManager
Assembly: WizardWrx.DLLConfigurationManager.dll
Syntax
public class ExceptionLogger : GenericSingletonBase<ExceptionLogger>
Remarks
This class was developed to report exceptions in a multi threaded console application. Its methods were designed to report messages in a manner that is thread-safe, yet keeps each message intact.
Both objectives are achieved fairly easily.
All methods use only local variables. The only class level static data is a handful of constants, which are, by definition, read only, and the private SyncRoot object used to synchronize access to the object and its properties. This satisfies the first condition of thread safety, because all methods have exclusive access to all of their data.
Each message is built up, line by line, by appending to an instance of a StringBuilder class, using its AppendFormat method, which behaves like the static Format method of the System.String class. Although the AppendFormat method is an instance method, since the associated instance is local, thread safety remains intact. See Reference 1.
A single call to TextWriter.Synchronized ( Console.Out ).WriteLine or TextWriter.Synchronized ( Console.Error ).WriteLine writes the message, all at once, onto the console, preserving its integrity. Since the only event that uses a shared resource is called once only, and that call is synchronized, the message display is intact.
Since each method uses the shared resource, access to the console Standard Error (STDERR) stream, once only, and does so in a synchronized (thread-safe) way, the entire method is thread-safe.
As a reminder to include WizardWrx.DLLServices2.dll in your projects, I left this class in the WizardWrx.DLLServices2 namespace. Only symbolic constants got promoted to the root namespace.
Fields
| Improve this Doc View SourceWIZARDWRX_EVENT_SOURCE_ID
This string defines a default event source ID, WizardWrx, which I register on behalf of my own applications.
Declaration
public const string WIZARDWRX_EVENT_SOURCE_ID = null
Field Value
Type | Description |
---|---|
System.String |
Properties
| Improve this Doc View SourceAppEventSourceID
Along with the EventLoggingState property, this property governs recording of events in the Windows Application Event Log or in a custom event log of your choice.
The value of this property is the event source ID string to use. To simplify applications, this property has a default value, defined by WIZARDWRX_EVENT_SOURCE_ID.
IMPORTANT: Each event source ID string is machine specific, and each maps to one, and only one, event log, which is designated when the source is registered, as it must be before its first use.
Declaration
public string AppEventSourceID { get; set; }
Property Value
Type | Description |
---|---|
System.String |
ApplicationSubsystem
The value of this property is the actual subsystem ID reported by a fully managed function that yields the same result as the usual native (unmanaged) method.
Declaration
public PESubsystemInfo.PESubsystemID ApplicationSubsystem { get; }
Property Value
Type | Description |
---|---|
PESubsystemInfo.PESubsystemID |
Remarks
This property uses GetExeSubsystem in lieu of GetProcessSubsystem to circumvent an anomaly in the Visual Studio debugging engine, which causes that function to return 2 (Windows GUI subsystem) when you use the Visual Studio Hosting Process, which runs in the Windows subsystem. The cause of this behavior is that the Visual Studio Hosting Process trades places with the process under study, becoming the first executable file loaded into the active process.
ErrorMessageColors
Set this property to cause error messages to be displayed in a distinctive pair of foreground and background colors.
Unless the AppSubsystem property is Console or CUI, this property is meaningless.
Unlike other properties, ErrorMessageColors must be set directly, and it may be changed at any time.
Declaration
public ErrorMessagesInColor ErrorMessageColors { get; set; }
Property Value
Type | Description |
---|---|
ErrorMessagesInColor |
Remarks
A hidden MessageInColor is maintained in tandem with this property, for use with STDERR. In this way, messages written to either STDOUT or STDERR use the same color scheme.
OptionFlags
Gets or sets the new OutputOptions enumeration, which supersedes the obsolete individual flags.
Declaration
public ExceptionLogger.OutputOptions OptionFlags { get; set; }
Property Value
Type | Description |
---|---|
ExceptionLogger.OutputOptions |
s_strSettingsOmittedFromConfigFile
Once an instance has spring into being, this static property returns the configuration values that are missing a setting in the configuration file.
Declaration
public static string s_strSettingsOmittedFromConfigFile { get; }
Property Value
Type | Description |
---|---|
System.String |
StdErrIsRedirected
Return TRUE if the Standard Error console stream was redirected by the shell. Otherwise, the return value is FALSE.
This flag is meaningless unless the ApplicationSubsystem property value is equal to ProcessSubsystem.Console, indicating that the calling process is running in the Windows Character Mode (CUI) subsystem.
Declaration
public bool StdErrIsRedirected { get; }
Property Value
Type | Description |
---|---|
System.Boolean |
StdOutIsRedirected
Return TRUE if the Standard Output console stream was redirected by the shell. Otherwise, the return value is FALSE.
This flag is meaningless unless the ApplicationSubsystem property value is equal to ProcessSubsystem.Console, indicating that the calling process is running in the Windows Character Mode (CUI) subsystem.
Declaration
public bool StdOutIsRedirected { get; }
Property Value
Type | Description |
---|---|
System.Boolean |
Methods
| Improve this Doc View SourceGetReservedErrorMessage()
Return a message suitable for display on a console to accompany a status code of ERROR_SUCCESS (zero) or ERROR_RUNTIME (one), both defined in the MagicNumbers class of standard constant definitions.
Declaration
public string GetReservedErrorMessage()
Returns
Type | Description |
---|---|
System.String | Since its operation is self contained, this method should always succeed in returning an appropriate message. |
See Also
| Improve this Doc View SourceGetReservedErrorMessage(ExceptionLogger.ErrorExitOptions)
Return a message suitable for display on a console to accompany a status code of ERROR_SUCCESS (zero) or ERROR_RUNTIME (one), both defined in the MagicNumbers class of standard constant definitions.
Declaration
public string GetReservedErrorMessage(ExceptionLogger.ErrorExitOptions penmErrorExitOptions)
Parameters
Type | Name | Description |
---|---|---|
ExceptionLogger.ErrorExitOptions | penmErrorExitOptions | A member of the ErrorExitOptions specifies the desired action. This value overrides the corresponding bits in the OptionFlags bit mask. If an invalid value is specified, the returned string is an error message that starts with "An internal error has occurred." If this happens, it should be treated as a coding error. |
Returns
Type | Description |
---|---|
System.String | If the function succeeds, the returned message is ready to use; appropriate substitutions have already been made. Otherwise, the return value is the error message described in the documentation of argument penmErrorExitOptions. |
GetSpecifiedReservedErrorMessage(ExceptionLogger.ErrorExitOptions)
Return a message suitable for display on a console to accompany a status code of ERROR_SUCCESS (zero) or ERROR_RUNTIME (one), both defined in the MagicNumbers class of standard constant definitions.
Call this method with penmErrorExitOptions equal to Succeeded to get the ERROR_SUCCESS placeholder string for your error message table.
Declaration
public static string GetSpecifiedReservedErrorMessage(ExceptionLogger.ErrorExitOptions penmErrorExitOptions)
Parameters
Type | Name | Description |
---|---|---|
ExceptionLogger.ErrorExitOptions | penmErrorExitOptions | A member of the ErrorExitOptions specifies the desired action. Since this is a static method, and doesn't have access to the instance properties, this value substitutes for the corresponding bits in the OptionFlags bit mask. If an invalid value is specified, the returned string is an error message that starts with "An internal error has occurred." If this happens, it should be treated as a coding error. |
Returns
Type | Description |
---|---|
System.String | If the function succeeds, the returned message is ready to use; appropriate substitutions have already been made. Otherwise, the return value is the error message described in the documentation of argument penmErrorExitOptions. |
GetTheSingleInstance()
Call this static method from anywhere to get a reference to the ExceptionLogger singleton.
Declaration
public static ExceptionLogger GetTheSingleInstance()
Returns
Type | Description |
---|---|
ExceptionLogger | The return value is a reference to the singleton, which is created the first time the method is called. Subsequent calls return a reference to the singleton. |
Remarks
All overloads call this method, caching the returned reference in a local variable, before they override one or more of its default property values. When all overrides have been processed, the cached reference is returned through the overload that took the call.
This roundabout procedure is necessary because the properties cannot be set until the object has been created. The most straightforward way to do this is to call the default method, which performs a task usually performed by a default constructor in this implementation of the singleton design pattern.
GetTheSingleInstance(PESubsystemInfo.PESubsystemID)
Call this static method from anywhere to get a reference to the ExceptionLogger singleton and set its AppSubsystem property.
Declaration
public static ExceptionLogger GetTheSingleInstance(PESubsystemInfo.PESubsystemID penmProcessSubsystem)
Parameters
Type | Name | Description |
---|---|---|
PESubsystemInfo.PESubsystemID | penmProcessSubsystem | Use this member of the ProcessSubsystem enumeration to modify the default behavior of the exception logging methods, by enabling console output if the calling application has one. |
Returns
Type | Description |
---|---|
ExceptionLogger | The return value is a reference to the singleton, which is created the first time the method is called. Subsequent calls return a reference to the singleton. |
GetTheSingleInstance(PESubsystemInfo.PESubsystemID, ExceptionLogger.OutputOptions, String)
Call this static method from anywhere to get a reference to the ExceptionLogger singleton and set its ProcessSubsystem, OptionFlags, and AppEventSourceID properties.
Declaration
public static ExceptionLogger GetTheSingleInstance(PESubsystemInfo.PESubsystemID penmProcessSubsystem, ExceptionLogger.OutputOptions penmOutputOptions, string pstrEventSourceID)
Parameters
Type | Name | Description |
---|---|---|
PESubsystemInfo.PESubsystemID | penmProcessSubsystem | Use this member of the ProcessSubsystem enumeration to modify the default behavior of the exception logging methods, by enabling console output if the calling application has one. |
ExceptionLogger.OutputOptions | penmOutputOptions | The OutputOptions enumeration is organized for use as a bit mask. Set its flags as desired to control the format and content of output generated by the ReportException methods. |
System.String | pstrEventSourceID | Use this string to override the default event source ID, which is WIZARDWRX_EVENT_SOURCE_ID. |
Returns
Type | Description |
---|---|
ExceptionLogger | The return value is a reference to the singleton, which is created the first time the method is called. Subsequent calls return a reference to the singleton. |
Remarks
This method looks entirely forward, which means that it doesn't bother with the obsolete properties.
GetTheSingleInstance(ExceptionLogger.OutputOptions)
Call this static method from anywhere to get a reference to the ExceptionLogger singleton and set its OptionFlags property.
Declaration
public static ExceptionLogger GetTheSingleInstance(ExceptionLogger.OutputOptions penmOutputOptions)
Parameters
Type | Name | Description |
---|---|---|
ExceptionLogger.OutputOptions | penmOutputOptions | The OutputOptions enumeration is organized for use as a bit mask. Set its flags as desired to control the format and content of output generated by the ReportException methods. |
Returns
Type | Description |
---|---|
ExceptionLogger | The return value is a reference to the singleton, which is created the first time the method is called. Subsequent calls return a reference to the singleton. |
GetTheSingleInstance(ExceptionLogger.OutputOptions, String)
Call this static method from anywhere to get a reference to the ExceptionLogger singleton and set its ProcessSubsystem, OptionFlags, and AppEventSourceID properties.
Declaration
public static ExceptionLogger GetTheSingleInstance(ExceptionLogger.OutputOptions penmOutputOptions, string pstrEventSourceID)
Parameters
Type | Name | Description |
---|---|---|
ExceptionLogger.OutputOptions | penmOutputOptions | The OutputOptions enumeration is organized for use as a bit mask. Set its flags as desired to control the format and content of output generated by the ReportException methods. |
System.String | pstrEventSourceID | Use this string to override the default event source ID, which is WIZARDWRX_EVENT_SOURCE_ID. |
Returns
Type | Description |
---|---|
ExceptionLogger | The return value is a reference to the singleton, which is created the first time the method is called. Subsequent calls return a reference to the singleton. |
Remarks
This method looks entirely forward, which means that it doesn't bother with the obsolete properties.
OutputOptionsDisplay(String)
Return a labeled string representation of the current OptionFlags, along with decimal and hexadecimal representations of the bit mask.
Declaration
public string OutputOptionsDisplay(string pstrLabel)
Parameters
Type | Name | Description |
---|---|---|
System.String | pstrLabel | Specify a label to be inserted into the message. This may be the empty string, or even a null reference, to omit the label. |
Returns
Type | Description |
---|---|
System.String | The returned string is ready to display via Console.WriteLine or MessageBox.Show. |
OutputOptionTurnOff(ExceptionLogger.OutputOptions)
Turn the specified bit in the OutputOptions bit mask OFF.
Declaration
public ExceptionLogger.OutputOptions OutputOptionTurnOff(ExceptionLogger.OutputOptions penmOutputOptions)
Parameters
Type | Name | Description |
---|---|---|
ExceptionLogger.OutputOptions | penmOutputOptions | Specify the member of the OutputOptions enumerated type to turn OFF. |
Returns
Type | Description |
---|---|
ExceptionLogger.OutputOptions | The return value is the updated OutputOptions enumerated type, which is organized as a bit mask. |
OutputOptionTurnOn(ExceptionLogger.OutputOptions)
Turn the specified bit in the OutputOptions bit mask ON.
Declaration
public ExceptionLogger.OutputOptions OutputOptionTurnOn(ExceptionLogger.OutputOptions penmOutputOptions)
Parameters
Type | Name | Description |
---|---|---|
ExceptionLogger.OutputOptions | penmOutputOptions | Specify the member of the OutputOptions enumerated type to turn ON. |
Returns
Type | Description |
---|---|
ExceptionLogger.OutputOptions | The return value is the updated OutputOptions enumerated type, which is organized as a bit mask. |
ReportException(ArgumentException)
Format and report the properties of an ArgumentException exception on a console in a thread-safe manner.
Declaration
public string ReportException(ArgumentException perrBadArg)
Parameters
Type | Name | Description |
---|---|---|
ArgumentException | perrBadArg | The instance of the ArgumentException exception to process. See Remarks. |
Returns
Type | Description |
---|---|
System.String | The return value is the string that was written onto the standard error or standard output stream (or both, depending on the flags). NOTE: The returned string is terminated by a single newline. Since it is appended to the stream by a Console.Write, the carriage is returned to the next line, but no additional line feeds follow. Hence, if you want your error message to be followed by a blank line, you must follow this call with an empty Console.WriteLine or, |
Remarks
Although this method can process objects of ANY class which derives from ArgumentException, other methods of this class specialize in processing objects of the commonly used ArgumentOutOfRangeException and ArgumentNullException derived classes.
The TargetSite property, exposed by descendants of System.Exception, is the name of the method in which the exception was thrown.
ReportException(ArgumentNullException)
Format and report the properties of an ArgumentNullException exception on a console in a thread-safe manner. See Remarks.
Declaration
public string ReportException(ArgumentNullException perrNullArg)
Parameters
Type | Name | Description |
---|---|---|
ArgumentNullException | perrNullArg | The instance of an ArgumentNullException exception to process. |
Returns
Type | Description |
---|---|
System.String | The return value is the string that was written onto the standard error or standard output stream (or both, depending on the flags). NOTE: The returned string is terminated by a single newline. Since it is appended to the stream by a Console.Write, the carriage is returned to the next line, but no additional line feeds follow. Hence, if you want your error message to be followed by a blank line, you must follow this call with an empty Console.WriteLine or, |
Remarks
The TargetSite property, exposed by descendants of System.Exception, is the name of the method in which the exception was thrown.
ReportException(ArgumentOutOfRangeException)
Format and report the properties of an ArgumentOutOfRangeException exception on a console in a thread-safe manner.
Declaration
public string ReportException(ArgumentOutOfRangeException perrBadArg)
Parameters
Type | Name | Description |
---|---|---|
ArgumentOutOfRangeException | perrBadArg | The instance of the ArgumentOutOfRangeException class to process. |
Returns
Type | Description |
---|---|
System.String | The return value is the string that was written onto the standard error or standard output stream (or both, depending on the flags). NOTE: The returned string is terminated by a single newline. Since it is appended to the stream by a Console.Write, the carriage is returned to the next line, but no additional line feeds follow. Hence, if you want your error message to be followed by a blank line, you must follow this call with an empty Console.WriteLine or, |
Remarks
The TargetSite property, exposed by descendants of System.Exception, is the name of the method in which the exception was thrown.
ReportException(Exception)
Format and report the properties of a generic Exception on a console in a thread-safe manner.
Declaration
public string ReportException(Exception perrAny)
Parameters
Type | Name | Description |
---|---|---|
Exception | perrAny | The instance of the base Exception class to process. See Remarks. |
Returns
Type | Description |
---|---|
System.String | The return value is the string that was written onto the standard error or standard output stream (or both, depending on the flags). NOTE: The returned string is terminated by a single newline. Since it is appended to the stream by a Console.Write, the carriage is returned to the next line, but no additional line feeds follow. Hence, if you want your error message to be followed by a blank line, you must follow this call with an empty Console.WriteLine or, |
Remarks
This can be ANY exception type, although the intent is to limit its use to reporting exceptions thrown by the base class, System.Exception.
Other overloads exist for reporting exceptions thrown by types derived from System.Exception.
The TargetSite property, exposed by descendants of System.Exception, is the name of the method in which the exception was thrown.
ReportException(FormatException, String)
Format and report the properties of an FormatException exception on a console in a thread-safe manner.
Declaration
public string ReportException(FormatException perrrBadFormat, string pstrFormatString)
Parameters
Type | Name | Description |
---|---|---|
FormatException | perrrBadFormat | The instance of the FormatException class to process. |
System.String | pstrFormatString | This should be the format string which caused the exception. There should be a way to feed this to the exception, or recover it, but I have yet to find it. |
Returns
Type | Description |
---|---|
System.String | The return value is the string that was written onto the standard error or standard output stream (or both, depending on the flags). NOTE: The returned string is terminated by a single newline. Since it is appended to the stream by a Console.Write, the carriage is returned to the next line, but no additional line feeds follow. Hence, if you want your error message to be followed by a blank line, you must follow this call with an empty Console.WriteLine or, |
Remarks
The TargetSite property, exposed by descendants of System.Exception, is the name of the method in which the exception was thrown.
ReportException(IOException, FileInfo)
Format and report the properties of an IOException exception on a console in a thread-safe manner.
Declaration
public string ReportException(IOException perrIOError, FileInfo pfi)
Parameters
Type | Name | Description |
---|---|---|
IOException | perrIOError | The instance of the IOException class to process. See Remarks. |
FileInfo | pfi | The FileInfo object makes available much more than the file name, allowing for the possibility of an override to deliver more detailed information about the file being processed. |
Returns
Type | Description |
---|---|
System.String | The return value is the string that was written onto the standard error or standard output stream (or both, depending on the flags). NOTE: The returned string is terminated by a single newline. Since it is appended to the stream by a Console.Write, the carriage is returned to the next line, but no additional line feeds follow. Hence, if you want your error message to be followed by a blank line, you must follow this call with an empty Console.WriteLine |
Remarks
This routine processes ANY exception of the IOException class and its derivatives. Methods for parsing published derived classes are somewhere on my ToDo list.
The TargetSite property, exposed by descendants of System.Exception, is the name of the method in which the exception was thrown.
ReportException(ObjectDisposedException)
Format and report the properties of an ObjectDisposedException exception on a console in a thread-safe manner. See Remarks.
Declaration
public string ReportException(ObjectDisposedException perrDisposed)
Parameters
Type | Name | Description |
---|---|---|
ObjectDisposedException | perrDisposed | The instance of the ObjectDisposedException Exception class to process. |
Returns
Type | Description |
---|---|
System.String | The return value is the string that was written onto the standard error or standard output stream (or both, depending on the flags). NOTE: The returned string is terminated by a single newline. Since it is appended to the stream by a Console.Write, the carriage is returned to the next line, but no additional line feeds follow. Hence, if you want your error message to be followed by a blank line, you must follow this call with an empty Console.WriteLine or, |
Remarks
Any process that throws an ObjectDisposedException exception is in serious trouble, and deserves to crash, and be investigated, because this type of exception is almost invariably caused by a programming logic error.
The TargetSite property, exposed by descendants of System.Exception, is the name of the method in which the exception was thrown.
RestoreDefaultColors(Boolean)
Restore the default exception message colors.
Declaration
public ErrorMessagesInColor RestoreDefaultColors(bool pfWipeSavedColors)
Parameters
Type | Name | Description |
---|---|---|
System.Boolean | pfWipeSavedColors | To have the colors saved by the last call to SaveCurrentColors discarded, set this argument to TRUE. Otherwise, the saved colors are preserved. |
Returns
Type | Description |
---|---|
ErrorMessagesInColor | The return value is the reinstated default exception message colors, which may be NULL if the color scheme is invalid (both colors set to the same value) or missing (no color scheme is configured). |
RestoreDefaultOptions()
Restore the state of the OutputOptions flags to their initial (default) values.
Declaration
public ExceptionLogger.OutputOptions RestoreDefaultOptions()
Returns
Type | Description |
---|---|
ExceptionLogger.OutputOptions | The return value is the reinstated property value. |
Remarks
This routine calls the same static SetDefaultOptions method used by the static initializer, so that the defaults can be changed by visiting just one routine.
RestoreSavedColors()
Restore the ErrorMessageColors from the copy saved by the last SaveCurrentColors method call.
Declaration
public ErrorMessagesInColor RestoreSavedColors()
Returns
Type | Description |
---|---|
ErrorMessagesInColor | This method returns the restored message colors, so that callers may sanity check them against the expected values. |
Remarks
CAUTION: Unless this method is preceded by a call to SaveCurrentColors, this call completely disables color error messages, unless the static initializer set default colors from a configuration file.
RestoreSavedOptions()
Restore the state of the OutputOptions flags from the copy saved by the last SaveCurrentOptions method call.
Declaration
public ExceptionLogger.OutputOptions RestoreSavedOptions()
Returns
Type | Description |
---|---|
ExceptionLogger.OutputOptions | This method returns the options that were just restored, so that callers can sanity check them against the expected settings. |
Remarks
CAUTION: Unless this method is preceded by a call to SaveCurrentOptions, this call clears all flags, not just back to their initial state, but truly clear - all flags OFF.
SaveCurrentColors()
Save a copy of the current colors defined by the ErrorMessageColors property into a private area reserved for the purpose.
Declaration
public ErrorMessagesInColor SaveCurrentColors()
Returns
Type | Description |
---|---|
ErrorMessagesInColor | The current settings (the settings just saved) are returned. |
SaveCurrentOptions()
Save a copy of the current state of the OutputOptions flags into a private area reserved for the purpose.
Declaration
public ExceptionLogger.OutputOptions SaveCurrentOptions()
Returns
Type | Description |
---|---|
ExceptionLogger.OutputOptions | The current settings (the settings just saved) are returned. |
TimeStampedTraceWrite(String)
Append a message to a standard ISO-8601 time stamp.
Declaration
public static void TimeStampedTraceWrite(string pstrMessage)
Parameters
Type | Name | Description |
---|---|---|
System.String | pstrMessage | Specify the message to record. |
Remarks
Though written ostensibly for internal use, I marked this method as public because it will quickly find employment outside this library.