jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more 
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. 
// The ASF licenses this file to you 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
 
using System;
using System.Text;
using System.Globalization;
 
using log4net.Core;
using log4net.Layout;
using log4net.Util;
 
namespace log4net.Appender
{
    /// <summary>
    /// Appends logging events to the terminal using ANSI color escape sequences.
    /// </summary>
    /// <remarks>
    /// <para>
    /// AnsiColorTerminalAppender 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 level of message to be set.
    /// </para>
    /// <note>
    /// This appender expects the terminal to understand the VT100 control set 
    /// in order to interpret the color codes. If the terminal or console does not
    /// understand the control codes the behavior is not defined.
    /// </note>
    /// <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 each message to the <c>System.Console.Out</c> or 
    /// <c>System.Console.Error</c> that is set at the time the event is appended.
    /// Therefore it is possible to programmatically redirect the output of this appender 
    /// (for example NUnit does this to capture program output). While this is the desired
    /// behavior of this appender it may have security implications in your application. 
    /// </para>
    /// <para>
    /// When configuring the ANSI colored terminal appender, a 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" />
    ///     <attributes value="Bright,Underscore" />
    /// </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
    /// 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>
    /// </list>
    /// These color values cannot be combined together to make new colors.
    /// </para>
    /// <para>
    /// The attributes can be any combination of the following:
    /// <list type="bullet">
    /// <item><term>Bright</term><description>foreground is brighter</description></item>
    /// <item><term>Dim</term><description>foreground is dimmer</description></item>
    /// <item><term>Underscore</term><description>message is underlined</description></item>
    /// <item><term>Blink</term><description>foreground is blinking (does not work on all terminals)</description></item>
    /// <item><term>Reverse</term><description>foreground and background are reversed</description></item>
    /// <item><term>Hidden</term><description>output is hidden</description></item>
    /// <item><term>Strikethrough</term><description>message has a line through it</description></item>
    /// </list>
    /// While any of these attributes may be combined together not all combinations
    /// work well together, for example setting both <i>Bright</i> and <i>Dim</i> attributes makes
    /// no sense.
    /// </para>
    /// </remarks>
    /// <author>Patrick Wagstrom</author>
    /// <author>Nicko Cadell</author>
    public class AnsiColorTerminalAppender : AppenderSkeleton
    {
        #region Colors Enum
 
        /// <summary>
        /// The enum of possible display attributes
        /// </summary>
        /// <remarks>
        /// <para>
        /// The following flags can be combined together to
        /// form the ANSI color attributes.
        /// </para>
        /// </remarks>
        /// <seealso cref="AnsiColorTerminalAppender" />
        [Flags]
        public enum AnsiAttributes : int
        {
            /// <summary>
            /// text is bright
            /// </summary>
            Bright            = 1,
            /// <summary>
            /// text is dim
            /// </summary>
            Dim                = 2,
 
            /// <summary>
            /// text is underlined
            /// </summary>
            Underscore        = 4,
 
            /// <summary>
            /// text is blinking
            /// </summary>
            /// <remarks>
            /// Not all terminals support this attribute
            /// </remarks>
            Blink            = 8,
 
            /// <summary>
            /// text and background colors are reversed
            /// </summary>
            Reverse            = 16,
 
            /// <summary>
            /// text is hidden
            /// </summary>
            Hidden            = 32,
 
            /// <summary>
            /// text is displayed with a strikethrough
            /// </summary>
            Strikethrough    = 64
        }
 
        /// <summary>
        /// The enum of possible foreground or background color values for 
        /// use with the color mapping method
        /// </summary>
        /// <remarks>
        /// <para>
        /// The output can be in one for the following ANSI colors.
        /// </para>
        /// </remarks>
        /// <seealso cref="AnsiColorTerminalAppender" />
        public enum AnsiColor : int
        {
            /// <summary>
            /// color is black
            /// </summary>
            Black    = 0,
 
            /// <summary>
            /// color is red
            /// </summary>
            Red        = 1,
 
            /// <summary>
            /// color is green
            /// </summary>
            Green    = 2,
 
            /// <summary>
            /// color is yellow
            /// </summary>
            Yellow    = 3,
 
            /// <summary>
            /// color is blue
            /// </summary>
            Blue    = 4,
 
            /// <summary>
            /// color is magenta
            /// </summary>
            Magenta    = 5,
 
            /// <summary>
            /// color is cyan
            /// </summary>
            Cyan    = 6,
 
            /// <summary>
            /// color is white
            /// </summary>
            White    = 7
        }
 
        #endregion
 
        #region Public Instance Constructors
 
        /// <summary>
        /// Initializes a new instance of the <see cref="AnsiColorTerminalAppender" /> class.
        /// </summary>
        /// <remarks>
        /// The instance of the <see cref="AnsiColorTerminalAppender" /> class is set up to write 
        /// to the standard output stream.
        /// </remarks>
        public AnsiColorTerminalAppender() 
        {
        }
 
        #endregion Public Instance Constructors
 
        #region Public Instance Properties
 
        /// <summary>
        /// Target is the value of the console output stream.
        /// </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 trimmedTargetName = value.Trim();
                
                if (string.Compare(ConsoleError, trimmedTargetName, true, CultureInfo.InvariantCulture) == 0) 
                {
                    m_writeToErrorStream = true;
                } 
                else 
                {
                    m_writeToErrorStream = false;
                }
            }
        }
 
        /// <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);
        }
 
        #endregion Public Instance Properties
 
        #region Override implementation of AppenderSkeleton
 
        /// <summary>
        /// This method is called by the <see cref="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>
        override protected 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
        
        }
 
        /// <summary>
        /// This appender requires a <see cref="Layout"/> to be set.
        /// </summary>
        /// <value><c>true</c></value>
        /// <remarks>
        /// <para>
        /// This appender requires a <see cref="Layout"/> to be set.
        /// </para>
        /// </remarks>
        override protected bool RequiresLayout
        {
            get { return true; }
        }
 
        /// <summary>
        /// Initialize the options for this appender
        /// </summary>
        /// <remarks>
        /// <para>
        /// Initialize the level to color mappings set on this appender.
        /// </para>
        /// </remarks>
        public override void ActivateOptions()
        {
            base.ActivateOptions();
            m_levelMapping.ActivateOptions();
        }
 
        #endregion Override implementation of AppenderSkeleton
 
        #region Public Static Fields
 
        /// <summary>
        /// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console 
        /// standard output stream.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console 
        /// standard output stream.
        /// </para>
        /// </remarks>
        public const string ConsoleOut = "Console.Out";
 
        /// <summary>
        /// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console 
        /// standard error output stream.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console 
        /// standard error output stream.
        /// </para>
        /// </remarks>
        public const string ConsoleError = "Console.Error";
 
        #endregion Public Static Fields
 
        #region Private Instances Fields
 
        /// <summary>
        /// Flag to write output to the error stream rather than the standard output stream
        /// </summary>
        private bool m_writeToErrorStream = false;
 
        /// <summary>
        /// Mapping from level object to color value
        /// </summary>
        private LevelMapping m_levelMapping = new LevelMapping();
 
        /// <summary>
        /// Ansi code to reset terminal
        /// </summary>
        private const string PostEventCodes = "\x1b[0m";
 
        #endregion Private Instances Fields
 
        #region LevelColors LevelMapping Entry
 
        /// <summary>
        /// A class to act as a mapping between the level that a logging call is made at and
        /// the color it should be displayed as.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Defines the mapping between a level and the color it should be displayed in.
        /// </para>
        /// </remarks>
        public class LevelColors : LevelMappingEntry
        {
            private AnsiColor m_foreColor;
            private AnsiColor m_backColor;
            private AnsiAttributes m_attributes;
            private string m_combinedColor = "";
 
            /// <summary>
            /// The mapped foreground color for the specified level
            /// </summary>
            /// <remarks>
            /// <para>
            /// Required property.
            /// The mapped foreground color for the specified level
            /// </para>
            /// </remarks>
            public AnsiColor ForeColor
            {
                get { return m_foreColor; }
                set { m_foreColor = value; }
            }
 
            /// <summary>
            /// The mapped background color for the specified level
            /// </summary>
            /// <remarks>
            /// <para>
            /// Required property.
            /// The mapped background color for the specified level
            /// </para>
            /// </remarks>
            public AnsiColor BackColor
            {
                get { return m_backColor; }
                set { m_backColor = value; }
            }
 
            /// <summary>
            /// The color attributes for the specified level
            /// </summary>
            /// <remarks>
            /// <para>
            /// Required property.
            /// The color attributes for the specified level
            /// </para>
            /// </remarks>
            public AnsiAttributes Attributes
            {
                get { return m_attributes; }
                set { m_attributes = value; }
            }
 
            /// <summary>
            /// Initialize the options for the object
            /// </summary>
            /// <remarks>
            /// <para>
            /// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together
            /// and append the attributes.
            /// </para>
            /// </remarks>
            public override void ActivateOptions()
            {
                base.ActivateOptions();
 
                StringBuilder buf = new StringBuilder();
 
                // Reset any existing codes
                buf.Append("\x1b[0;");
 
                // set the foreground color
                buf.Append(30 + (int)m_foreColor);
                buf.Append(';');
 
                // set the background color
                buf.Append(40 + (int)m_backColor);
 
                // set the attributes
                if ((m_attributes & AnsiAttributes.Bright) > 0)
                {
                    buf.Append(";1");
                }
                if ((m_attributes & AnsiAttributes.Dim) > 0)
                {
                    buf.Append(";2");
                }
                if ((m_attributes & AnsiAttributes.Underscore) > 0)
                {
                    buf.Append(";4");
                }
                if ((m_attributes & AnsiAttributes.Blink) > 0)
                {
                    buf.Append(";5");
                }
                if ((m_attributes & AnsiAttributes.Reverse) > 0)
                {
                    buf.Append(";7");
                }
                if ((m_attributes & AnsiAttributes.Hidden) > 0)
                {
                    buf.Append(";8");
                }
                if ((m_attributes & AnsiAttributes.Strikethrough) > 0)
                {
                    buf.Append(";9");
                }
 
                buf.Append('m');
 
                m_combinedColor = buf.ToString();
            }
 
            /// <summary>
            /// The combined <see cref="ForeColor"/>, <see cref="BackColor"/> and
            /// <see cref="Attributes"/> suitable for setting the ansi terminal color.
            /// </summary>
            internal string CombinedColor
            {
                get { return m_combinedColor; }
            }
        }
 
        #endregion // LevelColors LevelMapping Entry
    }
}