forked from dotnet/msbuild
/
TaskLoggingHelper.cs
1518 lines (1348 loc) · 71.4 KB
/
TaskLoggingHelper.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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Text;
#if FEATURE_APPDOMAIN
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting;
#endif
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
#if BUILD_ENGINE
namespace Microsoft.Build.BackEnd
#else
namespace Microsoft.Build.Utilities
#endif
{
/// <summary>
/// Helper logging class - contains all the logging methods used by tasks.
/// A TaskLoggingHelper object is passed to every task by MSBuild. For tasks that derive
/// from the Task class, it is provided in the Log property.
/// This class is thread safe: tasks can log from any threads.
/// </summary>
#if BUILD_ENGINE
internal
#else
public
#endif
class TaskLoggingHelper
#if FEATURE_APPDOMAIN
: MarshalByRefObject
#endif
{
#region Constructors
/// <summary>
/// public constructor
/// </summary>
/// <param name="taskInstance">task containing an instance of this class</param>
public TaskLoggingHelper(ITask taskInstance)
{
ErrorUtilities.VerifyThrowArgumentNull(taskInstance, nameof(taskInstance));
_taskInstance = taskInstance;
TaskName = taskInstance.GetType().Name;
}
/// <summary>
/// Public constructor which can be used by task factories to assist them in logging messages.
/// </summary>
public TaskLoggingHelper(IBuildEngine buildEngine, string taskName)
{
ErrorUtilities.VerifyThrowArgumentNull(buildEngine, nameof(buildEngine));
ErrorUtilities.VerifyThrowArgumentLength(taskName, nameof(taskName));
TaskName = taskName;
_buildEngine = buildEngine;
}
#endregion
#region Properties
#if FEATURE_APPDOMAIN
/// <summary>
/// A client sponsor is a class
/// which will respond to a lease renewal request and will
/// increase the lease time allowing the object to stay in memory
/// </summary>
private ClientSponsor _sponsor;
#endif
// We have to pass an instance of ITask to BuildEngine, and since we call into the engine from this class we
// need to store the actual task instance.
private readonly ITask _taskInstance;
#if FEATURE_APPDOMAIN
/// <summary>
/// Object to make this class thread-safe.
/// </summary>
private readonly Object _locker = new Object();
#endif // FEATURE_APPDOMAIN
/// <summary>
/// Gets the name of the parent task.
/// </summary>
/// <value>Task name string.</value>
protected string TaskName { get; }
/// <summary>
/// Gets the upper-case version of the parent task's name.
/// </summary>
/// <value>Upper-case task name string.</value>
private string TaskNameUpperCase
{
get
{
if (_taskNameUpperCase == null)
{
// NOTE: use the current thread culture, because this string will be displayed to the user
_taskNameUpperCase = TaskName.ToUpper();
}
return _taskNameUpperCase;
}
}
// the upper-case version of the parent task's name (for logging purposes)
private string _taskNameUpperCase;
/// <summary>
/// The build engine we are going to log against
/// </summary>
private readonly IBuildEngine _buildEngine;
/// <summary>
/// Shortcut property for getting our build engine - we retrieve it from the task instance
/// </summary>
protected IBuildEngine BuildEngine
{
get
{
// If the task instance does not equal null then use its build engine because
// the task instances build engine can be changed for example during tests. This changing of the engine on the same task object is not expected to happen
// during normal operation.
if (_taskInstance != null)
{
return _taskInstance.BuildEngine;
}
return _buildEngine;
}
}
/// <summary>
/// Used to load culture-specific resources. Derived classes should register their resources either during construction, or
/// via this property, if they have localized strings.
/// </summary>
public ResourceManager TaskResources { get; set; }
// UI resources (including strings) used by the logging methods
/// <summary>
/// Gets or sets the prefix used to compose help keywords from string resource names.
/// </summary>
/// <value>The help keyword prefix string.</value>
public string HelpKeywordPrefix { get; set; }
/// <summary>
/// Has the task logged any errors through this logging helper object?
/// </summary>
public bool HasLoggedErrors { get; private set; }
#endregion
#region Utility methods
/// <summary>
/// Extracts the message code (if any) prefixed to the given message string. Message code prefixes must match the
/// following .NET regular expression in order to be recognized: <c>^\s*[A-Za-z]+\d+:\s*</c>
/// Thread safe.
/// </summary>
/// <example>
/// If this method is given the string "MYTASK1001: This is an error message.", it will return "MYTASK1001" for the
/// message code, and "This is an error message." for the message.
/// </example>
/// <param name="message">The message to parse.</param>
/// <param name="messageWithoutCodePrefix">The message with the code prefix removed (if any).</param>
/// <returns>The message code extracted from the prefix, or null if there was no code.</returns>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public string ExtractMessageCode(string message, out string messageWithoutCodePrefix)
{
ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message));
messageWithoutCodePrefix = ResourceUtilities.ExtractMessageCode(false /* any code */, message, out string code);
return code;
}
/// <summary>
/// Loads the specified resource string and optionally formats it using the given arguments. The current thread's culture
/// is used for formatting.
///
/// Requires the owner task to have registered its resources either via the Task (or TaskMarshalByRef) base
/// class constructor, or the Task.TaskResources (or AppDomainIsolatedTask.TaskResources) property.
///
/// Thread safe.
/// </summary>
/// <param name="resourceName">The name of the string resource to load.</param>
/// <param name="args">Optional arguments for formatting the loaded string.</param>
/// <returns>The formatted string.</returns>
/// <exception cref="ArgumentNullException">Thrown when <c>resourceName</c> is null.</exception>
/// <exception cref="ArgumentException">Thrown when the string resource indicated by <c>resourceName</c> does not exist.</exception>
/// <exception cref="InvalidOperationException">Thrown when the <c>TaskResources</c> property of the owner task is not set.</exception>
public virtual string FormatResourceString(string resourceName, params object[] args)
{
ErrorUtilities.VerifyThrowArgumentNull(resourceName, nameof(resourceName));
ErrorUtilities.VerifyThrowInvalidOperation(TaskResources != null, "Shared.TaskResourcesNotRegistered", TaskName);
string resourceString = TaskResources.GetString(resourceName, CultureInfo.CurrentUICulture);
ErrorUtilities.VerifyThrowArgument(resourceString != null, "Shared.TaskResourceNotFound", resourceName, TaskName);
return FormatString(resourceString, args);
}
/// <summary>
/// Formats the given string using the variable arguments passed in. The current thread's culture is used for formatting.
/// Thread safe.
/// </summary>
/// <param name="unformatted">The string to format.</param>
/// <param name="args">Arguments for formatting.</param>
/// <returns>The formatted string.</returns>
/// <exception cref="ArgumentNullException">Thrown when <c>unformatted</c> is null.</exception>
public virtual string FormatString(string unformatted, params object[] args)
{
ErrorUtilities.VerifyThrowArgumentNull(unformatted, nameof(unformatted));
return ResourceUtilities.FormatString(unformatted, args);
}
/// <summary>
/// Get the message from resource in task library.
/// Thread safe.
/// </summary>
/// <param name="resourceName">The resource name.</param>
/// <returns>The message from resource.</returns>
public virtual string GetResourceMessage(string resourceName)
{
string resourceString = FormatResourceString(resourceName, null);
return resourceString;
}
#endregion
#region Message logging methods
/// <summary>
/// Logs a message using the specified string.
/// Thread safe.
/// </summary>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogMessage(string message, params object[] messageArgs)
{
// This API is poorly designed, because parameters misordered like LogMessage(message, MessageImportance.High)
// will use this overload, ignore the importance and accidentally format the string.
// Can't change it now as it's shipped, but this debug assert will help catch callers doing this.
// Debug only because it is in theory legitimate to pass importance as a string format parameter.
Debug.Assert(messageArgs == null || messageArgs.Length == 0 || messageArgs[0].GetType() != typeof(MessageImportance), "Did you call the wrong overload?");
LogMessage(MessageImportance.Normal, message, messageArgs);
}
/// <summary>
/// Logs a message of the given importance using the specified string.
/// Thread safe.
/// </summary>
/// <remarks>
/// Take care to order the parameters correctly or the other overload will be called inadvertently.
/// </remarks>
/// <param name="importance">The importance level of the message.</param>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogMessage(MessageImportance importance, string message, params object[] messageArgs)
{
// No lock needed, as BuildEngine methods from v4.5 onwards are thread safe.
ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message));
#if DEBUG
if (messageArgs?.Length > 0)
{
// Verify that message can be formatted using given arguments
ResourceUtilities.FormatString(message, messageArgs);
}
#endif
BuildMessageEventArgs e = new BuildMessageEventArgs
(
message, // message
null, // help keyword
TaskName, // sender
importance, // importance
DateTime.UtcNow, // timestamp
messageArgs // message arguments
);
// If BuildEngine is null, task attempted to log before it was set on it,
// presumably in its constructor. This is not allowed, and all
// we can do is throw.
if (BuildEngine == null)
{
// Do not use Verify[...] as it would read e.Message ahead of time
ErrorUtilities.ThrowInvalidOperation("LoggingBeforeTaskInitialization", e.Message);
}
BuildEngine.LogMessageEvent(e);
#if DEBUG
// Assert that the message does not contain an error code. Only errors and warnings
// should have error codes.
string errorCode;
ResourceUtilities.ExtractMessageCode(true /* only msbuild codes */, message, out errorCode);
ErrorUtilities.VerifyThrow(errorCode == null, "This message contains an error code (" + errorCode + "), yet it was logged as a regular message: " + message);
#endif
}
/// <summary>
/// Logs a message using the specified string and other message details.
/// Thread safe.
/// </summary>
/// <param name="subcategory">Description of the warning type (can be null).</param>
/// <param name="code">Message code (can be null)</param>
/// <param name="helpKeyword">The help keyword for the host IDE (can be null).</param>
/// <param name="file">The path to the file causing the message (can be null).</param>
/// <param name="lineNumber">The line in the file causing the message (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file causing the message (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file causing the message (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file causing the message (set to zero if not available).</param>
/// <param name="importance">Importance of the message.</param>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogMessage
(
string subcategory,
string code,
string helpKeyword,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
MessageImportance importance,
string message,
params object[] messageArgs
)
{
// No lock needed, as BuildEngine methods from v4.5 onwards are thread safe.
ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message));
// If BuildEngine is null, task attempted to log before it was set on it,
// presumably in its constructor. This is not allowed, and all
// we can do is throw.
ErrorUtilities.VerifyThrowInvalidOperation(BuildEngine != null, "LoggingBeforeTaskInitialization", message);
// If the task has missed out all location information, add the location of the task invocation;
// that gives the user something.
bool fillInLocation = (String.IsNullOrEmpty(file) && (lineNumber == 0) && (columnNumber == 0));
var e = new BuildMessageEventArgs
(
subcategory,
code,
fillInLocation ? BuildEngine.ProjectFileOfTaskNode : file,
fillInLocation ? BuildEngine.LineNumberOfTaskNode : lineNumber,
fillInLocation ? BuildEngine.ColumnNumberOfTaskNode : columnNumber,
endLineNumber,
endColumnNumber,
message,
helpKeyword,
TaskName,
importance,
DateTime.UtcNow,
messageArgs
);
BuildEngine.LogMessageEvent(e);
}
/// <summary>
/// Logs a critical message using the specified string and other message details.
/// Thread safe.
/// </summary>
/// <param name="subcategory">Description of the warning type (can be null).</param>
/// <param name="code">Message code (can be null).</param>
/// <param name="helpKeyword">The help keyword for the host IDE (can be null).</param>
/// <param name="file">The path to the file causing the message (can be null).</param>
/// <param name="lineNumber">The line in the file causing the message (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file causing the message (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file causing the message (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file causing the message (set to zero if not available).</param>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogCriticalMessage
(
string subcategory,
string code,
string helpKeyword,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string message,
params object[] messageArgs
)
{
// No lock needed, as BuildEngine methods from v4.5 onwards are thread safe.
ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message));
// If BuildEngine is null, task attempted to log before it was set on it,
// presumably in its constructor. This is not allowed, and all
// we can do is throw.
ErrorUtilities.VerifyThrowInvalidOperation(BuildEngine != null, "LoggingBeforeTaskInitialization", message);
// If the task has missed out all location information, add the location of the task invocation;
// that gives the user something.
bool fillInLocation = (String.IsNullOrEmpty(file) && (lineNumber == 0) && (columnNumber == 0));
var e = new CriticalBuildMessageEventArgs
(
subcategory,
code,
fillInLocation ? BuildEngine.ProjectFileOfTaskNode : file,
fillInLocation ? BuildEngine.LineNumberOfTaskNode : lineNumber,
fillInLocation ? BuildEngine.ColumnNumberOfTaskNode : columnNumber,
endLineNumber,
endColumnNumber,
message,
helpKeyword,
TaskName,
DateTime.UtcNow,
messageArgs
);
BuildEngine.LogMessageEvent(e);
}
/// <summary>
/// Logs a message using the specified resource string.
/// Thread safe.
/// </summary>
/// <param name="messageResourceName">The name of the string resource to load.</param>
/// <param name="messageArgs">Optional arguments for formatting the loaded string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception>
public void LogMessageFromResources(string messageResourceName, params object[] messageArgs)
{
// No lock needed, as the logging methods are thread safe and the rest does not modify
// global state.
//
// This API is poorly designed, because parameters misordered like LogMessageFromResources(messageResourceName, MessageImportance.High)
// will use this overload, ignore the importance and accidentally format the string.
// Can't change it now as it's shipped, but this debug assert will help catch callers doing this.
// Debug only because it is in theory legitimate to pass importance as a string format parameter.
Debug.Assert(messageArgs == null || messageArgs.Length == 0 || messageArgs[0].GetType() != typeof(MessageImportance), "Did you call the wrong overload?");
LogMessageFromResources(MessageImportance.Normal, messageResourceName, messageArgs);
}
/// <summary>
/// Logs a message of the given importance using the specified resource string.
/// Thread safe.
/// </summary>
/// <remarks>
/// Take care to order the parameters correctly or the other overload will be called inadvertently.
/// </remarks>
/// <param name="importance">The importance level of the message.</param>
/// <param name="messageResourceName">The name of the string resource to load.</param>
/// <param name="messageArgs">Optional arguments for formatting the loaded string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception>
public void LogMessageFromResources(MessageImportance importance, string messageResourceName, params object[] messageArgs)
{
// No lock needed, as the logging methods are thread safe and the rest does not modify
// global state.
ErrorUtilities.VerifyThrowArgumentNull(messageResourceName, nameof(messageResourceName));
LogMessage(importance, GetResourceMessage(messageResourceName), messageArgs);
#if DEBUG
// Assert that the message does not contain an error code. Only errors and warnings
// should have error codes.
string errorCode;
ResourceUtilities.ExtractMessageCode(true /* only msbuild codes */, FormatResourceString(messageResourceName, messageArgs), out errorCode);
ErrorUtilities.VerifyThrow(errorCode == null, errorCode, FormatResourceString(messageResourceName, messageArgs));
#endif
}
#endregion
#region ExternalProjectStarted/Finished logging methods
/// <summary>
/// Small helper for logging the custom ExternalProjectStarted build event
/// Thread safe.
/// </summary>
/// <param name="message">text message</param>
/// <param name="helpKeyword">help keyword</param>
/// <param name="projectFile">project name</param>
/// <param name="targetNames">targets we are going to build (empty indicates default targets)</param>
public void LogExternalProjectStarted
(
string message,
string helpKeyword,
string projectFile,
string targetNames
)
{
// No lock needed, as BuildEngine methods from v4.5 onwards are thread safe.
var eps = new ExternalProjectStartedEventArgs(message, helpKeyword, TaskName, projectFile, targetNames);
BuildEngine.LogCustomEvent(eps);
}
/// <summary>
/// Small helper for logging the custom ExternalProjectFinished build event.
/// Thread safe.
/// </summary>
/// <param name="message">text message</param>
/// <param name="helpKeyword">help keyword</param>
/// <param name="projectFile">project name</param>
/// <param name="succeeded">true indicates project built successfully</param>
public void LogExternalProjectFinished
(
string message,
string helpKeyword,
string projectFile,
bool succeeded
)
{
// No lock needed, as BuildEngine methods from v4.5 onwards are thread safe.
var epf = new ExternalProjectFinishedEventArgs(message, helpKeyword, TaskName, projectFile, succeeded);
BuildEngine.LogCustomEvent(epf);
}
#endregion
#region Command line logging methods
/// <summary>
/// Logs the command line for a task's underlying tool/executable/shell command.
/// Thread safe.
/// </summary>
/// <param name="commandLine">The command line string.</param>
public void LogCommandLine(string commandLine)
{
LogCommandLine(MessageImportance.Low, commandLine);
}
/// <summary>
/// Logs the command line for a task's underlying tool/executable/shell
/// command, using the given importance level.
/// Thread safe.
/// </summary>
/// <param name="importance">The importance level of the command line.</param>
/// <param name="commandLine">The command line string.</param>
public void LogCommandLine(MessageImportance importance, string commandLine)
{
// No lock needed, as BuildEngine methods from v4.5 onwards are thread safe.
ErrorUtilities.VerifyThrowArgumentNull(commandLine, nameof(commandLine));
var e = new TaskCommandLineEventArgs(commandLine, TaskName, importance);
// If BuildEngine is null, the task attempted to log before it was set on it,
// presumably in its constructor. This is not allowed, and all we can do is throw.
if (BuildEngine == null)
{
// Do not use Verify[...] as it would read e.Message ahead of time
ErrorUtilities.ThrowInvalidOperation("LoggingBeforeTaskInitialization", e.Message);
}
BuildEngine.LogMessageEvent(e);
}
#endregion
#region Error logging methods
/// <summary>
/// Logs an error using the specified string.
/// Thread safe.
/// </summary>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogError(string message, params object[] messageArgs)
{
LogError(null, null, null, null, null, 0, 0, 0, 0, message, messageArgs);
}
/// <summary>
/// Logs an error using the specified string and other error details.
/// Thread safe.
/// </summary>
/// <param name="subcategory">Description of the error type (can be null).</param>
/// <param name="errorCode">The error code (can be null).</param>
/// <param name="helpKeyword">The help keyword for the host IDE (can be null).</param>
/// <param name="file">The path to the file containing the error (can be null).</param>
/// <param name="lineNumber">The line in the file where the error occurs (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file where the error occurs (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file where the error occurs (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file where the error occurs (set to zero if not available).</param>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogError
(
string subcategory,
string errorCode,
string helpKeyword,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string message,
params object[] messageArgs
)
{
LogError(subcategory, errorCode, helpKeyword, null, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, messageArgs);
}
/// <summary>
/// Logs an error using the specified string and other error details.
/// Thread safe.
/// </summary>
/// <param name="subcategory">Description of the error type (can be null).</param>
/// <param name="errorCode">The error code (can be null).</param>
/// <param name="helpKeyword">The help keyword for the host IDE (can be null).</param>
/// <param name="file">The path to the file containing the error (can be null).</param>
/// <param name="lineNumber">The line in the file where the error occurs (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file where the error occurs (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file where the error occurs (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file where the error occurs (set to zero if not available).</param>
/// <param name="message">The message string.</param>
/// <param name="helpLink">A link pointing to more information about the error.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogError
(
string subcategory,
string errorCode,
string helpKeyword,
string helpLink,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string message,
params object[] messageArgs
)
{
// No lock needed, as BuildEngine methods from v4.5 onwards are thread safe.
ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message));
// If BuildEngine is null, task attempted to log before it was set on it,
// presumably in its constructor. This is not allowed, and all
// we can do is throw.
ErrorUtilities.VerifyThrowInvalidOperation(BuildEngine != null, "LoggingBeforeTaskInitialization", message);
// All of our errors should have an error code, so the user has something
// to look up in the documentation. To help find errors without error codes,
// temporarily uncomment this line and run the unit tests.
//if (null == errorCode) File.AppendAllText("c:\\errorsWithoutCodes", message + "\n");
// We don't have a Debug.Assert for this, because it would be triggered by <Error> and <Warning> tags.
// If the task has missed out all location information, add the location of the task invocation;
// that gives the user something.
bool fillInLocation = (String.IsNullOrEmpty(file) && (lineNumber == 0) && (columnNumber == 0));
var e = new BuildErrorEventArgs
(
subcategory,
errorCode,
fillInLocation ? BuildEngine.ProjectFileOfTaskNode : file,
fillInLocation ? BuildEngine.LineNumberOfTaskNode : lineNumber,
fillInLocation ? BuildEngine.ColumnNumberOfTaskNode : columnNumber,
endLineNumber,
endColumnNumber,
message,
helpKeyword,
TaskName,
helpLink,
DateTime.UtcNow,
messageArgs
);
BuildEngine.LogErrorEvent(e);
HasLoggedErrors = true;
}
/// <summary>
/// Logs an error using the specified resource string.
/// Thread safe.
/// </summary>
/// <param name="messageResourceName">The name of the string resource to load.</param>
/// <param name="messageArgs">Optional arguments for formatting the loaded string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception>
public void LogErrorFromResources(string messageResourceName, params object[] messageArgs)
{
LogErrorFromResources(null, null, null, null, 0, 0, 0, 0, messageResourceName, messageArgs);
}
/// <summary>
/// Logs an error using the specified resource string and other error details.
/// Thread safe.
/// </summary>
/// <param name="subcategoryResourceName">The name of the string resource that describes the error type (can be null).</param>
/// <param name="errorCode">The error code (can be null).</param>
/// <param name="helpKeyword">The help keyword for the host IDE (can be null).</param>
/// <param name="file">The path to the file containing the error (can be null).</param>
/// <param name="lineNumber">The line in the file where the error occurs (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file where the error occurs (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file where the error occurs (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file where the error occurs (set to zero if not available).</param>
/// <param name="messageResourceName">The name of the string resource containing the error message.</param>
/// <param name="messageArgs">Optional arguments for formatting the loaded string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception>
public void LogErrorFromResources
(
string subcategoryResourceName,
string errorCode,
string helpKeyword,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string messageResourceName,
params object[] messageArgs
)
{
// No lock needed, as the logging methods are thread safe and the rest does not modify
// global state.
ErrorUtilities.VerifyThrowArgumentNull(messageResourceName, nameof(messageResourceName));
string subcategory = null;
if (subcategoryResourceName != null)
{
subcategory = FormatResourceString(subcategoryResourceName);
}
#if DEBUG
// If the message does have a message code, LogErrorWithCodeFromResources
// should have been called instead, so that the errorCode field gets populated.
// Check this only in debug, to avoid the cost of attempting to extract a
// message code when there probably isn't one.
string messageCode;
string throwAwayMessageBody = ResourceUtilities.ExtractMessageCode(true /* only msbuild codes */, FormatResourceString(messageResourceName, messageArgs), out messageCode);
ErrorUtilities.VerifyThrow(string.IsNullOrEmpty(messageCode), "Called LogErrorFromResources instead of LogErrorWithCodeFromResources, but message '" + throwAwayMessageBody + "' does have an error code '" + messageCode + "'");
#endif
LogError
(
subcategory,
errorCode,
helpKeyword,
file,
lineNumber,
columnNumber,
endLineNumber,
endColumnNumber,
FormatResourceString(messageResourceName, messageArgs)
);
}
/// <summary>
/// Logs an error using the specified resource string.
/// If the message has an error code prefixed to it, the code is extracted and logged with the message. If a help keyword
/// prefix has been provided, a help keyword for the host IDE is also logged with the message. The help keyword is
/// composed by appending the string resource name to the prefix.
///
/// A task can provide a help keyword prefix either via the Task (or TaskMarshalByRef) base class constructor, or the
/// Task.HelpKeywordPrefix (or AppDomainIsolatedTask.HelpKeywordPrefix) property.
///
/// Thread safe.
/// </summary>
/// <param name="messageResourceName">The name of the string resource to load.</param>
/// <param name="messageArgs">Optional arguments for formatting the loaded string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception>
public void LogErrorWithCodeFromResources(string messageResourceName, params object[] messageArgs)
{
LogErrorWithCodeFromResources(null, null, 0, 0, 0, 0, messageResourceName, messageArgs);
}
/// <summary>
/// Logs an error using the specified resource string and other error details.
/// If the message has an error code prefixed, the code is extracted and logged with the message. If a
/// help keyword prefix has been provided, a help keyword for the host IDE is also logged with the message. The help
/// keyword is composed by appending the error message resource string name to the prefix.
///
/// A task can provide a help keyword prefix either via the Task (or TaskMarshalByRef) base class constructor, or the
/// Task.HelpKeywordPrefix (or AppDomainIsolatedTask.HelpKeywordPrefix) property.
///
/// Thread safe.
/// </summary>
/// <param name="subcategoryResourceName">The name of the string resource that describes the error type (can be null).</param>
/// <param name="file">The path to the file containing the error (can be null).</param>
/// <param name="lineNumber">The line in the file where the error occurs (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file where the error occurs (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file where the error occurs (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file where the error occurs (set to zero if not available).</param>
/// <param name="messageResourceName">The name of the string resource containing the error message.</param>
/// <param name="messageArgs">Optional arguments for formatting the loaded string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception>
public void LogErrorWithCodeFromResources
(
string subcategoryResourceName,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string messageResourceName,
params object[] messageArgs
)
{
// No lock needed, as the logging methods are thread safe and the rest does not modify
// global state.
ErrorUtilities.VerifyThrowArgumentNull(messageResourceName, nameof(messageResourceName));
string subcategory = null;
if (subcategoryResourceName != null)
{
subcategory = FormatResourceString(subcategoryResourceName);
}
string message = ResourceUtilities.ExtractMessageCode(false /* all codes */, FormatResourceString(messageResourceName, messageArgs), out string errorCode);
string helpKeyword = null;
if (HelpKeywordPrefix != null)
{
helpKeyword = HelpKeywordPrefix + messageResourceName;
}
LogError
(
subcategory,
errorCode,
helpKeyword,
file,
lineNumber,
columnNumber,
endLineNumber,
endColumnNumber,
message
);
}
/// <summary>
/// Logs an error using the message from the given exception context.
/// No callstack will be shown.
/// Thread safe.
/// </summary>
/// <param name="exception">Exception to log.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>e</c> is null.</exception>
public void LogErrorFromException(Exception exception)
{
LogErrorFromException(exception, false);
}
/// <summary>
/// Logs an error using the message (and optionally the stack-trace) from the given exception context.
/// Thread safe.
/// </summary>
/// <param name="exception">Exception to log.</param>
/// <param name="showStackTrace">If true, callstack will be appended to message.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>exception</c> is null.</exception>
public void LogErrorFromException(Exception exception, bool showStackTrace)
{
LogErrorFromException(exception, showStackTrace, false, null);
}
/// <summary>
/// Logs an error using the message, and optionally the stack-trace from the given exception, and
/// optionally inner exceptions too.
/// Thread safe.
/// </summary>
/// <param name="exception">Exception to log.</param>
/// <param name="showStackTrace">If true, callstack will be appended to message.</param>
/// <param name="showDetail">Whether to log exception types and any inner exceptions.</param>
/// <param name="file">File related to the exception, or null if the project file should be logged</param>
/// <exception cref="ArgumentNullException">Thrown when <c>exception</c> is null.</exception>
public void LogErrorFromException(Exception exception, bool showStackTrace, bool showDetail, string file)
{
// No lock needed, as the logging methods are thread safe and the rest does not modify
// global state.
ErrorUtilities.VerifyThrowArgumentNull(exception, nameof(exception));
string message;
if (!showDetail && (Environment.GetEnvironmentVariable("MSBUILDDIAGNOSTICS") == null)) // This env var is also used in ToolTask
{
message = exception.Message;
if (showStackTrace)
{
message += Environment.NewLine + exception.StackTrace;
}
}
else
{
// The more comprehensive output, showing exception types
// and inner exceptions
var builder = new StringBuilder(200);
do
{
builder.Append(exception.GetType().Name);
builder.Append(": ");
builder.AppendLine(exception.Message);
if (showStackTrace)
{
builder.AppendLine(exception.StackTrace);
}
exception = exception.InnerException;
} while (exception != null);
message = builder.ToString();
}
LogError(null, null, null, file, 0, 0, 0, 0, message);
}
#endregion
#region Warning logging methods
/// <summary>
/// Logs a warning using the specified string.
/// Thread safe.
/// </summary>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogWarning(string message, params object[] messageArgs)
{
LogWarning(null, null, null, null, 0, 0, 0, 0, message, messageArgs);
}
/// <summary>
/// Logs a warning using the specified string and other warning details.
/// Thread safe.
/// </summary>
/// <param name="subcategory">Description of the warning type (can be null).</param>
/// <param name="warningCode">The warning code (can be null).</param>
/// <param name="helpKeyword">The help keyword for the host IDE (can be null).</param>
/// <param name="file">The path to the file causing the warning (can be null).</param>
/// <param name="lineNumber">The line in the file causing the warning (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file causing the warning (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file causing the warning (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file causing the warning (set to zero if not available).</param>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogWarning
(
string subcategory,
string warningCode,
string helpKeyword,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string message,
params object[] messageArgs
)
{
LogWarning(subcategory, warningCode, helpKeyword, null, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, messageArgs);
}
/// <summary>
/// Logs a warning using the specified string and other warning details.
/// Thread safe.
/// </summary>
/// <param name="subcategory">Description of the warning type (can be null).</param>
/// <param name="warningCode">The warning code (can be null).</param>
/// <param name="helpKeyword">The help keyword for the host IDE (can be null).</param>
/// <param name="helpLink">A link pointing to more information about the warning (can be null).</param>
/// <param name="file">The path to the file causing the warning (can be null).</param>
/// <param name="lineNumber">The line in the file causing the warning (set to zero if not available).</param>
/// <param name="columnNumber">The column in the file causing the warning (set to zero if not available).</param>
/// <param name="endLineNumber">The last line of a range of lines in the file causing the warning (set to zero if not available).</param>
/// <param name="endColumnNumber">The last column of a range of columns in the file causing the warning (set to zero if not available).</param>
/// <param name="message">The message string.</param>
/// <param name="messageArgs">Optional arguments for formatting the message string.</param>
/// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception>
public void LogWarning
(
string subcategory,
string warningCode,
string helpKeyword,
string helpLink,
string file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string message,
params object[] messageArgs
)
{