⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 coloredconsoleappender.cs

📁 精通SQL Server2005项目开发
💻 CS
📖 第 1 页 / 共 2 页
字号:
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax

// .NET Compact Framework 1.0 has no support for Win32 Console API's
#if !NETCF 
// .Mono 1.0 has no support for Win32 Console API's
#if !MONO 
// SSCLI 1.0 has no support for Win32 Console API's
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0

using System;
using System.Globalization;
using System.Runtime.InteropServices;

using log4net.Layout;
using log4net.Util;

namespace log4net.Appender
{
	/// <summary>
	/// Appends logging events to the console.
	/// </summary>
	/// <remarks>
	/// <para>
	/// ColoredConsoleAppender appends log events to the standard output stream
	/// or the error output stream using a layout specified by the 
	/// user. It also allows the color of a specific type of message to be set.
	/// </para>
	/// <para>
	/// By default, all output is written to the console's standard output stream.
	/// The <see cref="Target"/> property can be set to direct the output to the
	/// error stream.
	/// </para>
	/// <para>
	/// NOTE: This appender writes directly to the application's attached console
	/// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>.
	/// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be
	/// programmatically redirected (for example NUnit does this to capture program output).
	/// This appender will ignore these redirections because it needs to use Win32
	/// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/>
	/// must be used.
	/// </para>
	/// <para>
	/// When configuring the colored console appender, mapping should be
	/// specified to map a logging level to a color. For example:
	/// </para>
	/// <code lang="XML" escaped="true">
	/// <mapping>
	/// 	<level value="ERROR" />
	/// 	<foreColor value="White" />
	/// 	<backColor value="Red, HighIntensity" />
	/// </mapping>
	/// <mapping>
	/// 	<level value="DEBUG" />
	/// 	<backColor value="Green" />
	/// </mapping>
	/// </code>
	/// <para>
	/// The Level is the standard log4net logging level and ForeColor and BackColor can be any
	/// combination of the following values:
	/// <list type="bullet">
	/// <item><term>Blue</term><description></description></item>
	/// <item><term>Green</term><description></description></item>
	/// <item><term>Red</term><description></description></item>
	/// <item><term>White</term><description></description></item>
	/// <item><term>Yellow</term><description></description></item>
	/// <item><term>Purple</term><description></description></item>
	/// <item><term>Cyan</term><description></description></item>
	/// <item><term>HighIntensity</term><description></description></item>
	/// </list>
	/// </para>
	/// </remarks>
	/// <author>Rick Hobbs</author>
	/// <author>Nicko Cadell</author>
	public class ColoredConsoleAppender : AppenderSkeleton
	{
		#region Colors Enum

		/// <summary>
		/// The enum of possible color values for use with the color mapping method
		/// </summary>
		/// <remarks>
		/// <para>
		/// The following flags can be combined together to
		/// form the colors.
		/// </para>
		/// </remarks>
		/// <seealso cref="ColoredConsoleAppender" />
		[Flags]
		public enum Colors : int
		{
			/// <summary>
			/// color is blue
			/// </summary>
			Blue = 0x0001,

			/// <summary>
			/// color is green
			/// </summary>
			Green = 0x0002,

			/// <summary>
			/// color is red
			/// </summary>
			Red = 0x0004,

			/// <summary>
			/// color is white
			/// </summary>
			White = Blue | Green | Red,

			/// <summary>
			/// color is yellow
			/// </summary>
			Yellow = Red | Green,

			/// <summary>
			/// color is purple
			/// </summary>
			Purple = Red | Blue,

			/// <summary>
			/// color is cyan
			/// </summary>
			Cyan = Green | Blue,

			/// <summary>
			/// color is intensified
			/// </summary>
			HighIntensity = 0x0008,
		}

		#endregion // Colors Enum

		#region Public Instance Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class.
		/// </summary>
		/// <remarks>
		/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write 
		/// to the standard output stream.
		/// </remarks>
		public ColoredConsoleAppender() 
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
		/// with the specified layout.
		/// </summary>
		/// <param name="layout">the layout to use for this appender</param>
		/// <remarks>
		/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write 
		/// to the standard output stream.
		/// </remarks>
		[Obsolete("Instead use the default constructor and set the Layout property")]
		public ColoredConsoleAppender(ILayout layout) : this(layout, false)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
		/// with the specified layout.
		/// </summary>
		/// <param name="layout">the layout to use for this appender</param>
		/// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param>
		/// <remarks>
		/// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to
		/// the standard error output stream.  Otherwise, output is written to the standard
		/// output stream.
		/// </remarks>
		[Obsolete("Instead use the default constructor and set the Layout & Target properties")]
		public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) 
		{
			Layout = layout;
			m_writeToErrorStream = writeToErrorStream;
		}

		#endregion // Public Instance Constructors

		#region Public Instance Properties

		/// <summary>
		/// Target is the value of the console output stream.
		/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
		/// </summary>
		/// <value>
		/// Target is the value of the console output stream.
		/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
		/// </value>
		/// <remarks>
		/// <para>
		/// Target is the value of the console output stream.
		/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
		/// </para>
		/// </remarks>
		virtual public string Target
		{
			get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; }
			set
			{
				string v = value.Trim();
				
				if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) 
				{
					m_writeToErrorStream = true;
				} 
				else 
				{
					m_writeToErrorStream = false;
				}
			}
		}

		/// <summary>
		/// Add a mapping of level to color - done by the config file
		/// </summary>
		/// <param name="mapping">The mapping to add</param>
		/// <remarks>
		/// <para>
		/// Add a <see cref="LevelColors"/> mapping to this appender.
		/// Each mapping defines the foreground and background colors
		/// for a level.
		/// </para>
		/// </remarks>
		public void AddMapping(LevelColors mapping)
		{
			m_levelMapping.Add(mapping);
		}

		#endregion // Public Instance Properties

		#region Override implementation of AppenderSkeleton

		/// <summary>
		/// This method is called by the <see cref="AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method.
		/// </summary>
		/// <param name="loggingEvent">The event to log.</param>
		/// <remarks>
		/// <para>
		/// Writes the event to the console.
		/// </para>
		/// <para>
		/// The format of the output will depend on the appender's layout.
		/// </para>
		/// </remarks>
		override protected void Append(log4net.Core.LoggingEvent loggingEvent) 
		{
			if (m_consoleOutputWriter != null)
			{
				IntPtr consoleHandle = IntPtr.Zero;
				if (m_writeToErrorStream)
				{
					// Write to the error stream
					consoleHandle = GetStdHandle(STD_ERROR_HANDLE);
				}
				else
				{
					// Write to the output stream
					consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
				}

				// Default to white on black
				ushort colorInfo = (ushort)Colors.White;

				// see if there is a specified lookup
				LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
				if (levelColors != null)
				{
					colorInfo = levelColors.CombinedColor;
				}

				// Render the event to a string
				string strLoggingMessage = RenderLoggingEvent(loggingEvent);

				// get the current console color - to restore later
				CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
				GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo);

				// set the console colors
				SetConsoleTextAttribute(consoleHandle, colorInfo);

				// Using WriteConsoleW seems to be unreliable.
				// If a large buffer is written, say 15,000 chars
				// Followed by a larger buffer, say 20,000 chars
				// then WriteConsoleW will fail, last error 8
				// 'Not enough storage is available to process this command.'
				// 
				// Although the documentation states that the buffer must
				// be less that 64KB (i.e. 32,000 WCHARs) the longest string
				// that I can write out a the first call to WriteConsoleW
				// is only 30,704 chars.
				//
				// Unlike the WriteFile API the WriteConsoleW method does not 
				// seem to be able to partially write out from the input buffer.
				// It does have a lpNumberOfCharsWritten parameter, but this is
				// either the length of the input buffer if any output was written,
				// or 0 when an error occurs.
				//
				// All results above were observed on Windows XP SP1 running
				// .NET runtime 1.1 SP1.
				//
				// Old call to WriteConsoleW:
				//
				// WriteConsoleW(
				//     consoleHandle,
				//     strLoggingMessage,
				//     (UInt32)strLoggingMessage.Length,
				//     out (UInt32)ignoreWrittenCount,

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -