You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4net-dev@logging.apache.org by Wesley Smith <We...@tdsway.com> on 2005/01/27 21:09:57 UTC

Make ColoredConsoleAppender reset console's colors when finished.

ColoredConsoleAppender does not reset the console's colors back to their
original color, so that after the program being logged finishes, your
console is left in whatever color the last log message was printed in.
The following patch fixes the problem:


--- C:\TEMP\log4net-1.2.0-beta8\src\Appender\ColoredConsoleAppender.cs
Mon Jul 07 01:05:02 2003
+++ C:\Program
Files\log4net\log4net-1.2.0-beta8\src\Appender\ColoredConsoleAppender.cs
Wed Jan 26 13:00:00 2005
@@ -275,6 +275,11 @@
 				uiColorInfo = (uint)colLookup;
 			}
 
+			// Save existing console colors
+
+			CONSOLE_SCREEN_BUFFER_INFO originalBufferInfo;
+			GetConsoleScreenBufferInfo(iConsoleHandle, out
originalBufferInfo);
+
 			// set the console.
 			SetConsoleTextAttribute(iConsoleHandle,
uiColorInfo);
 
@@ -287,6 +292,9 @@
 
(UInt32)strLoggingMessage.Length,
 							out
(UInt32)uiWritten,
 							IntPtr.Zero);
+
+			// Restore original colors
+			SetConsoleTextAttribute(iConsoleHandle,
originalBufferInfo.wAttributes);
 		}
 
 		/// <summary>
@@ -346,6 +354,36 @@
 		[DllImport("Kernel32.dll", SetLastError=true,
CharSet=CharSet.Auto)]
 		private static extern IntPtr GetStdHandle(
 			UInt32 uiType);
+
+		[StructLayout(LayoutKind.Sequential)]
+			struct COORD
+		{
+			public short x;
+			public short y;
+		}
+
+		[StructLayout(LayoutKind.Sequential)]
+			struct SMALL_RECT
+		{
+			public short Left;
+			public short Top;
+			public short Right;
+			public short Bottom;
+		}
+
+		[StructLayout(LayoutKind.Sequential)]
+			struct	CONSOLE_SCREEN_BUFFER_INFO
+		{
+			public COORD dwSize;
+			public COORD dwCursorPosition;
+			public uint wAttributes;
+			public SMALL_RECT srWindow;
+			public COORD dwMaximumWindowSize;
+		}
+
+		[DllImport("kernel32.dll",
EntryPoint="GetConsoleScreenBufferInfo", SetLastError=true,
CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
+		private static extern int
GetConsoleScreenBufferInfo(IntPtr hConsoleHandle, out
CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);
+
 
 		#endregion
 	}