示例#1
0
        /// <summary>
        /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(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>
        protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        {
            string loggingMessage = RenderLoggingEvent(loggingEvent);

            // see if there is a specified lookup.
            LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;

            if (levelColors != null)
            {
                // Prepend the Ansi Color code
                loggingMessage = levelColors.CombinedColor + loggingMessage;
            }

            // on most terminals there are weird effects if we don't clear the background color
            // before the new line.  This checks to see if it ends with a newline, and if
            // so, inserts the clear codes before the newline, otherwise the clear codes
            // are inserted afterwards.
            if (loggingMessage.Length > 1)
            {
                if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r"))
                {
                    loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes);
                }
                else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r"))
                {
                    loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes);
                }
                else
                {
                    loggingMessage = loggingMessage + PostEventCodes;
                }
            }
            else
            {
                if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r')
                {
                    loggingMessage = PostEventCodes + loggingMessage;
                }
                else
                {
                    loggingMessage = loggingMessage + PostEventCodes;
                }
            }

#if NETCF_1_0
            // Write to the output stream
            Console.Write(loggingMessage);
#else
            if (m_writeToErrorStream)
            {
                // Write to the error stream
                Console.Error.Write(loggingMessage);
            }
            else
            {
                // Write to the output stream
                Console.Write(loggingMessage);
            }
#endif
        }
示例#2
0
        override protected void Append(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);

                char[] messageCharArray = strLoggingMessage.ToCharArray();
                int    arrayLength      = messageCharArray.Length;
                bool   appendNewline    = false;

                // Trim off last newline, if it exists
                if (arrayLength > 1 && messageCharArray[arrayLength - 2] == '\r' && messageCharArray[arrayLength - 1] == '\n')
                {
                    arrayLength  -= 2;
                    appendNewline = true;
                }

                // Write to the output stream
                m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength);

                // Restore the console back to its previous color scheme
                SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes);

                if (appendNewline)
                {
                    // Write the newline, after changing the color scheme
                    m_consoleOutputWriter.Write(s_windowsNewline, 0, 2);
                }
            }
        }
示例#3
0
        private Color GetLevelColor(String strAttribute, String strValue, List <LevelColors> listLC, bool?bLCAscending)
        {
            if (Global.GetAttributeType(strAttribute) == "STRING")
            {
                LevelColors lcTemp = listLC.Find(delegate(LevelColors lc) { return(lc.m_strLevel == strValue); });
                if (lcTemp != null)
                {
                    return(lcTemp.m_Color);
                }
                else
                {
                    return(System.Drawing.Color.FromArgb(0, Color.Gray));
                }
            }
            else
            {
                float fValue = 0;
                if (strValue == "")
                {
                    return(System.Drawing.Color.FromArgb(0, Color.Gray));
                }
                try
                {
                    fValue = float.Parse(strValue);
                }
                catch
                {
                    return(System.Drawing.Color.FromArgb(0, Color.Gray));
                }

                // Ascending attribute
                if (bLCAscending == true)
                {
                    for (int i = 0; i < listLC.Count - 1; i++)
                    {
                        if (fValue < float.Parse(listLC[i].m_strLevel))
                        {
                            return(listLC[i].m_Color);
                        }
                    }
                }
                // Descending attribute
                else if (bLCAscending == false)
                {
                    for (int i = 0; i < listLC.Count - 1; i++)
                    {
                        if (fValue > float.Parse(listLC[i].m_strLevel))
                        {
                            return(listLC[i].m_Color);
                        }
                    }
                }
                else
                {
                    return(Color.Gray);
                }
                return(listLC[listLC.Count - 1].m_Color);
            }
        }
        private static LevelColors CreateMapping(Level level, Colors foreground, Colors background = 0)
        {
            var levelColor = new LevelColors();

            levelColor.Level     = level;
            levelColor.ForeColor = foreground;
            levelColor.BackColor = background;
            levelColor.ActivateOptions();

            return(levelColor);
        }
示例#5
0
    void ChangeColors()
    {
        var pr     = Random.Range(0f, 1f);
        var colors = new LevelColors()
        {
            LightColor = _lightColors.Evaluate(pr),
            DarkColor  = _darkColors.Evaluate(pr)
        };

        _levelSpawner?.ChangeColor(colors);
        CurrentColors = colors;
    }
示例#6
0
        /// <summary>
        /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(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>
        protected override void Append(LoggingEvent loggingEvent)
        {
            string      text        = RenderLoggingEvent(loggingEvent);
            LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;

            if (levelColors != null)
            {
                text = levelColors.CombinedColor + text;
            }
            text = ((text.Length > 1) ? ((!text.EndsWith("\r\n") && !text.EndsWith("\n\r")) ? ((!text.EndsWith("\n") && !text.EndsWith("\r")) ? (text + "\u001b[0m") : text.Insert(text.Length - 1, "\u001b[0m")) : text.Insert(text.Length - 2, "\u001b[0m")) : ((text[0] != '\n' && text[0] != '\r') ? (text + "\u001b[0m") : ("\u001b[0m" + text)));
            if (m_writeToErrorStream)
            {
                Console.Error.Write(text);
            }
            else
            {
                Console.Write(text);
            }
        }
        protected override void Append(LoggingEvent loggingEvent)
        {
            string      str    = base.RenderLoggingEvent(loggingEvent);
            LevelColors colors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;

            if (colors != null)
            {
                str = colors.CombinedColor + str;
            }
            str = (str.Length <= 1) ? (((str[0] == '\n') || (str[0] == '\r')) ? ("\x001b[0m" + str) : (str + "\x001b[0m")) : ((str.EndsWith("\r\n") || str.EndsWith("\n\r")) ? str.Insert(str.Length - 2, "\x001b[0m") : ((str.EndsWith("\n") || str.EndsWith("\r")) ? str.Insert(str.Length - 1, "\x001b[0m") : (str + "\x001b[0m")));
            if (this.m_writeToErrorStream)
            {
                Console.Error.Write(str);
            }
            else
            {
                Console.Write(str);
            }
        }
        /// <summary>
        /// This method is called by the <see cref="M: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>
        protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        {
            System.IO.TextWriter writer;

            if (this.m_writeToErrorStream)
            {
                writer = Console.Error;
            }
            else
            {
                writer = Console.Out;
            }

            // Reset color
            Console.ResetColor();

            // see if there is a specified lookup
            LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;

            if (levelColors != null)
            {
                // if the backColor has been explicitly set
                if (levelColors.HasBackColor)
                {
                    Console.BackgroundColor = levelColors.BackColor;
                }

                // if the foreColor has been explicitly set
                if (levelColors.HasForeColor)
                {
                    Console.ForegroundColor = levelColors.ForeColor;
                }
            }

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

            // and write it
            writer.Write(strLoggingMessage);

            // Reset color again
            Console.ResetColor();
        }
示例#9
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info;
            IntPtr zero = IntPtr.Zero;

            if (this._writeToErrorStream)
            {
                zero = GetStdHandle(0xfffffff4);
            }
            else
            {
                zero = GetStdHandle(0xfffffff5);
            }
            ushort      attributes = 7;
            LevelColors colors     = _levelMapping.Lookup(loggingEvent.Level) as LevelColors;

            if (colors != null)
            {
                attributes = colors.CombinedColor;
            }

            string str = RenderLoggingEvent(loggingEvent);

            GetConsoleScreenBufferInfo(zero, out console_screen_buffer_info);
            SetConsoleTextAttribute(zero, attributes);
            char[] buffer = str.ToCharArray();
            int    length = buffer.Length;
            bool   flag   = false;

            if (((length > 1) && (buffer[length - 2] == '\r')) && (buffer[length - 1] == '\n'))
            {
                length -= 2;
                flag    = true;
            }

            Console.Write(buffer, 0, length);
            SetConsoleTextAttribute(zero, console_screen_buffer_info.wAttributes);
            if (flag)
            {
                Console.Write(_windowsNewline, 0, 2);
            }
        }
示例#10
0
        /// <summary>
        /// This method is called by the <see cref="M: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>
        protected override void Append(LoggingEvent loggingEvent)
        {
            TextWriter textWriter = (!m_writeToErrorStream) ? Console.Out : Console.Error;

            Console.ResetColor();
            LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;

            if (levelColors != null)
            {
                if (levelColors.HasBackColor)
                {
                    Console.BackgroundColor = levelColors.BackColor;
                }
                if (levelColors.HasForeColor)
                {
                    Console.ForegroundColor = levelColors.ForeColor;
                }
            }
            string value = RenderLoggingEvent(loggingEvent);

            textWriter.Write(value);
            Console.ResetColor();
        }
		/// <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);
		}
        /// <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,
                //     IntPtr.Zero);
                //
                // Instead of calling WriteConsoleW we use WriteFile which
                // handles large buffers correctly. Because WriteFile does not
                // handle the codepage conversion as WriteConsoleW does we
                // need to use a System.IO.StreamWriter with the appropriate
                // Encoding. The WriteFile calls are wrapped up in the
                // System.IO.__ConsoleStream internal class obtained through
                // the System.Console.OpenStandardOutput method.
                //
                // See the ActivateOptions method below for the code that
                // retrieves and wraps the stream.


                // The windows console uses ScrollConsoleScreenBuffer internally to
                // scroll the console buffer when the display buffer of the console
                // has been used up. ScrollConsoleScreenBuffer fills the area uncovered
                // by moving the current content with the background color
                // currently specified on the console. This means that it fills the
                // whole line in front of the cursor position with the current
                // background color.
                // This causes an issue when writing out text with a non default
                // background color. For example; We write a message with a Blue
                // background color and the scrollable area of the console is full.
                // When we write the newline at the end of the message the console
                // needs to scroll the buffer to make space available for the new line.
                // The ScrollConsoleScreenBuffer internals will fill the newly created
                // space with the current background color: Blue.
                // We then change the console color back to default (White text on a
                // Black background). We write some text to the console, the text is
                // written correctly in White with a Black background, however the
                // remainder of the line still has a Blue background.
                //
                // This causes a disjointed appearance to the output where the background
                // colors change.
                //
                // This can be remedied by restoring the console colors before causing
                // the buffer to scroll, i.e. before writing the last newline. This does
                // assume that the rendered message will end with a newline.
                //
                // Therefore we identify a trailing newline in the message and don't
                // write this to the output, then we restore the console color and write
                // a newline. Note that we must AutoFlush before we restore the console
                // color otherwise we will have no effect.
                //
                // There will still be a slight artefact for the last line of the message
                // will have the background extended to the end of the line, however this
                // is unlikely to cause any user issues.
                //
                // Note that none of the above is visible while the console buffer is scrollable
                // within the console window viewport, the effects only arise when the actual
                // buffer is full and needs to be scrolled.

                char[] messageCharArray = strLoggingMessage.ToCharArray();
                int    arrayLength      = messageCharArray.Length;
                bool   appendNewline    = false;

                // Trim off last newline, if it exists
                if (arrayLength > 1 && messageCharArray[arrayLength - 2] == '\r' && messageCharArray[arrayLength - 1] == '\n')
                {
                    arrayLength  -= 2;
                    appendNewline = true;
                }

                // Write to the output stream
                m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength);

                // Restore the console back to its previous color scheme
                SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes);

                if (appendNewline)
                {
                    // Write the newline, after changing the color scheme
                    m_consoleOutputWriter.Write(s_windowsNewline, 0, 2);
                }
            }
        }
示例#13
0
 public new void AddMapping(LevelColors mapping)
 {
     maps.Add(mapping.Level, mapping);
 }
示例#14
0
 public LevCol(LevelColors lc)
 {
     ForeColor = lc.ForeColor;
     BackColor = lc.BackColor;
     ActivateOptions();
 }
示例#15
0
        public static void Setup(Level level, string logPath, string id)
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly());

            hierarchy.Root.RemoveAllAppenders();

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date{HH:mm:ss,fff},%level,%message%newline";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();

            roller.AppendToFile       = false;
            roller.File               = Path.Combine(logPath, $"extractlog_{id}.csv");
            roller.Layout             = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize    = "1MB";
            roller.RollingStyle       = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName  = true;
            roller.ActivateOptions();

            PatternLayout patternLayout2 = new PatternLayout();

            patternLayout2.ConversionPattern = "%level,%message%newline";
            patternLayout2.ActivateOptions();

            ManagedColoredConsoleAppender console = new ManagedColoredConsoleAppender();
            var l1 = new LevelColors
            {
                ForeColor = ConsoleColor.Green,
                Level     = Level.Fatal
            };
            var l2 = new LevelColors
            {
                ForeColor = ConsoleColor.Red,
                Level     = Level.Error
            };
            var l3 = new LevelColors
            {
                ForeColor = ConsoleColor.Yellow,
                Level     = Level.Warn
            };
            var l4 = new LevelColors
            {
                ForeColor = ConsoleColor.White,
                Level     = Level.Info
            };
            var l5 = new LevelColors
            {
                ForeColor = ConsoleColor.White,
                Level     = Level.Debug
            };

            console.AddMapping(l1);
            console.AddMapping(l2);
            console.AddMapping(l3);
            console.AddMapping(l4);
            console.AddMapping(l5);
            console.Layout = patternLayout2;
            console.ActivateOptions();
            hierarchy.Root.Level = level;
            BasicConfigurator.Configure(hierarchy, roller, console);
        }
示例#16
0
 public void ChangeColor(LevelColors c)
 {
     _currentColor = c;
 }
示例#17
0
        /// <summary>
        /// Initializes with a default configuration.
        /// </summary>
        /// <param name="useConsole">是否输出到控制台</param>
        /// <param name="useFile">是否输出到文件</param>
        /// <returns></returns>
        public static ICollection Configure(bool useConsole = false, bool useFile = true)
        {
            // 创建默认工厂
            ILoggerRepository repository;
            string            repositoryName = "log4net-default-repository";  // 默认工厂

            if (LoggerManager.Exists(repositoryName))
            {
                repository = LoggerManager.GetRepository(repositoryName);
            }
            else
            {
                repository = LoggerManager.CreateRepository(repositoryName);
            }

            // 进行配置
            ArrayList arrayList = new ArrayList();

            using (new LogLog.LogReceivedAdapter(arrayList))
            {
                // 日志输出格式, 各种参数设置参见PatternLayout.cs:
                // %m(message):    输出的日志消息;
                // %n(newline):    换行;
                // %d(datetime):   输出当前语句运行的时刻;
                // %r(runtime):    输出程序从运行到执行到当前语句时消耗的毫秒数;
                // %t(threadid):   当前语句所在的线程ID;
                // %p(priority):   日志的当前日志级别;
                // %c(class):      当前日志对象的名称;
                // %L:             输出语句所在的行号;
                // %F:             输出语句所在的文件名;
                // %-10:           表示最小长度为10,如果不够,则用空格填充;
                PatternLayout patternLayout = new PatternLayout();

                //patternLayout.ConversionPattern = "--------时间: %d, 耗时: %r(ms), 类型: %-5p --------%n对象: %c%n消息: %m%n%n";
                //patternLayout.ConversionPattern = "--------时间: %d, 耗时: %r(ms), 类型: %-5p --------%n对象: %c%n消息: %m%n详情: %exception%n%n";
                patternLayout.ConversionPattern = "--------时间: %d, 类型: %-5p --------%n%property{source}%property{class}%property{method}%property{message}%property{detail}%property{data}%n";
                patternLayout.ActivateOptions();

                #region 文件输出器

                RollingFileAppender fileAppender = null;
                if (useFile)
                {
                    fileAppender = new RollingFileAppender();
                    // 日志文件名,
                    // 如果RollingStyle为Composite或Date, 则这里一般设置成目录名, 文件名在DatePattern里设置;
                    // 如果RollingStyle为其他滚动方式, 则必须设置成文件名
                    fileAppender.File = "log\\";

                    // 是否是静态的日志文件名, 即固定的日志文件名称,
                    // 如果你想要动态生成日志文件名,例如将RollingStyle设置成Date或Composite, 以让系统自动生成日志文件的名称,
                    // 那么你必须将staticLogFileName设置成false
                    fileAppender.StaticLogFileName = false;

                    // 日志滚动方式,可设置成:
                    // Size(按文件), 此时你应该将file的值设置成一个固定的名称, 例如: test.log 或 log\\test.log 或 c:\\log\\test.log;
                    // Date(按日期), 此时你应该将file的值设置成一个目录或者空字符串, 如果设置成空字符串, 系统将把日志记录在当前应用程序所在的目录中;
                    // Composite(按日期及文件),默认为Composite
                    fileAppender.RollingStyle = RollingFileAppender.RollingMode.Composite;

                    // 日志文件名格式,
                    // 当RollingStyle为Composite或Date, 在此处设置日志文件名的格式时,
                    // 固定不变的部分用单引号括起来, 其它部分则设置成日期格式
                    fileAppender.DatePattern = "yyyyMMdd'.log'";

                    // 日志记录是否追加到文件,
                    // 默认为true, 表示将记录追加到文件尾部; flase, 表示覆盖已有的日志文件记录
                    fileAppender.AppendToFile = true;

                    // 单个日志文件的最大尺寸,
                    // 可用的单位有: KB | MB | GB, 默认为字节(不带单位)
                    fileAppender.MaximumFileSize = "2MB";

                    //每日最多记录的日志文件个数
                    fileAppender.MaxSizeRollBackups = 10;

                    // 单个日志文件超限后日志备份方式, 默认值为 - 1,
                    // 当日志文件超过MaximumFileSize大小时,系统根据CountDirection的值来备份日志文件:
                    // (1)当此值设置成 > -1时, 则根据file里指定的文件名依次按0,1,2...递增创建日志备份, 直到数量等于MaxSizeRollBackups参数值为止,
                    // 以后的日志记录则会根据maximumFileSize循环写入file, 当filesize > maximumFileSize, 进行一次新的循环写入时, 会将file记录写入备份日志, 并对备份日志进行重新编号;
                    // (2)当此值设置成 <= -1时, 则根据file里指定的文件名依次按0,1,2...递增创建日志备份, 直到数量等于MaxSizeRollBackups参数值为止,
                    // 以后的日志记录则会根据maximumFileSize循环写入file, 当filesize > maximumFileSize, 进行一次新的循环写入时, 不会将file记录写入备份日志, 即备份日志被固化不受影响-- >
                    fileAppender.CountDirection = -1;

                    fileAppender.Layout = patternLayout;
                    fileAppender.ActivateOptions();
                }

                #endregion

                #region 控制台输出器

                //ConsoleAppender consoleAppender = null;
                //if (useConsole)
                //{
                //	consoleAppender = new ConsoleAppender();
                //	consoleAppender.Layout = patternLayout;
                //	consoleAppender.ActivateOptions();
                //}

                #endregion

                #region 颜色控制台输出器

                ManagedColoredConsoleAppender coloredConsoleAppender = null;
                if (useConsole)
                {
                    coloredConsoleAppender = new ManagedColoredConsoleAppender();

                    // 设置日志级别, 默认值为DEBUG,
                    // 级别由低到高依次为: ALL | DEBUG < INFO < WARN < ERROR < FATAL | OFF.其中:
                    // ALL表示记录所有日志;
                    // OFF表示不记录日志, 即关闭日志记录;
                    // 其它则按级别记录,例如级别设置成WARN,则低于WARN级别的INFO和DEBUG日志将不会被记录, 其它依次类推.
                    var debugMap = new LevelColors
                    {
                        ForeColor = ConsoleColor.White,
                        Level     = Level.Debug
                    };

                    var infoMap = new LevelColors
                    {
                        ForeColor = ConsoleColor.Green,
                        Level     = Level.Info
                    };

                    var warnMap = new LevelColors
                    {
                        ForeColor = ConsoleColor.Yellow,
                        Level     = Level.Warn
                    };

                    var errorMap = new LevelColors
                    {
                        ForeColor = ConsoleColor.Red,
                        Level     = Level.Error
                    };

                    var fatalMap = new LevelColors
                    {
                        ForeColor = ConsoleColor.Magenta,
                        Level     = Level.Fatal
                    };

                    debugMap.ActivateOptions();
                    infoMap.ActivateOptions();
                    warnMap.ActivateOptions();
                    errorMap.ActivateOptions();
                    fatalMap.ActivateOptions();
                    coloredConsoleAppender.AddMapping(debugMap);
                    coloredConsoleAppender.AddMapping(warnMap);
                    coloredConsoleAppender.AddMapping(infoMap);
                    coloredConsoleAppender.AddMapping(errorMap);
                    coloredConsoleAppender.AddMapping(fatalMap);

                    coloredConsoleAppender.Layout = patternLayout;
                    coloredConsoleAppender.ActivateOptions();
                }

                #endregion

                var appenders = new List <IAppender>();
                if (useFile)
                {
                    appenders.Add(fileAppender);
                }
                if (useConsole)
                {
                    appenders.Add(coloredConsoleAppender);
                }

                if (appenders.Count > 0)
                {
                    InternalConfigure(repository, appenders.ToArray());
                }
            }
            repository.ConfigurationMessages = arrayList;
            return(arrayList);
        }
示例#18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogMessageEntry"/> struct.
 /// </summary>
 /// <param name="message">The formatted message.</param>
 /// <param name="levelString">The text representation of the <see cref="Microsoft.Extensions.Logging.LogLevel"/>.</param>
 /// <param name="levelColors">The colors to use when displaying this message.</param>
 public LogMessageEntry(string message, string levelString, LevelColors levelColors)
 {
     Message     = message ?? throw new ArgumentNullException(nameof(message));
     LevelString = levelString ?? throw new ArgumentNullException(nameof(levelString));
     LevelColors = levelColors;
 }
示例#19
0
 public void Init(ObjectsPool pool, LevelColors c)
 {
     _currentCollors = c;
     _pool           = pool;
 }
示例#20
0
 /// <summary>
 /// Add a mapping of level to color
 /// </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 colours
 /// for a level.
 /// </para>
 /// </remarks>
 public void AddMapping(LevelColors mapping)
 {
     m_levelMapping.Add(mapping);
 }
示例#21
0
 public void ChangeColor(LevelColors c)
 {
     _spawner.ChangeColor(c);
 }