-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
BaseConsoleLogger.cs
1226 lines (1055 loc) · 44.7 KB
/
BaseConsoleLogger.cs
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using System.Collections;
using System.Globalization;
using System.IO;
using ColorSetter = Microsoft.Build.Logging.ColorSetter;
using ColorResetter = Microsoft.Build.Logging.ColorResetter;
using WriteHandler = Microsoft.Build.Logging.WriteHandler;
using Microsoft.Build.Exceptions;
namespace Microsoft.Build.BackEnd.Logging
{
#region Delegates
internal delegate void WriteLinePrettyFromResourceDelegate(int indentLevel, string resourceString, params object[] args);
#endregion
internal abstract class BaseConsoleLogger : INodeLogger
{
/// <summary>
/// When set, we'll try reading background color.
/// </summary>
private static bool _supportReadingBackgroundColor = true;
#region Properties
/// <summary>
/// Some platforms do not allow getting current background color. There
/// is not way to check, but not-supported exception is thrown. Assume
/// black, but don't crash.
/// </summary>
internal static ConsoleColor BackgroundColor
{
get
{
if (_supportReadingBackgroundColor)
{
try
{
return Console.BackgroundColor;
}
catch (PlatformNotSupportedException)
{
_supportReadingBackgroundColor = false;
}
}
return ConsoleColor.Black;
}
}
/// <summary>
/// Gets or sets the level of detail to show in the event log.
/// </summary>
/// <value>Verbosity level.</value>
public LoggerVerbosity Verbosity { get; set; } = LoggerVerbosity.Normal;
/// <summary>
/// Gets or sets the number of MSBuild processes participating in the build. If greater than 1,
/// include the node ID
/// </summary>
public int NumberOfProcessors { get; set; } = 1;
/// <summary>
/// The console logger takes a single parameter to suppress the output of the errors
/// and warnings summary at the end of a build.
/// </summary>
/// <value>null</value>
public string Parameters { get; set; } = null;
/// <summary>
/// Suppresses the display of project headers. Project headers are
/// displayed by default unless this property is set.
/// </summary>
/// <remarks>This is only needed by the IDE logger.</remarks>
internal bool SkipProjectStartedText { get; set; } = false;
/// <summary>
/// Suppresses the display of error and warnings summary.
/// If null, user has made no indication.
/// </summary>
internal bool? ShowSummary { get; set; }
/// <summary>
/// Provide access to the write hander delegate so that it can be redirected
/// if necessary (e.g. to a file)
/// </summary>
protected internal WriteHandler WriteHandler { get; set; }
#endregion
/// <summary>
/// Parses out the logger parameters from the Parameters string.
/// </summary>
public void ParseParameters()
{
if (Parameters == null) return;
foreach (string parameter in Parameters.Split(parameterDelimiters))
{
if (string.IsNullOrWhiteSpace(parameter)) continue;
string[] parameterAndValue = parameter.Split(s_parameterValueSplitCharacter);
ApplyParameter(parameterAndValue[0], parameterAndValue.Length > 1 ? parameterAndValue[1] : null);
}
}
/// <summary>
/// An implementation of IComparer useful for comparing the keys
/// on DictionaryEntry's
/// </summary>
/// <remarks>Uses CurrentCulture for display purposes</remarks>
internal class DictionaryEntryKeyComparer : IComparer<DictionaryEntry>
{
public int Compare(DictionaryEntry a, DictionaryEntry b)
{
return string.Compare((string) a.Key, (string) b.Key, StringComparison.CurrentCultureIgnoreCase);
}
}
/// <summary>
/// An implementation of IComparer useful for comparing the ItemSpecs
/// on ITaskItem's
/// </summary>
/// <remarks>Uses CurrentCulture for display purposes</remarks>
internal class ITaskItemItemSpecComparer : IComparer
{
public int Compare(Object a, Object b)
{
return String.Compare(
((ITaskItem)a).ItemSpec,
((ITaskItem)b).ItemSpec,
StringComparison.CurrentCultureIgnoreCase);
}
}
/// <summary>
/// Indents the given string by the specified number of spaces.
/// </summary>
/// <param name="s">String to indent.</param>
/// <param name="indent">Depth to indent.</param>
internal string IndentString(string s, int indent)
{
// It's possible the event has a null message
if (s == null) return string.Empty;
// This will never return an empty array. The returned array will always
// have at least one non-null element, even if "s" is totally empty.
String[] subStrings = SplitStringOnNewLines(s);
StringBuilder result = new StringBuilder(
(subStrings.Length * indent) +
(subStrings.Length * Environment.NewLine.Length) +
s.Length);
for (int i = 0; i < subStrings.Length; i++)
{
result.Append(' ', indent).Append(subStrings[i]);
result.AppendLine();
}
return result.ToString();
}
/// <summary>
/// Splits strings on 'newLines' with tolerance for Everett and Dogfood builds.
/// </summary>
/// <param name="s">String to split.</param>
internal static string[] SplitStringOnNewLines(string s)
{
string[] subStrings = s.Split(newLines, StringSplitOptions.None);
return subStrings;
}
/// <summary>
/// Writes a newline to the log.
/// </summary>
internal void WriteNewLine()
{
WriteHandler(Environment.NewLine);
}
/// <summary>
/// Writes a line from a resource string to the log, using the default indentation.
/// </summary>
/// <param name="resourceString"></param>
/// <param name="args"></param>
internal void WriteLinePrettyFromResource(string resourceString, params object[] args)
{
int indentLevel = IsVerbosityAtLeast(LoggerVerbosity.Normal) ? this.currentIndentLevel : 0;
WriteLinePrettyFromResource(indentLevel, resourceString, args);
}
/// <summary>
/// Writes a line from a resource string to the log, using the specified indentation.
/// </summary>
internal void WriteLinePrettyFromResource(int indentLevel, string resourceString, params object[] args)
{
string formattedString = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(resourceString, args);
WriteLinePretty(indentLevel, formattedString);
}
/// <summary>
/// Writes to the log, using the default indentation. Does not
/// terminate with a newline.
/// </summary>
internal void WritePretty(string formattedString)
{
int indentLevel = IsVerbosityAtLeast(LoggerVerbosity.Normal) ? this.currentIndentLevel : 0;
WritePretty(indentLevel, formattedString);
}
/// <summary>
/// If requested, display a performance summary at the end of the build. This
/// shows how much time (and # hits) were spent inside of each project, target,
/// and task.
/// </summary>
internal void ShowPerfSummary()
{
if (projectEvaluationPerformanceCounters != null)
{
setColor(ConsoleColor.Green);
WriteNewLine();
WriteLinePrettyFromResource("ProjectEvaluationPerformanceSummary");
setColor(ConsoleColor.Gray);
DisplayCounters(projectEvaluationPerformanceCounters);
}
// Show project performance summary.
if (projectPerformanceCounters != null)
{
setColor(ConsoleColor.Green);
WriteNewLine();
WriteLinePrettyFromResource("ProjectPerformanceSummary");
setColor(ConsoleColor.Gray);
DisplayCounters(projectPerformanceCounters);
}
// Show target performance summary.
if (targetPerformanceCounters != null)
{
setColor(ConsoleColor.Green);
WriteNewLine();
WriteLinePrettyFromResource("TargetPerformanceSummary");
setColor(ConsoleColor.Gray);
DisplayCounters(targetPerformanceCounters);
}
// Show task performance summary.
if (taskPerformanceCounters != null)
{
setColor(ConsoleColor.Green);
WriteNewLine();
WriteLinePrettyFromResource("TaskPerformanceSummary");
setColor(ConsoleColor.Gray);
DisplayCounters(taskPerformanceCounters);
}
resetColor();
}
/// <summary>
/// Writes to the log, using the specified indentation. Does not
/// terminate with a newline.
/// </summary>
internal void WritePretty(int indentLevel, string formattedString)
{
StringBuilder result = new StringBuilder((indentLevel * tabWidth) + formattedString.Length);
result.Append(' ', indentLevel * tabWidth).Append(formattedString);
WriteHandler(result.ToString());
}
/// <summary>
/// Writes a line to the log, using the default indentation.
/// </summary>
/// <param name="formattedString"></param>
internal void WriteLinePretty(string formattedString)
{
int indentLevel = IsVerbosityAtLeast(LoggerVerbosity.Normal) ? currentIndentLevel : 0;
WriteLinePretty(indentLevel, formattedString);
}
/// <summary>
/// Writes a line to the log, using the specified indentation.
/// </summary>
internal void WriteLinePretty(int indentLevel, string formattedString)
{
indentLevel = indentLevel > 0 ? indentLevel : 0;
WriteHandler(IndentString(formattedString, indentLevel * tabWidth));
}
/// <summary>
/// Check to see what kind of device we are outputting the log to, is it a character device, a file, or something else
/// this can be used by loggers to modify their outputs based on the device they are writing to
/// </summary>
internal void IsRunningWithCharacterFileType()
{
runningWithCharacterFileType = false;
if (NativeMethodsShared.IsWindows)
{
// Get the std out handle
IntPtr stdHandle = NativeMethodsShared.GetStdHandle(NativeMethodsShared.STD_OUTPUT_HANDLE);
if (stdHandle != NativeMethods.InvalidHandle)
{
uint fileType = NativeMethodsShared.GetFileType(stdHandle);
// The std out is a char type(LPT or Console)
runningWithCharacterFileType = (fileType == NativeMethodsShared.FILE_TYPE_CHAR);
}
}
}
/// <summary>
/// Determines whether the current verbosity setting is at least the value
/// passed in.
/// </summary>
internal bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) => Verbosity >= checkVerbosity;
/// <summary>
/// Sets foreground color to color specified
/// </summary>
internal static void SetColor(ConsoleColor c)
{
try
{
Console.ForegroundColor = TransformColor(c, BackgroundColor);
}
catch (IOException)
{
// Does not matter if we cannot set the color
}
}
/// <summary>
/// Resets the color
/// </summary>
internal static void ResetColor()
{
try
{
Console.ResetColor();
}
catch (IOException)
{
// The color could not be reset, no reason to crash
}
}
/// <summary>
/// Sets foreground color to color specified using ANSI escape codes
/// </summary>
/// <param name="c">foreground color</param>
internal static void SetColorAnsi(ConsoleColor c)
{
string colorString = "\x1b[";
switch (c)
{
case ConsoleColor.Black: colorString += "30"; break;
case ConsoleColor.DarkBlue: colorString += "34"; break;
case ConsoleColor.DarkGreen: colorString += "32"; break;
case ConsoleColor.DarkCyan: colorString += "36"; break;
case ConsoleColor.DarkRed: colorString += "31"; break;
case ConsoleColor.DarkMagenta: colorString += "35"; break;
case ConsoleColor.DarkYellow: colorString += "33"; break;
case ConsoleColor.Gray: colorString += "37"; break;
case ConsoleColor.DarkGray: colorString += "30;1"; break;
case ConsoleColor.Blue: colorString += "34;1"; break;
case ConsoleColor.Green: colorString += "32;1"; break;
case ConsoleColor.Cyan: colorString += "36;1"; break;
case ConsoleColor.Red: colorString += "31;1"; break;
case ConsoleColor.Magenta: colorString += "35;1"; break;
case ConsoleColor.Yellow: colorString += "33;1"; break;
case ConsoleColor.White: colorString += "37;1"; break;
default: colorString = ""; break;
}
if ("" != colorString)
{
colorString += "m";
Console.Out.Write(colorString);
}
}
/// <summary>
/// Resets the color using ANSI escape codes
/// </summary>
internal static void ResetColorAnsi()
{
Console.Out.Write("\x1b[m");
}
/// <summary>
/// Changes the foreground color to black if the foreground is the
/// same as the background. Changes the foreground to white if the
/// background is black.
/// </summary>
/// <param name="foreground">foreground color for black</param>
/// <param name="background">current background</param>
internal static ConsoleColor TransformColor(ConsoleColor foreground, ConsoleColor background)
{
ConsoleColor result = foreground; //typically do nothing ...
if (foreground == background)
{
result = background != ConsoleColor.Black ? ConsoleColor.Black : ConsoleColor.Gray;
}
return result;
}
/// <summary>
/// Does nothing, meets the ColorSetter delegate type
/// </summary>
/// <param name="c">foreground color (is ignored)</param>
internal static void DontSetColor(ConsoleColor c)
{
// do nothing...
}
/// <summary>
/// Does nothing, meets the ColorResetter delegate type
/// </summary>
internal static void DontResetColor()
{
// do nothing...
}
internal void InitializeConsoleMethods(LoggerVerbosity logverbosity, WriteHandler logwriter, ColorSetter colorSet, ColorResetter colorReset)
{
Verbosity = logverbosity;
WriteHandler = logwriter;
IsRunningWithCharacterFileType();
// This is a workaround, because the Console class provides no way to check that a color
// can actually be set or not. Color cannot be set if the console has been redirected
// in certain ways (e.g. how BUILD.EXE does it)
bool canSetColor = true;
try
{
ConsoleColor c = BackgroundColor;
}
catch (IOException)
{
// If the attempt to set a color fails with an IO exception then it is
// likely that the console has been redirected in a way that cannot
// cope with color (e.g. BUILD.EXE) so don't try to do color again.
canSetColor = false;
}
if (colorSet != null && canSetColor)
{
this.setColor = colorSet;
}
else
{
this.setColor = DontSetColor;
}
if (colorReset != null && canSetColor)
{
this.resetColor = colorReset;
}
else
{
this.resetColor = DontResetColor;
}
}
/// <summary>
/// Writes out the list of property names and their values.
/// This could be done at any time during the build to show the latest
/// property values, using the cached reference to the list from the
/// appropriate ProjectStarted event.
/// </summary>
/// <param name="properties">List of properties</param>
internal void WriteProperties(List<DictionaryEntry> properties)
{
if (Verbosity == LoggerVerbosity.Diagnostic && showItemAndPropertyList)
{
if (properties.Count == 0)
{
return;
}
OutputProperties(properties);
// Add a blank line
WriteNewLine();
}
}
/// <summary>
/// Writes out the environment as seen on build started.
/// </summary>
internal void WriteEnvironment(IDictionary<string, string> environment)
{
if (environment == null || environment.Count == 0)
{
return;
}
if (Verbosity == LoggerVerbosity.Diagnostic || showEnvironment)
{
OutputEnvironment(environment);
// Add a blank line
WriteNewLine();
}
}
/// <summary>
/// Generate a list which contains the properties referenced by the properties
/// enumerable object
/// </summary>
internal List<DictionaryEntry> ExtractPropertyList(IEnumerable properties)
{
// Gather a sorted list of all the properties.
var list = new List<DictionaryEntry>(properties.FastCountOrZero());
Internal.Utilities.EnumerateProperties(properties, kvp => list.Add(new DictionaryEntry(kvp.Key, kvp.Value)));
list.Sort(new DictionaryEntryKeyComparer());
return list;
}
/// <summary>
/// Write the environment of the build as was captured on the build started event.
/// </summary>
internal virtual void OutputEnvironment(IDictionary<string, string> environment)
{
// Write the banner
setColor(ConsoleColor.Green);
WriteLinePretty(currentIndentLevel, ResourceUtilities.GetResourceString("EnvironmentHeader"));
if (environment != null)
{
// Write each environment value one per line
foreach (KeyValuePair<string, string> entry in environment)
{
setColor(ConsoleColor.Gray);
WritePretty(String.Format(CultureInfo.CurrentCulture, "{0,-30} = ", entry.Key));
setColor(ConsoleColor.DarkGray);
WriteLinePretty(entry.Value);
}
}
resetColor();
}
internal virtual void OutputProperties(List<DictionaryEntry> list)
{
// Write the banner
setColor(ConsoleColor.Green);
WriteLinePretty(currentIndentLevel, ResourceUtilities.GetResourceString("PropertyListHeader"));
// Write each property name and its value, one per line
foreach (DictionaryEntry prop in list)
{
setColor(ConsoleColor.Gray);
WritePretty(String.Format(CultureInfo.CurrentCulture, "{0,-30} = ", prop.Key));
setColor(ConsoleColor.DarkGray);
WriteLinePretty(EscapingUtilities.UnescapeAll((string)prop.Value));
}
resetColor();
}
/// <summary>
/// Writes out the list of item specs and their metadata.
/// This could be done at any time during the build to show the latest
/// items, using the cached reference to the list from the
/// appropriate ProjectStarted event.
/// </summary>
internal void WriteItems(SortedList itemTypes)
{
if (Verbosity != LoggerVerbosity.Diagnostic || !showItemAndPropertyList || itemTypes.Count == 0) return;
// Write the banner
setColor(ConsoleColor.Green);
WriteLinePretty(currentIndentLevel, ResourceUtilities.GetResourceString("ItemListHeader"));
// Write each item type and its itemspec, one per line
foreach (DictionaryEntry entry in itemTypes)
{
string itemType = (string) entry.Key;
ArrayList itemTypeList = (ArrayList) entry.Value;
if (itemTypeList.Count == 0)
{
continue;
}
// Sort the list by itemSpec
itemTypeList.Sort(new ITaskItemItemSpecComparer());
OutputItems(itemType, itemTypeList);
}
// Add a blank line
WriteNewLine();
}
/// <summary>
/// Extract the Items from the enumerable object and return a sorted list containing these items
/// </summary>
internal SortedList ExtractItemList(IEnumerable items)
{
// The "items" list is a flat list of itemtype-ITaskItem pairs.
// We would like to organize the ITaskItems into groups by itemtype.
// Use a SortedList instead of an ArrayList (because we need to lookup fast)
// and instead of a Hashtable (because we need to sort it)
SortedList itemTypes = new SortedList(CaseInsensitiveComparer.Default);
Internal.Utilities.EnumerateItems(items, item =>
{
string key = (string)item.Key;
var bucket = itemTypes[key] as ArrayList;
if (bucket == null)
{
bucket = new ArrayList();
itemTypes[key] = bucket;
}
bucket.Add(item.Value);
});
return itemTypes;
}
/// <summary>
/// Dump the initial items provided.
/// Overridden in ParallelConsoleLogger.
/// </summary>
internal virtual void OutputItems(string itemType, ArrayList itemTypeList)
{
// Write each item, one per line
bool haveWrittenItemType = false;
setColor(ConsoleColor.DarkGray);
foreach (ITaskItem item in itemTypeList)
{
if (!haveWrittenItemType)
{
setColor(ConsoleColor.Gray);
WriteLinePretty(itemType);
haveWrittenItemType = true;
setColor(ConsoleColor.DarkGray);
}
WriteLinePretty(" " /* indent slightly*/ + item.ItemSpec);
IDictionary metadata = item.CloneCustomMetadata();
foreach (DictionaryEntry metadatum in metadata)
{
string valueOrError;
try
{
valueOrError = item.GetMetadata(metadatum.Key as string);
}
catch (InvalidProjectFileException e)
{
valueOrError = e.Message;
}
// A metadatum's "value" is its escaped value, since that's how we represent them internally.
// So unescape before returning to the world at large.
WriteLinePretty(" " + metadatum.Key + " = " + valueOrError);
}
}
resetColor();
}
/// <summary>
/// Returns a performance counter for a given scope (either task name or target name)
/// from the given table.
/// </summary>
/// <param name="scopeName">Task name or target name.</param>
/// <param name="table">Table that has tasks or targets.</param>
/// <returns></returns>
internal static PerformanceCounter GetPerformanceCounter(string scopeName, ref Dictionary<string, PerformanceCounter> table)
{
// Lazily construct the performance counter table.
if (table == null)
{
table = new Dictionary<string, PerformanceCounter>(StringComparer.OrdinalIgnoreCase);
}
// And lazily construct the performance counter itself.
PerformanceCounter counter;
if (!table.TryGetValue(scopeName, out counter))
{
counter = new PerformanceCounter(scopeName);
table[scopeName] = counter;
}
return counter;
}
/// <summary>
/// Display the timings for each counter in the dictionary.
/// </summary>
/// <param name="counters"></param>
internal void DisplayCounters(Dictionary<string, PerformanceCounter> counters)
{
ArrayList perfCounters = new ArrayList(counters.Values.Count);
perfCounters.AddRange(counters.Values);
perfCounters.Sort(PerformanceCounter.DescendingByElapsedTimeComparer);
bool reentrantCounterExists = false;
WriteLinePrettyFromResourceDelegate lineWriter = WriteLinePrettyFromResource;
foreach (PerformanceCounter counter in perfCounters)
{
if (counter.ReenteredScope)
{
reentrantCounterExists = true;
}
counter.PrintCounterMessage(lineWriter, setColor, resetColor);
}
if (reentrantCounterExists)
{
// display an explanation of why there was no value displayed
WriteLinePrettyFromResource(4, "PerformanceReentrancyNote");
}
}
/// <summary>
/// Records performance information consumed by a task or target.
/// </summary>
internal class PerformanceCounter
{
protected string scopeName;
protected int calls;
protected TimeSpan elapsedTime = new TimeSpan(0);
protected bool inScope;
protected DateTime scopeStartTime;
protected bool reenteredScope;
/// <summary>
/// Construct.
/// </summary>
/// <param name="scopeName"></param>
internal PerformanceCounter(string scopeName)
{
this.scopeName = scopeName;
}
/// <summary>
/// Name of the scope.
/// </summary>
internal string ScopeName => scopeName;
/// <summary>
/// Total number of calls so far.
/// </summary>
internal int Calls => calls;
/// <summary>
/// Total accumulated time so far.
/// </summary>
internal TimeSpan ElapsedTime => elapsedTime;
/// <summary>
/// Whether or not this scope was reentered. Timing information is not recorded in these cases.
/// </summary>
internal bool ReenteredScope => reenteredScope;
/// <summary>
/// Whether or not this task or target is executing right now.
/// </summary>
internal bool InScope
{
get { return inScope; }
set
{
if (!reenteredScope)
{
if (InScope && !value)
{
// Edge meaning scope is finishing.
inScope = false;
elapsedTime += (DateTime.Now - scopeStartTime);
}
else if (!InScope && value)
{
// Edge meaning scope is starting.
inScope = true;
++calls;
scopeStartTime = DateTime.Now;
}
else
{
// Should only happen when a scope is reentrant.
// We don't track these numbers.
reenteredScope = true;
}
}
}
}
internal virtual void PrintCounterMessage(WriteLinePrettyFromResourceDelegate writeLinePrettyFromResource, ColorSetter setColor, ColorResetter resetColor)
{
string time;
if (!reenteredScope)
{
// round: sub-millisecond values are not meaningful
time = String.Format(CultureInfo.CurrentCulture,
"{0,5}", Math.Round(elapsedTime.TotalMilliseconds, 0));
}
else
{
// no value available; instead display an asterisk
time = " *";
}
writeLinePrettyFromResource(
2,
"PerformanceLine",
time,
String.Format(CultureInfo.CurrentCulture, "{0,-40}" /* pad to 40 align left */, scopeName),
String.Format(CultureInfo.CurrentCulture, "{0,3}", calls));
}
/// <summary>
/// Returns an IComparer that will put performance counters
/// in descending order by elapsed time.
/// </summary>
internal static IComparer DescendingByElapsedTimeComparer => new DescendingByElapsedTime();
/// <summary>
/// Private IComparer class for sorting performance counters
/// in descending order by elapsed time.
/// </summary>
internal class DescendingByElapsedTime : IComparer
{
/// <summary>
/// Compare two PerformanceCounters.
/// </summary>
/// <param name="o1"></param>
/// <param name="o2"></param>
/// <returns></returns>
public int Compare(object o1, object o2)
{
PerformanceCounter p1 = (PerformanceCounter)o1;
PerformanceCounter p2 = (PerformanceCounter)o2;
// don't compare reentrant counters, time is incorrect
// and we want to sort them first
if (!p1.reenteredScope && !p2.reenteredScope)
{
return TimeSpan.Compare(p1.ElapsedTime, p2.ElapsedTime);
}
else if (p1.Equals(p2))
{
return 0;
}
else if (p1.reenteredScope && !p2.reenteredScope)
{
// p1 was reentrant; sort first
return -1;
}
else if (!p1.reenteredScope && p2.reenteredScope)
{
// p2 was reentrant; sort first
return 1;
}
else
{
// both reentrant; sort stably by another field to avoid throwing
return string.Compare(p1.ScopeName, p2.ScopeName, StringComparison.Ordinal);
}
}
}
}
#region eventHandlers
public virtual void Shutdown()
{
// do nothing
}
internal abstract void ResetConsoleLoggerState();
public virtual void Initialize(IEventSource eventSource, int nodeCount)
{
NumberOfProcessors = nodeCount;
Initialize(eventSource);
}
/// <summary>
/// Signs up the console logger for all build events.
/// </summary>
/// <param name="eventSource">Available events.</param>
public virtual void Initialize(IEventSource eventSource)
{
// Always show perf summary for diagnostic verbosity.
if (IsVerbosityAtLeast(LoggerVerbosity.Diagnostic))
{
this.showPerfSummary = true;
}
ParseParameters();
showTargetOutputs = !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING"));
if (showOnlyWarnings || showOnlyErrors)
{
if (ShowSummary == null)
{
// By default don't show the summary when the showOnlyWarnings / showOnlyErrors is specified.
// However, if the user explicitly specified summary or nosummary, use that.
ShowSummary = false;
}
this.showPerfSummary = false;
}
// If not specifically instructed otherwise, show a summary in normal
// and higher verbosities.
if (ShowSummary == null && IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
ShowSummary = true;
}
// Put this after reading the parameters, since it may want to initialize something
// specially based on some parameter value. For example, choose whether to have a summary, based
// on the verbosity.
ResetConsoleLoggerState();
// Event source is allowed to be null; this allows the logger to be wrapped by a class that wishes
// to call its event handlers directly. The VS HostLogger does this.
if (eventSource != null)
{
eventSource.BuildStarted += BuildStartedHandler;
eventSource.BuildFinished +=BuildFinishedHandler;
eventSource.ProjectStarted += ProjectStartedHandler;
eventSource.ProjectFinished += ProjectFinishedHandler;
eventSource.TargetStarted += TargetStartedHandler;
eventSource.TargetFinished += TargetFinishedHandler;
eventSource.TaskStarted += TaskStartedHandler;
eventSource.TaskFinished += TaskFinishedHandler;
eventSource.ErrorRaised += ErrorHandler;
eventSource.WarningRaised += WarningHandler;
eventSource.MessageRaised += MessageHandler;
eventSource.CustomEventRaised += CustomEventHandler;
eventSource.StatusEventRaised += StatusEventHandler;
}
}
/// <summary>
/// Apply a logger parameter.
/// parameterValue may be null, if there is no parameter value.
/// </summary>
internal virtual bool ApplyParameter(string parameterName, string parameterValue)
{
ErrorUtilities.VerifyThrowArgumentNull(parameterName, nameof(parameterName));
switch (parameterName.ToUpperInvariant())
{
case "PERFORMANCESUMMARY":
showPerfSummary = true;
return true;
case "NOPERFORMANCESUMMARY":
showPerfSummary = false;
return true;
case "NOSUMMARY":
ShowSummary = false;
return true;
case "SUMMARY":
ShowSummary = true;
return true;
case "NOITEMANDPROPERTYLIST":
showItemAndPropertyList = false;
return true;
case "WARNINGSONLY":
showOnlyWarnings = true;
return true;
case "ERRORSONLY":
showOnlyErrors = true;
return true;
case "SHOWENVIRONMENT":
showEnvironment = true;
return true;
case "SHOWPROJECTFILE":
if (parameterValue == null)