-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathParallelConsoleLogger.cs
1793 lines (1577 loc) · 79 KB
/
ParallelConsoleLogger.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using ColorResetter = Microsoft.Build.Logging.ColorResetter;
using ColorSetter = Microsoft.Build.Logging.ColorSetter;
using WriteHandler = Microsoft.Build.Logging.WriteHandler;
#nullable disable
namespace Microsoft.Build.BackEnd.Logging
{
/// <summary>
/// This class implements the default logger that outputs event data
/// to the console (stdout).
/// </summary>
/// <remarks>This class is not thread safe.</remarks>
internal class ParallelConsoleLogger : BaseConsoleLogger
{
/// <summary>
/// Associate a (nodeID and project_context_id) to a target framework.
/// </summary>
internal Dictionary<(int nodeId, int contextId), string> propertyOutputMap = new Dictionary<(int nodeId, int contextId), string>();
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public ParallelConsoleLogger()
: this(LoggerVerbosity.Normal)
{
// do nothing
}
/// <summary>
/// Create a logger instance with a specific verbosity. This logs to
/// the default console.
/// </summary>
public ParallelConsoleLogger(LoggerVerbosity verbosity)
:
this
(
verbosity,
new WriteHandler(Console.Out.Write),
new ColorSetter(SetColor),
new ColorResetter(ResetColor))
{
// do nothing
}
/// <summary>
/// Initializes the logger, with alternate output handlers.
/// </summary>
public ParallelConsoleLogger(
LoggerVerbosity verbosity,
WriteHandler write,
ColorSetter colorSet,
ColorResetter colorReset)
{
InitializeConsoleMethods(verbosity, write, colorSet, colorReset);
_deferredMessages = new Dictionary<BuildEventContext, List<BuildMessageEventArgs>>(s_compareContextNodeId);
_buildEventManager = new BuildEventManager();
}
/// <summary>
/// Check to see if the console is going to a char output such as a console,printer or com port, or if it going to a file
/// </summary>
private void CheckIfOutputSupportsAlignment()
{
_alignMessages = false;
_bufferWidth = -1;
// If forceNoAlign is set there is no point getting the console width as there will be no aligning of the text
if (!_forceNoAlign)
{
if (runningWithCharacterFileType)
{
// Get the size of the console buffer so messages can be formatted to the console width
try
{
_bufferWidth = ConsoleConfiguration.BufferWidth;
_alignMessages = true;
}
catch (Exception)
{
// on Win8 machines while in IDE Console.BufferWidth will throw (while it talks to native console it gets "operation aborted" native error)
// this is probably temporary workaround till we understand what is the reason for that exception
_alignMessages = false;
}
}
else
{
_alignMessages = false;
}
}
_consoleOutputAligner = new ConsoleOutputAligner(_bufferWidth, _alignMessages, (IStringBuilderProvider)this);
}
#endregion
#region Methods
/// <summary>
/// Allows the logger to take action based on a parameter passed on when initializing the logger
/// </summary>
internal override bool ApplyParameter(string parameterName, string parameterValue)
{
if (base.ApplyParameter(parameterName, parameterValue))
{
return true;
}
if (String.Equals(parameterName, "SHOWCOMMANDLINE", StringComparison.OrdinalIgnoreCase))
{
if (String.IsNullOrEmpty(parameterValue))
{
_showCommandLine = true;
}
else
{
try
{
_showCommandLine = ConversionUtilities.ConvertStringToBool(parameterValue);
}
catch (ArgumentException)
{
// For compatibility, if the string is not a boolean, just ignore it
_showCommandLine = false;
}
}
return true;
}
else if (String.Equals(parameterName, "SHOWTIMESTAMP", StringComparison.OrdinalIgnoreCase))
{
_showTimeStamp = true;
return true;
}
else if (String.Equals(parameterName, "SHOWEVENTID", StringComparison.OrdinalIgnoreCase))
{
_showEventId = true;
return true;
}
else if (String.Equals(parameterName, "FORCENOALIGN", StringComparison.OrdinalIgnoreCase))
{
_forceNoAlign = true;
_alignMessages = false;
return true;
}
return false;
}
public override void Initialize(IEventSource eventSource)
{
// If the logger is being used in singleproc do not show EventId after each message unless it is set as part of a console parameter
if (NumberOfProcessors == 1)
{
_showEventId = false;
}
// Parameters are parsed in Initialize
base.Initialize(eventSource);
CheckIfOutputSupportsAlignment();
}
/// <summary>
/// Keep track of the last event displayed so target names can be displayed at the correct time
/// </summary>
private void ShownBuildEventContext(BuildEventContext e)
{
_lastDisplayedBuildEventContext = e;
}
/// <summary>
/// Reset the states of per-build member variables
/// VSW#516376
/// </summary>
internal override void ResetConsoleLoggerState()
{
if (ShowSummary == true)
{
errorList = new List<BuildErrorEventArgs>();
warningList = new List<BuildWarningEventArgs>();
}
else
{
errorList = null;
warningList = null;
}
errorCount = 0;
warningCount = 0;
projectPerformanceCounters = null;
targetPerformanceCounters = null;
taskPerformanceCounters = null;
_hasBuildStarted = false;
// Reset the data structures created when the logger was created
propertyOutputMap = new Dictionary<(int, int), string>();
_buildEventManager = new BuildEventManager();
_deferredMessages = new Dictionary<BuildEventContext, List<BuildMessageEventArgs>>(s_compareContextNodeId);
_prefixWidth = 0;
_lastDisplayedBuildEventContext = null;
}
/// <summary>
/// Handler for build started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void BuildStartedHandler(object sender, BuildStartedEventArgs e)
{
buildStarted = e.Timestamp;
_hasBuildStarted = true;
if (showOnlyErrors || showOnlyWarnings)
{
return;
}
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
WriteLinePrettyFromResource("BuildStartedWithTime", e.Timestamp);
}
if (Traits.LogAllEnvironmentVariables)
{
WriteEnvironment(e.BuildEnvironment);
}
else
{
WriteEnvironment(e.BuildEnvironment?.Where(kvp => EnvironmentUtilities.IsWellKnownEnvironmentDerivedProperty(kvp.Key)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
}
}
/// <summary>
/// Handler for build finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs e)
{
// If for some reason we have deferred messages at the end of the build they should be displayed
// so that the reason why they are still buffered can be determined.
if (!showOnlyErrors && !showOnlyWarnings && _deferredMessages.Count > 0)
{
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
// Print out all of the deferred messages
WriteLinePrettyFromResource("DeferredMessages");
foreach (List<BuildMessageEventArgs> messageList in _deferredMessages.Values)
{
foreach (BuildMessageEventArgs message in messageList)
{
PrintMessage(message, false);
}
}
}
}
// Show the performance summary if the verbosity is diagnostic or the user specifically asked for it
// with a logger parameter.
if (this.showPerfSummary)
{
ShowPerfSummary();
}
// Write the "Build Finished" event if verbosity is normal, detailed or diagnostic or the user
// specified to show the summary.
if (ShowSummary == true)
{
if (e.Succeeded)
{
setColor(ConsoleColor.Green);
}
// Write the "Build Finished" event.
WriteNewLine();
WriteLinePretty(e.Message);
resetColor();
}
// The decision whether or not to show a summary at this verbosity
// was made during initialization. We just do what we're told.
if (ShowSummary == true)
{
// We can't display a nice nested summary unless we're at Normal or above,
// since we need to have gotten TargetStarted events, which aren't forwarded otherwise.
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
ShowNestedErrorWarningSummary();
}
else
{
ShowFlatErrorWarningSummary();
}
// Emit text like:
// 1 Warning(s)
// 0 Error(s)
// Don't color the line if it's zero. (Per Whidbey behavior.)
if (warningCount > 0)
{
setColor(ConsoleColor.Yellow);
}
WriteLinePrettyFromResource(2, "WarningCount", warningCount);
resetColor();
if (errorCount > 0)
{
setColor(ConsoleColor.Red);
}
WriteLinePrettyFromResource(2, "ErrorCount", errorCount);
resetColor();
}
// Show build time if verbosity is normal, detailed or diagnostic or the user specified to
// show the summary.
if (ShowSummary == true)
{
// The time elapsed is the difference between when the BuildStartedEventArg
// was created and when the BuildFinishedEventArg was created
string timeElapsed = LogFormatter.FormatTimeSpan(e.Timestamp - buildStarted);
WriteNewLine();
WriteLinePrettyFromResource("TimeElapsed", timeElapsed);
}
ResetConsoleLoggerState();
CheckIfOutputSupportsAlignment();
}
/// <summary>
/// At the end of the build, repeats the errors and warnings that occurred
/// during the build, and displays the error count and warning count.
/// Does this in a "flat" style, without context.
/// </summary>
private void ShowFlatErrorWarningSummary()
{
if (warningList.Count == 0 && errorList.Count == 0)
{
return;
}
// If we're showing only warnings and/or errors, don't summarize.
// This is the buildc.err case. There's no point summarizing since we'd just
// repeat the entire log content again.
if (showOnlyErrors || showOnlyWarnings)
{
return;
}
// Make some effort to distinguish this summary from the output above, since otherwise
// it's not clear in lower verbosities
WriteNewLine();
if (warningList.Count > 0)
{
setColor(ConsoleColor.Yellow);
foreach (BuildWarningEventArgs warning in warningList)
{
WriteMessageAligned(EventArgsFormatting.FormatEventMessage(warning, showProjectFile, FindLogOutputProperties(warning)), true);
}
}
if (errorList.Count > 0)
{
setColor(ConsoleColor.Red);
foreach (BuildErrorEventArgs error in errorList)
{
WriteMessageAligned(EventArgsFormatting.FormatEventMessage(error, showProjectFile, FindLogOutputProperties(error)), true);
}
}
resetColor();
}
/// <summary>
/// At the end of the build, repeats the errors and warnings that occurred
/// during the build, and displays the error count and warning count.
/// Does this in a "nested" style.
/// </summary>
private void ShowNestedErrorWarningSummary()
{
if (warningList.Count == 0 && errorList.Count == 0)
{
return;
}
// If we're showing only warnings and/or errors, don't summarize.
// This is the buildc.err case. There's no point summarizing since we'd just
// repeat the entire log content again.
if (showOnlyErrors || showOnlyWarnings)
{
return;
}
if (warningCount > 0)
{
setColor(ConsoleColor.Yellow);
ShowErrorWarningSummary(warningList);
}
if (errorCount > 0)
{
setColor(ConsoleColor.Red);
ShowErrorWarningSummary(errorList);
}
resetColor();
}
private void ShowErrorWarningSummary(IEnumerable<BuildEventArgs> listToProcess)
{
// Group the build warning event args based on the entry point and the target in which the warning occurred
var groupByProjectEntryPoint = new Dictionary<ErrorWarningSummaryDictionaryKey, List<BuildEventArgs>>();
// Loop through each of the warnings and put them into the correct buckets
foreach (BuildEventArgs errorWarningEventArgs in listToProcess)
{
// Target event may be null for a couple of reasons:
// 1) If the event was from a project load, or engine
// 2) If the flushing of the event queue for each request and result is turned off
// as this could cause errors and warnings to be seen by the logger after the target finished event
// which would cause the error or warning to have no matching target started event as they are removed
// when a target finished event is logged.
// 3) On NORMAL verbosity if the error or warning occurs in a project load then the error or warning and the target started event will be forwarded to
// different forwarding loggers which cannot communicate to each other, meaning there will be no matching target started event logged
// as the forwarding logger did not know to forward the target started event
string targetName = null;
TargetStartedEventMinimumFields targetEvent = _buildEventManager.GetTargetStartedEvent(errorWarningEventArgs.BuildEventContext);
if (targetEvent != null)
{
targetName = targetEvent.TargetName;
}
// Create a new key from the error event context and the target where the error happened
ErrorWarningSummaryDictionaryKey key = new ErrorWarningSummaryDictionaryKey(errorWarningEventArgs.BuildEventContext, targetName);
// Check to see if there is a bucket for the warning
// If there is no bucket create a new one which contains a list of all the errors which
// happened for a given buildEventContext / target
if (!groupByProjectEntryPoint.TryGetValue(key, out var errorWarningEventListByTarget))
{
// happened for a given buildEventContext / target
errorWarningEventListByTarget = new List<BuildEventArgs>();
groupByProjectEntryPoint.Add(key, errorWarningEventListByTarget);
}
// Add the error event to the correct bucket
errorWarningEventListByTarget.Add(errorWarningEventArgs);
}
BuildEventContext previousEntryPoint = null;
string previousTarget = null;
// Loop through each of the bucket and print out the stack trace information for the errors
foreach (KeyValuePair<ErrorWarningSummaryDictionaryKey, List<BuildEventArgs>> valuePair in groupByProjectEntryPoint)
{
// If the project entry point where the error occurred is the same as the previous message do not print the
// stack trace again
if (previousEntryPoint != valuePair.Key.EntryPointContext)
{
WriteNewLine();
foreach (string s in _buildEventManager.ProjectCallStackFromProject(valuePair.Key.EntryPointContext))
{
WriteMessageAligned(s, false);
}
previousEntryPoint = valuePair.Key.EntryPointContext;
}
// If the target where the error occurred is the same as the previous message do not print the location
// where the error occurred again
if (!String.Equals(previousTarget, valuePair.Key.TargetName, StringComparison.OrdinalIgnoreCase))
{
// If no targetName was specified then do not show the target where the error occurred
if (!string.IsNullOrEmpty(valuePair.Key.TargetName))
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ErrorWarningInTarget", valuePair.Key.TargetName), false);
}
previousTarget = valuePair.Key.TargetName;
}
// Print out all of the errors under the ProjectEntryPoint / target
foreach (BuildEventArgs errorWarningEvent in valuePair.Value)
{
if (errorWarningEvent is BuildErrorEventArgs buildErrorEventArgs)
{
WriteMessageAligned(" " + EventArgsFormatting.FormatEventMessage(buildErrorEventArgs, showProjectFile, FindLogOutputProperties(errorWarningEvent)), false);
}
else if (errorWarningEvent is BuildWarningEventArgs buildWarningEventArgs)
{
WriteMessageAligned(" " + EventArgsFormatting.FormatEventMessage(buildWarningEventArgs, showProjectFile, FindLogOutputProperties(errorWarningEvent)), false);
}
}
WriteNewLine();
}
}
/// <summary>
/// Handler for project started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void ProjectStartedHandler(object sender, ProjectStartedEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext");
ErrorUtilities.VerifyThrowArgumentNull(e.ParentProjectBuildEventContext, "ParentProjectBuildEventContext");
// Add the project to the BuildManager so we can use the start information later in the build process
_buildEventManager.AddProjectStartedEvent(e, _showTimeStamp || IsVerbosityAtLeast(LoggerVerbosity.Detailed));
if (this.showPerfSummary)
{
// Create a new project performance counter for this project
MPPerformanceCounter counter = GetPerformanceCounter(e.ProjectFile, ref projectPerformanceCounters);
counter.AddEventStarted(e.TargetNames, e.BuildEventContext, e.Timestamp, s_compareContextNodeId);
}
// If there were deferred messages then we should show them now, this will cause the project started event to be shown properly
if (_deferredMessages.TryGetValue(e.BuildEventContext, out var deferredMessages))
{
if (!showOnlyErrors && !showOnlyWarnings)
{
foreach (BuildMessageEventArgs message in deferredMessages)
{
// This will display the project started event before the messages is shown
this.MessageHandler(sender, message);
}
}
_deferredMessages.Remove(e.BuildEventContext);
}
// If we are in diagnostic and are going to show items, show the project started event
// along with the items. The project started event will only be shown if it has not been shown before
if (Verbosity == LoggerVerbosity.Diagnostic && showItemAndPropertyList)
{
// Show the deferredProjectStartedEvent
if (!showOnlyErrors && !showOnlyWarnings)
{
DisplayDeferredProjectStartedEvent(e.BuildEventContext);
}
if (e.Properties != null)
{
WriteProperties(e, e.Properties);
}
if (e.Items != null)
{
WriteItems(e, e.Items);
}
}
var projectKey = (e.BuildEventContext.NodeId, e.BuildEventContext.ProjectContextId);
// If the value is available at all, it will be either in the items
// from ProjectStarted (old behavior), or the items from ProjectEvaluationFinished (new behavior).
// First try the old behavior, and fallback to the new behavior.
var result = ReadProjectConfigurationDescription(e.Items);
if (result != null)
{
// Found the items directly on ProjectStarted
propertyOutputMap[projectKey] = result;
}
else
{
// Try to see if we saw the items on the corresponding ProjectEvaluationFinished
var evaluationKey = GetEvaluationKey(e.BuildEventContext);
// if the value was set from ProjectEvaluationFinished, copy it into the entry
// for this project
if (propertyOutputMap.TryGetValue(evaluationKey, out string value))
{
propertyOutputMap[projectKey] = value;
}
}
}
private string ReadProjectConfigurationDescription(IEnumerable items)
{
if (items == null)
{
return null;
}
ReuseableStringBuilder projectConfigurationDescription = null;
bool descriptionEmpty = true;
Internal.Utilities.EnumerateItems(items, item =>
{
// Determine if the LogOutputProperties item has been used.
if (string.Equals((string)item.Key, ItemMetadataNames.ProjectConfigurationDescription, StringComparison.OrdinalIgnoreCase))
{
if (projectConfigurationDescription == null)
{
projectConfigurationDescription = new ReuseableStringBuilder();
}
string itemSpec = item.Value switch
{
IItem iitem => iitem.EvaluatedInclude, // ProjectItem
ITaskItem taskItem => taskItem.ItemSpec, // ProjectItemInstance
_ => throw new NotSupportedException(Convert.ToString(item.Value))
};
// Add the item value to the string to be printed in error/warning messages.
if (!descriptionEmpty)
{
projectConfigurationDescription.Append(" ");
}
projectConfigurationDescription.Append(itemSpec);
descriptionEmpty = false;
}
});
if (projectConfigurationDescription != null)
{
var result = projectConfigurationDescription.ToString();
(projectConfigurationDescription as IDisposable)?.Dispose();
return result;
}
return null;
}
/// <summary>
/// In case the items are stored on ProjectEvaluationFinishedEventArgs
/// (new behavior), we first store the value per evaluation, and then
/// in ProjectStarted, find the value from the project's evaluation
/// and use that.
/// </summary>
private (int, int) GetEvaluationKey(BuildEventContext buildEventContext)
// note that we use a negative number for evaluations so that we don't conflict
// with project context ids.
=> (buildEventContext.NodeId, -buildEventContext.EvaluationId);
/// <summary>
/// Handler for project finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext");
// Get the project started event so we can use its information to properly display a project finished event
ProjectStartedEventMinimumFields startedEvent = _buildEventManager.GetProjectStartedEvent(e.BuildEventContext);
ErrorUtilities.VerifyThrow(startedEvent != null, "Project finished event for {0} received without matching start event", e.ProjectFile);
if (this.showPerfSummary)
{
// Stop the performance counter which was created in the project started event handler
MPPerformanceCounter counter = GetPerformanceCounter(e.ProjectFile, ref projectPerformanceCounters);
counter.AddEventFinished(startedEvent.TargetNames, e.BuildEventContext, e.Timestamp);
}
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
// Only want to show the project finished event if a project started event has been shown
if (startedEvent.ShowProjectFinishedEvent)
{
_lastProjectFullKey = GetFullProjectKey(e.BuildEventContext);
if (!showOnlyErrors && !showOnlyWarnings)
{
WriteLinePrefix(e.BuildEventContext, e.Timestamp, false);
setColor(ConsoleColor.Cyan);
// In the project finished message the targets which were built and the project which was built
// should be shown
string targets = startedEvent.TargetNames;
string projectName = startedEvent.ProjectFile ?? string.Empty;
// Show which targets were built as part of this project
if (string.IsNullOrEmpty(targets))
{
if (e.Succeeded)
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ProjectFinishedPrefixWithDefaultTargetsMultiProc", projectName), true);
}
else
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ProjectFinishedPrefixWithDefaultTargetsMultiProcFailed", projectName), true);
}
}
else
{
if (e.Succeeded)
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ProjectFinishedPrefixWithTargetNamesMultiProc", projectName, targets), true);
}
else
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ProjectFinishedPrefixWithTargetNamesMultiProcFailed", projectName, targets), true);
}
}
// In single proc only make a space between the project done event and the next line, this
// is to increase the readability on the single proc log when there are a number of done events
// or a mix of done events and project started events. Also only do this on the console and not any log file.
if (NumberOfProcessors == 1 && runningWithCharacterFileType)
{
WriteNewLine();
}
}
ShownBuildEventContext(e.BuildEventContext);
resetColor();
}
}
// We are done with the project started event if the project has finished building, remove its reference
_buildEventManager.RemoveProjectStartedEvent(e.BuildEventContext);
}
/// <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="e">A <see cref="BuildEventArgs"/> object containing information about the build event.</param>
/// <param name="properties">List of properties</param>
internal void WriteProperties(BuildEventArgs e, IEnumerable properties)
{
if (showOnlyErrors || showOnlyWarnings)
{
return;
}
var propertyList = ExtractPropertyList(properties);
// if there are no properties to display return out of the method and dont print out anything related to displaying
// the properties, this includes the multiproc prefix information or the Initial properties header
if (propertyList.Count == 0)
{
return;
}
WriteLinePrefix(e.BuildEventContext, e.Timestamp, false);
WriteProperties(propertyList);
ShownBuildEventContext(e.BuildEventContext);
}
internal override void OutputProperties(List<DictionaryEntry> list)
{
// Write the banner
setColor(ConsoleColor.Green);
WriteMessageAligned(ResourceUtilities.GetResourceString("PropertyListHeader"), true);
// Write each property name and its value, one per line
foreach (DictionaryEntry prop in list)
{
setColor(ConsoleColor.Gray);
string propertyString = $"{prop.Key} = {EscapingUtilities.UnescapeAll((string)(prop.Value))}";
WriteMessageAligned(propertyString, false);
}
resetColor();
}
/// <summary>
/// Write the environment strings to the console.
/// </summary>
internal override void OutputEnvironment(IDictionary<string, string> environment)
{
// Write the banner
setColor(ConsoleColor.Green);
WriteMessageAligned(ResourceUtilities.GetResourceString("EnvironmentHeader"), true);
if (environment != null)
{
// Write each property name and its value, one per line
foreach (KeyValuePair<string, string> entry in environment)
{
setColor(ConsoleColor.Gray);
string environmentMessage = $"{entry.Key} = {entry.Value}";
WriteMessageAligned(environmentMessage, false);
}
}
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>
/// <param name="e">A <see cref="BuildEventArgs"/> object containing information about the build event.</param>
/// <param name="items">List of items</param>
internal void WriteItems(BuildEventArgs e, IEnumerable items)
{
if (showOnlyErrors || showOnlyWarnings)
{
return;
}
SortedList itemList = ExtractItemList(items);
// If there are no Items to display return out of the method and don't print out anything related to displaying
// the items, this includes the multiproc prefix information or the Initial items header
if (itemList.Count == 0)
{
return;
}
WriteLinePrefix(e.BuildEventContext, e.Timestamp, false);
WriteItems(itemList);
ShownBuildEventContext(e.BuildEventContext);
}
protected override void WriteItemType(string itemType)
{
setColor(ConsoleColor.DarkGray);
WriteMessageAligned(itemType, prefixAlreadyWritten: false);
setColor(ConsoleColor.Gray);
}
protected override void WriteItemSpec(string itemSpec)
{
WriteMessageAligned(new string(' ', 2 * tabWidth) + itemSpec, prefixAlreadyWritten: false);
}
protected override void WriteMetadata(string name, string value)
{
WriteMessageAligned($"{new string(' ', 4 * tabWidth)}{name} = {value}", prefixAlreadyWritten: false);
}
/// <summary>
/// Handler for target started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void TargetStartedHandler(object sender, TargetStartedEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext");
// Add the target started information to the buildEventManager so its information can be used
// later in the build
_buildEventManager.AddTargetStartedEvent(e, _showTimeStamp || IsVerbosityAtLeast(LoggerVerbosity.Detailed));
if (this.showPerfSummary)
{
// Create a new performance counter for this target
MPPerformanceCounter counter = GetPerformanceCounter(e.TargetName, ref targetPerformanceCounters);
counter.AddEventStarted(null, e.BuildEventContext, e.Timestamp, s_compareContextNodeIdTargetId);
}
}
/// <summary>
/// Handler for target finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void TargetFinishedHandler(object sender, TargetFinishedEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext");
if (this.showPerfSummary)
{
// Stop the performance counter started in the targetStartedEventHandler
MPPerformanceCounter counter = GetPerformanceCounter(e.TargetName, ref targetPerformanceCounters);
counter.AddEventFinished(null, e.BuildEventContext, e.Timestamp);
}
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
// Display the target started event arg if we have got to the target finished but have not displayed it yet.
DisplayDeferredTargetStartedEvent(e.BuildEventContext);
// Get the target started event so we can determine whether or not to show the targetFinishedEvent
// as we only want to show target finished events if a target started event has been shown
TargetStartedEventMinimumFields startedEvent = _buildEventManager.GetTargetStartedEvent(e.BuildEventContext);
ErrorUtilities.VerifyThrow(startedEvent != null, "Started event should not be null in the finished event handler");
if (startedEvent.ShowTargetFinishedEvent)
{
if (showTargetOutputs)
{
IEnumerable targetOutputs = e.TargetOutputs;
if (targetOutputs != null)
{
WriteMessageAligned(ResourceUtilities.GetResourceString("TargetOutputItemsHeader"), false);
foreach (ITaskItem item in targetOutputs)
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TargetOutputItem", item.ItemSpec), false);
IDictionary metadata = item.CloneCustomMetadata();
foreach (DictionaryEntry metadatum in metadata)
{
WriteMessageAligned($"{new String(' ', 4 * tabWidth)}{metadatum.Key} = {item.GetMetadata(metadatum.Key as string)}", false);
}
}
}
}
if (!showOnlyErrors && !showOnlyWarnings)
{
_lastProjectFullKey = GetFullProjectKey(e.BuildEventContext);
WriteLinePrefix(e.BuildEventContext, e.Timestamp, false);
setColor(ConsoleColor.Cyan);
if (IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || _showEventId)
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TargetMessageWithId", e.Message, e.BuildEventContext.TargetId), true);
}
else
{
WriteMessageAligned(e.Message, true);
}
resetColor();
}
ShownBuildEventContext(e.BuildEventContext);
}
}
// We no longer need this target started event, it can be removed
_buildEventManager.RemoveTargetStartedEvent(e.BuildEventContext);
}
/// <summary>
/// Handler for task started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void TaskStartedHandler(object sender, TaskStartedEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext");
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
DisplayDeferredStartedEvents(e.BuildEventContext);
if (!showOnlyErrors && !showOnlyWarnings)
{
bool prefixAlreadyWritten = WriteTargetMessagePrefix(e, e.BuildEventContext, e.Timestamp);
setColor(ConsoleColor.DarkCyan);
if (IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || _showEventId)
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskMessageWithId", e.Message, e.BuildEventContext.TaskId), prefixAlreadyWritten);
}
else
{
WriteMessageAligned(e.Message, prefixAlreadyWritten);
}
resetColor();
}
ShownBuildEventContext(e.BuildEventContext);
}
if (this.showPerfSummary)
{
// Create a new performance counter for this task
MPPerformanceCounter counter = GetPerformanceCounter(e.TaskName, ref taskPerformanceCounters);
counter.AddEventStarted(null, e.BuildEventContext, e.Timestamp, null);
}
}
/// <summary>
/// Handler for task finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
public override void TaskFinishedHandler(object sender, TaskFinishedEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext");
if (this.showPerfSummary)
{
// Stop the task performance counter which was started in the task started event
MPPerformanceCounter counter = GetPerformanceCounter(e.TaskName, ref taskPerformanceCounters);
counter.AddEventFinished(null, e.BuildEventContext, e.Timestamp);
}
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
if (!showOnlyErrors && !showOnlyWarnings)
{
bool prefixAlreadyWritten = WriteTargetMessagePrefix(e, e.BuildEventContext, e.Timestamp);
setColor(ConsoleColor.DarkCyan);
if (IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || _showEventId)
{
WriteMessageAligned(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskMessageWithId", e.Message, e.BuildEventContext.TaskId), prefixAlreadyWritten);
}
else
{
WriteMessageAligned(e.Message, prefixAlreadyWritten);
}