internal static async Task<BuildResult> BuildAsync(this BuildManager buildManager, ITestOutputHelper logger, ProjectCollection projectCollection, ProjectRootElement project, string target, IDictionary<string, string> globalProperties = null, LoggerVerbosity logVerbosity = LoggerVerbosity.Detailed, ILogger[] additionalLoggers = null) { Requires.NotNull(buildManager, nameof(buildManager)); Requires.NotNull(projectCollection, nameof(projectCollection)); Requires.NotNull(project, nameof(project)); globalProperties = globalProperties ?? new Dictionary<string, string>(); var projectInstance = new ProjectInstance(project, globalProperties, null, projectCollection); var brd = new BuildRequestData(projectInstance, new[] { target }, null, BuildRequestDataFlags.ProvideProjectStateAfterBuild); var parameters = new BuildParameters(projectCollection); var loggers = new List<ILogger>(); loggers.Add(new ConsoleLogger(logVerbosity, s => logger.WriteLine(s.TrimEnd('\r', '\n')), null, null)); loggers.AddRange(additionalLoggers); parameters.Loggers = loggers.ToArray(); buildManager.BeginBuild(parameters); var result = await buildManager.BuildAsync(brd); buildManager.EndBuild(); return result; }
public static ITargetResult BuildScenario(string scenarioName, object properties = null, string target = "GetPackageContents", ITestOutputHelper output = null, LoggerVerbosity? verbosity = null) { var projectName = scenarioName; if (scenarioName.StartsWith("given", StringComparison.OrdinalIgnoreCase)) projectName = string.Join("_", scenarioName.Split('_').Skip(2)); var scenarioDir = Path.Combine(ModuleInitializer.BaseDirectory, "Scenarios", scenarioName); string projectOrSolution; if (File.Exists(Path.Combine(scenarioDir, $"{projectName}.csproj"))) projectOrSolution = Path.Combine(scenarioDir, $"{projectName}.csproj"); else projectOrSolution = Directory.EnumerateFiles(scenarioDir, "*.csproj").First(); var logger = default(ILogger); if (output != null) { if (verbosity == null) { var data = Thread.GetNamedDataSlot(nameof(LoggerVerbosity)); if (data != null) verbosity = (LoggerVerbosity?)Thread.GetData(data); } logger = new TestOutputLogger(output, verbosity); } if (properties != null) return Build(projectOrSolution, target, properties: properties.GetType().GetProperties().ToDictionary(prop => prop.Name, prop => prop.GetValue(properties).ToString()), logger: logger)[target]; else return Build(projectOrSolution, target, logger: logger)[target]; }
public SDConsoleLogger(IBuildFeedbackSink feedbackSink, LoggerVerbosity verbosity) : base(verbosity) { if (feedbackSink == null) throw new ArgumentNullException("feedbackSink"); this.feedbackSink = feedbackSink; this.ShowSummary = false; base.WriteHandler = Write; }
public CmdLineBuilder(CSBuildConfig config, LoggerVerbosity? verbosity, string groups, string[] targetNames, string[] propertySets) { _config = config; _verbosity = verbosity; _groups = groups; _targetNames = targetNames; _propertySets = propertySets; _thread = new System.Threading.Thread(this.Build); }
/// <summary> /// Initializes the logger, with alternate output handlers. /// </summary> /// <param name="verbosity"></param> /// <param name="write"></param> /// <param name="colorSet"></param> /// <param name="colorReset"></param> public SerialConsoleLogger ( LoggerVerbosity verbosity, WriteHandler write, ColorSetter colorSet, ColorResetter colorReset ) { InitializeConsoleMethods(verbosity, write, colorSet, colorReset); }
/// <summary> /// Creates a new instance of the <see cref="DebugMctLogger" /> class. /// </summary> /// <param name="verbosity">The verbosity of the <see cref="MctLogger" />.</param> public DebugMctLogger(LoggerVerbosity verbosity) { Verbosity = verbosity; if (!Debugger.IsAttached) try { Debugger.Launch(); } catch { } }
private static void CheckVerbosity(string errorMessage, LoggerVerbosity expectedVerbosity, string verbosity = null, string logLevel = null, int expectedNumberOfWarnings = 0) { var provider = CreatePropertiesProvider(verbosity, logLevel); TestLogger logger = new TestLogger(); var actualVerbosity = VerbosityCalculator.ComputeVerbosity(provider, logger); Assert.AreEqual(expectedVerbosity, actualVerbosity, errorMessage); logger.AssertErrorsLogged(0); logger.AssertWarningsLogged(expectedNumberOfWarnings); }
/// <summary> /// Create a logger instance with a specific verbosity. This logs to /// the default console. /// </summary> /// <param name="verbosity">Verbosity level.</param> public ConsoleLogger(LoggerVerbosity verbosity) : this ( verbosity, new WriteHandler(Console.Out.Write), new ColorSetter(BaseConsoleLogger.SetColor), new ColorResetter(BaseConsoleLogger.ResetColor) ) { // do nothing }
public static RegisterLoggerResult Register( Guid loggerId, LoggerVerbosity loggerVerbosity, out BuildOutputLogger buildLogger) { try { const BindingFlags InterfacePropertyFlags = BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance; BuildManager buildManager = BuildManager.DefaultBuildManager; Type buildHostType = buildManager.GetType().Assembly.GetType("Microsoft.Build.BackEnd.IBuildComponentHost"); PropertyInfo loggingSeviceProperty = buildHostType.GetProperty("LoggingService", InterfacePropertyFlags); object loggingServiceObj; try { // Microsoft.Build.BackEnd.ILoggingService loggingServiceObj = loggingSeviceProperty.GetValue(buildManager, null); } catch (TargetInvocationException ex) { ex.Trace("Microsoft.Build.BackEnd.ILoggingService is not available."); buildLogger = null; return RegisterLoggerResult.FatalError; } PropertyInfo loggersProperty = loggingServiceObj.GetType().GetProperty("Loggers", InterfacePropertyFlags); ICollection<ILogger> loggers = (ICollection<ILogger>)loggersProperty.GetValue(loggingServiceObj, null); ILogger logger = loggers.FirstOrDefault(x => x is BuildOutputLogger && ((BuildOutputLogger)x)._id.Equals(loggerId)); if (logger != null) { buildLogger = (BuildOutputLogger)logger; buildLogger.Verbosity = loggerVerbosity; return RegisterLoggerResult.AlreadyExists; } MethodInfo registerLoggerMethod = loggingServiceObj.GetType().GetMethod("RegisterLogger"); buildLogger = new BuildOutputLogger(loggerId) { Verbosity = loggerVerbosity }; bool registerResult = (bool)registerLoggerMethod.Invoke(loggingServiceObj, new object[] { buildLogger }); return registerResult ? RegisterLoggerResult.RegisterSuccess : RegisterLoggerResult.RegisterFailed; } catch (Exception ex) { ex.TraceUnknownException(); buildLogger = null; return RegisterLoggerResult.FatalError; } }
public ConsoleLogger (LoggerVerbosity verbosity, WriteHandler write, ColorSetter colorSet, ColorResetter colorReset) { if (write == null) throw new ArgumentNullException ("write"); if (colorSet == null) throw new ArgumentNullException ("colorSet"); if (colorReset == null) throw new ArgumentNullException ("colorReset"); Verbosity = verbosity; this.write = write; set_color = colorSet; reset_color = colorReset; }
/// <summary> /// Creates a logger description from given data /// </summary> public LoggerDescription ( string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, LoggerVerbosity verbosity ) { this.loggerClassName = loggerClassName; this.loggerAssembly = new AssemblyLoadInfo(loggerAssemblyName, loggerAssemblyFile); this.loggerSwitchParameters = loggerSwitchParameters; this.verbosity = verbosity; }
public LoggerDescription (string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, LoggerVerbosity verbosity) { if (loggerAssemblyName != null && loggerAssemblyFile != null) throw new InvalidOperationException ("Cannot specify both loggerAssemblyName and loggerAssemblyFile at the same time."); if (loggerAssemblyName == null && loggerAssemblyFile == null) throw new InvalidOperationException ("Either loggerAssemblyName or loggerAssemblyFile must be specified"); class_name = loggerClassName; assembly_name = loggerAssemblyName; assembly_file = loggerAssemblyFile; LoggerSwitchParameters = loggerSwitchParameters; Verbosity = verbosity; }
public Parameters () { consoleLoggerParameters = ""; displayHelp = false; loggerInfos = new List<LoggerInfo> (); loggerVerbosity = LoggerVerbosity.Normal; noConsoleLogger = false; noLogo = false; properties = new Dictionary<string,string> (); targets = new string [0]; responseFile = Path.Combine ( Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location), "msbuild.rsp"); }
public Parameters () { consoleLoggerParameters = ""; displayHelp = false; loggers = new ArrayList (); loggerVerbosity = LoggerVerbosity.Normal; noConsoleLogger = false; noLogo = false; properties = new BuildPropertyGroup (); targets = new string [0]; responseFile = Path.Combine ( Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location), "xbuild.rsp"); }
public BootstrapperSettings(AnalysisPhase phase, IEnumerable<string> childCmdLineArgs, string sonarQubeUrl, LoggerVerbosity verbosity, ILogger logger) { if (sonarQubeUrl == null) { throw new ArgumentNullException("sonarQubeUrl"); } if (logger == null) { throw new ArgumentNullException("logger"); } this.sonarQubeUrl = sonarQubeUrl; this.analysisPhase = phase; this.childCmdLineArgs = childCmdLineArgs; this.verbosity = verbosity; this.logger = logger; }
/// <summary> /// Creates a logger description from given data /// </summary> public LoggerDescription ( string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, LoggerVerbosity verbosity ) { _loggerClassName = loggerClassName; if (loggerAssemblyFile != null && !Path.IsPathRooted(loggerAssemblyFile)) { loggerAssemblyFile = FileUtilities.NormalizePath(loggerAssemblyFile); } _loggerAssembly = AssemblyLoadInfo.Create(loggerAssemblyName, loggerAssemblyFile); _loggerSwitchParameters = loggerSwitchParameters; _verbosity = verbosity; }
public ContentBuilder(string contentProjectFile, GraphicsProfile graphicsProfile = GraphicsProfile.HiDef, TargetPlatform targetPlatform = TargetPlatform.Windows, bool compressContent = true, LoggerVerbosity loggerVerbosity = LoggerVerbosity.Normal, bool rebuildContent = false) { FileInfo fileInfo = new FileInfo(contentProjectFile); _contentProjectFile = Path.GetFullPath(fileInfo.FullName); if (fileInfo.Extension != ".contentproj") throw new NotSupportedException(string.Format("The file '{0}' is not a XNA content project.", _contentProjectFile)); if (!fileInfo.Exists) throw new FileNotFoundException(String.Format("The file '{0}' does not exist.", _contentProjectFile, _contentProjectFile)); GraphicsProfile = graphicsProfile; TargetPlatform = targetPlatform; CompressContent = compressContent; LoggerVerbosity = loggerVerbosity; RebuildContent = rebuildContent; if (!_globalProperties.ContainsKey("XnaProfile")) _globalProperties.Add("XnaProfile", GraphicsProfile.ToString()); if (!_globalProperties.ContainsKey("XNAContentPipelineTargetPlatform")) _globalProperties.Add("XNAContentPipelineTargetPlatform", TargetPlatform.ToString()); if (!_globalProperties.ContainsKey("XnaCompressContent")) _globalProperties.Add("XnaCompressContent", CompressContent.ToString()); if (!_globalProperties.ContainsKey("OutputhPath")) _globalProperties.Add("OutputPath", OutputPath); if (!_globalProperties.ContainsKey("ContentRootDirectory")) _globalProperties.Add("ContentRootDirectory", ContentRootDirectory); }
/// <summary> /// Parses command line arguments describing the distributed loggers /// </summary> /// <returns>List of distributed logger records</returns> private static List<DistributedLoggerRecord> ProcessDistributedLoggerSwitch(string[] parameters, LoggerVerbosity verbosity) { List<DistributedLoggerRecord> distributedLoggers = new List<DistributedLoggerRecord>(); foreach (string parameter in parameters) { // split each <central logger>|<node logger> string into two pieces, breaking on the first | that is found int emptySplits; // ignored ArrayList loggerSpec = QuotingUtilities.SplitUnquoted(parameter, 2, true /* keep empty splits */, false /* keep quotes */, out emptySplits, '*'); ErrorUtilities.VerifyThrow((loggerSpec.Count >= 1) && (loggerSpec.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two."); string unquotedParameter = QuotingUtilities.Unquote((string)loggerSpec[0]); LoggerDescription centralLoggerDescription = ParseLoggingParameter((string)loggerSpec[0], unquotedParameter, verbosity); ILogger centralLogger = CreateAndConfigureLogger(centralLoggerDescription, verbosity, unquotedParameter); // By default if no forwarding logger description is specified the same logger is used for both functions LoggerDescription forwardingLoggerDescription = centralLoggerDescription; if (loggerSpec.Count > 1) { unquotedParameter = QuotingUtilities.Unquote((string)loggerSpec[1]); forwardingLoggerDescription = ParseLoggingParameter((string)loggerSpec[1], unquotedParameter, verbosity); } DistributedLoggerRecord distributedLoggerRecord = new DistributedLoggerRecord(centralLogger, forwardingLoggerDescription); distributedLoggers.Add(distributedLoggerRecord); } return distributedLoggers; }
/// <summary> /// Returns a DistributedLoggerRecord containing this logger and a ConfigurableForwardingLogger. /// Looks at the logger's parameters for any verbosity parameter in order to make sure it is setting up the ConfigurableForwardingLogger /// with the verbosity level that the logger will actually use. /// </summary> private static DistributedLoggerRecord CreateForwardingLoggerRecord(ILogger logger, string loggerParameters, LoggerVerbosity defaultVerbosity) { string verbosityParameter = ExtractAnyLoggerParameter(loggerParameters, "verbosity", "v"); string verbosityValue = ExtractAnyParameterValue(verbosityParameter); LoggerVerbosity effectiveVerbosity = defaultVerbosity; if (!String.IsNullOrEmpty(verbosityValue)) { effectiveVerbosity = ProcessVerbositySwitch(verbosityValue); } //Gets the currently loaded assembly in which the specified class is defined Assembly engineAssembly = Assembly.GetAssembly(typeof(ProjectCollection)); string loggerClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string loggerAssemblyName = engineAssembly.GetName().FullName; LoggerDescription forwardingLoggerDescription = new LoggerDescription(loggerClassName, loggerAssemblyName, null, loggerParameters, effectiveVerbosity); DistributedLoggerRecord distributedLoggerRecord = new DistributedLoggerRecord(logger, forwardingLoggerDescription); return distributedLoggerRecord; }
public void AssertVerbosity(LoggerVerbosity expected) { Assert.AreEqual(expected, this.Verbosity, "Logger verbosity mismatch"); }
public AnalyzerManager(TextWriter logWriter, LoggerVerbosity loggerVerbosity = LoggerVerbosity.Normal) : this(null, logWriter, loggerVerbosity) { }
public StringLogger(LoggerVerbosity verbosity) : base(verbosity) { WriteHandler = Lines.Add; }
private async Task <BuildResults> BuildAsync(string target = Targets.GetBuildVersion, LoggerVerbosity logVerbosity = LoggerVerbosity.Detailed, bool assertSuccessfulBuild = true) { var eventLogger = new MSBuildLogger { Verbosity = LoggerVerbosity.Minimal }; var loggers = new ILogger[] { eventLogger }; var buildResult = await this.buildManager.BuildAsync( this.Logger, this.projectCollection, this.testProject, target, this.globalProperties, logVerbosity, loggers); var result = new BuildResults(buildResult, eventLogger.LoggedEvents); this.Logger.WriteLine(result.ToString()); if (assertSuccessfulBuild) { Assert.Equal(BuildResultCode.Success, buildResult.OverallResult); } return(result); }
public EmptyLogger(LoggerVerbosity verbosity) { Verbosity = verbosity; }
public string ToString(LoggerVerbosity verbosity) { return(verbosity <= LoggerVerbosity.Normal ? string.Format(CultureInfo.InvariantCulture, "{0}", ProjectKey) : ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="ConsoleLoggingQueue" /> class. /// </summary> /// <param name="verbosity">The <see cref="LoggerVerbosity" /> to use when logging messages.</param> public ConsoleLoggingQueue(LoggerVerbosity verbosity) { Verbosity = verbosity; _taskLoggingHelperLazy = new Lazy <TaskLoggingHelper>(() => new TaskLoggingHelper(this, nameof(MSBuildStaticGraphRestore))); }
public LoggingServiceToPluginLoggerAdapter( LoggerVerbosity verbosity, ILoggingService loggingService) : base(verbosity) { _loggingService = loggingService; }
private static void VerbositySetterOnLogger(IDELoggerProxy logger, LoggerVerbosity verbosity) { logger.Verbosity = verbosity; }
public VerbosityImportancePair(LoggerVerbosity v, MessageImportance i, bool print) { verbosity = v; importance = i; shouldPrint = print; }
/// <summary> /// Determines whether the current verbosity setting is at least the value /// passed in. /// </summary> internal bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) { return(this.verbosity >= checkVerbosity); }
/// <summary> /// Loads a logger from its assembly, instantiates it, and handles errors. /// </summary> /// <returns>Instantiated logger.</returns> private static ILogger CreateAndConfigureLogger ( LoggerDescription loggerDescription, LoggerVerbosity verbosity, string unquotedParameter ) { ILogger logger = null; try { logger = loggerDescription.CreateLogger(); if (logger == null) { InitializationException.VerifyThrow(logger != null, "LoggerNotFoundError", unquotedParameter); } } catch (IOException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (BadImageFormatException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (SecurityException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (ReflectionTypeLoadException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (MemberAccessException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (TargetInvocationException e) { InitializationException.Throw("LoggerFatalError", unquotedParameter, e.InnerException, true); } // Configure the logger by setting the verbosity level and parameters try { // set its verbosity level logger.Verbosity = verbosity; // set the logger parameters (if any) if (loggerDescription.LoggerSwitchParameters != null) { logger.Parameters = loggerDescription.LoggerSwitchParameters; } } catch (LoggerException) { // Logger failed politely during parameter/verbosity setting throw; } catch (Exception e) { InitializationException.Throw("LoggerFatalError", unquotedParameter, e, true); } return logger; }
public LoggerDescription(string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, LoggerVerbosity verbosity) { throw new NotImplementedException(); }
internal static bool BuildProject ( string projectFile, string[] targets, string toolsVersion, Dictionary<string, string> globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, bool needToValidateProject, string schemaFile, int cpuCount, bool enableNodeReuse, TextWriter preprocessWriter, bool debugger, bool detailedSummary ) { if (String.Equals(Path.GetExtension(projectFile), ".vcproj", StringComparison.OrdinalIgnoreCase) || String.Equals(Path.GetExtension(projectFile), ".dsp", StringComparison.OrdinalIgnoreCase)) { InitializationException.Throw(ResourceUtilities.FormatResourceString("ProjectUpgradeNeededToVcxProj", projectFile), null); } bool success = false; ProjectCollection projectCollection = null; bool onlyLogCriticalEvents = false; try { List<ForwardingLoggerRecord> remoteLoggerRecords = new List<ForwardingLoggerRecord>(); foreach (DistributedLoggerRecord distRecord in distributedLoggerRecords) { remoteLoggerRecords.Add(new ForwardingLoggerRecord(distRecord.CentralLogger, distRecord.ForwardingLoggerDescription)); } // Targeted perf optimization for the case where we only have our own parallel console logger, and verbosity is quiet. In such a case // we know we won't emit any messages except for errors and warnings, so the engine should not bother even logging them. // If we're using the original serial console logger we can't do this, as it shows project started/finished context // around errors and warnings. // Telling the engine to not bother logging non-critical messages means that typically it can avoid loading any resources in the successful // build case. if (loggers.Length == 1 && remoteLoggerRecords.Count == 0 && verbosity == LoggerVerbosity.Quiet && loggers[0].Parameters != null && loggers[0].Parameters.IndexOf("ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) != -1 && loggers[0].Parameters.IndexOf("DISABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) == -1 && loggers[0].Parameters.IndexOf("V=", StringComparison.OrdinalIgnoreCase) == -1 && // Console logger could have had a verbosity loggers[0].Parameters.IndexOf("VERBOSITY=", StringComparison.OrdinalIgnoreCase) == -1) // override with the /clp switch { // Must be exactly the console logger, not a derived type like the file logger. Type t1 = loggers[0].GetType(); Type t2 = typeof(ConsoleLogger); if (t1 == t2) { onlyLogCriticalEvents = true; } } // HACK HACK: this enables task parameter logging. // This is a hack for now to make sure the perf hit only happens // on diagnostic. This should be changed to pipe it through properly, // perhaps as part of a fuller tracing feature. bool logTaskInputs = verbosity == LoggerVerbosity.Diagnostic; if (!logTaskInputs) { foreach (var logger in loggers) { if (logger.Parameters != null && (logger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 || logger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1) ) { logTaskInputs = true; break; } } } if (!logTaskInputs) { foreach (var logger in distributedLoggerRecords) { if (logger.CentralLogger != null) { if (logger.CentralLogger.Parameters != null && (logger.CentralLogger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 || logger.CentralLogger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1) ) { logTaskInputs = true; break; } } } } projectCollection = new ProjectCollection ( globalProperties, loggers, null, Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry, cpuCount, onlyLogCriticalEvents ); if (debugger) { // Debugging is not currently fully supported so we don't want to open // public API for it. Also, we want to have a way to make it work when running inside VS. // So use an environment variable. The undocumented /debug switch is just an easy way to set it. Environment.SetEnvironmentVariable("MSBUILDDEBUGGING", "1"); } if (toolsVersion != null && !projectCollection.ContainsToolset(toolsVersion)) { ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, toolsVersion); } // If the user has requested that the schema be validated, do that here. if (needToValidateProject && !FileUtilities.IsSolutionFilename(projectFile)) { Microsoft.Build.Evaluation.Project project = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion); Microsoft.Build.Evaluation.Toolset toolset = projectCollection.GetToolset((toolsVersion == null) ? project.ToolsVersion : toolsVersion); if (toolset == null) { ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, project.ToolsVersion); } ProjectSchemaValidationHandler.VerifyProjectSchema(projectFile, schemaFile, toolset.ToolsPath); // If there are schema validation errors, an InitializationException is thrown, so if we get here, // we can safely assume that the project successfully validated. projectCollection.UnloadProject(project); } if (preprocessWriter != null && !FileUtilities.IsSolutionFilename(projectFile)) { Project project = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion); project.SaveLogicalProject(preprocessWriter); projectCollection.UnloadProject(project); success = true; } else { BuildRequestData request = new BuildRequestData(projectFile, globalProperties, toolsVersion, targets, null); BuildParameters parameters = new BuildParameters(projectCollection); // By default we log synchronously to the console for compatibility with previous versions, // but it is slightly slower if (!String.Equals(Environment.GetEnvironmentVariable("MSBUILDLOGASYNC"), "1", StringComparison.Ordinal)) { parameters.UseSynchronousLogging = true; } parameters.EnableNodeReuse = enableNodeReuse; parameters.NodeExeLocation = Assembly.GetExecutingAssembly().Location; parameters.MaxNodeCount = cpuCount; parameters.Loggers = projectCollection.Loggers; parameters.ForwardingLoggers = remoteLoggerRecords; parameters.ToolsetDefinitionLocations = Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry; parameters.DetailedSummary = detailedSummary; parameters.LogTaskInputs = logTaskInputs; if (!String.IsNullOrEmpty(toolsVersion)) { parameters.DefaultToolsVersion = toolsVersion; } string memoryUseLimit = Environment.GetEnvironmentVariable("MSBUILDMEMORYUSELIMIT"); if (!String.IsNullOrEmpty(memoryUseLimit)) { parameters.MemoryUseLimit = Convert.ToInt32(memoryUseLimit, CultureInfo.InvariantCulture); // The following ensures that when we divide the use by node count to get the per-limit amount, we always end up with a // positive value - otherwise setting it too low will result in a zero, which will enable only the default cache behavior // which is not what is intended by using this environment variable. if (parameters.MemoryUseLimit < parameters.MaxNodeCount) { parameters.MemoryUseLimit = parameters.MaxNodeCount; } } BuildManager buildManager = BuildManager.DefaultBuildManager; #if MSBUILDENABLEVSPROFILING DataCollection.CommentMarkProfile(8800, "Pending Build Request from MSBuild.exe"); #endif BuildResult results = null; buildManager.BeginBuild(parameters); Exception exception = null; try { try { lock (s_buildLock) { s_activeBuild = buildManager.PendBuildRequest(request); // Even if Ctrl-C was already hit, we still pend the build request and then cancel. // That's so the build does not appear to have completed successfully. if (s_receivedCancel == 1) { buildManager.CancelAllSubmissions(); } } results = s_activeBuild.Execute(); } finally { buildManager.EndBuild(); } } catch (Exception ex) { exception = ex; success = false; } if (results != null && exception == null) { success = results.OverallResult == BuildResultCode.Success; exception = results.Exception; } if (exception != null) { success = false; // InvalidProjectFileExceptions have already been logged. if (exception.GetType() != typeof(InvalidProjectFileException)) { if ( exception.GetType() == typeof(LoggerException) || exception.GetType() == typeof(InternalLoggerException) ) { // We will rethrow this so the outer exception handler can catch it, but we don't // want to log the outer exception stack here. throw exception; } if (exception.GetType() == typeof(BuildAbortedException)) { // this is not a bug and should not dump stack. It will already have been logged // appropriately, there is no need to take any further action with it. } else { // After throwing again below the stack will be reset. Make certain we log everything we // can now Console.WriteLine(AssemblyResources.GetString("FatalError")); #if DEBUG Console.WriteLine("This is an unhandled exception in MSBuild -- PLEASE OPEN A BUG AGAINST THE MSBUILD TEAM."); #endif Console.WriteLine(exception.ToString()); Console.WriteLine(); throw exception; } } } } } // handle project file errors catch (InvalidProjectFileException ex) { // just eat the exception because it has already been logged ErrorUtilities.VerifyThrow(ex.HasBeenLogged, "Should have been logged"); success = false; } finally { FileUtilities.ClearCacheDirectory(); if (projectCollection != null) { projectCollection.Dispose(); } BuildManager.DefaultBuildManager.Dispose(); } return success; }
public AnalyzerManager(ILoggerFactory loggerFactory = null, LoggerVerbosity loggerVerbosity = LoggerVerbosity.Normal) : this(null, loggerFactory, loggerVerbosity) { }
public bool IsVerbosityAtLeast(LoggerVerbosity verbosity) { return((this.verbosity >= verbosity) ? true : false); }
public void FromLoggerVerbosity(LoggerVerbosity v, string expectedResult) { var s = String.Join(" ", VerbosityUtils.GetVerbosityLevel(v)); Assert.That(s, Is.EqualTo(expectedResult), v.ToString()); }
public AnalyzerManager(string solutionFilePath, ILoggerFactory loggerFactory = null, LoggerVerbosity loggerVerbosity = LoggerVerbosity.Normal) { LoggerVerbosity = loggerVerbosity; ProjectLogger = loggerFactory?.CreateLogger <ProjectAnalyzer>(); if (solutionFilePath != null) { solutionFilePath = ValidatePath(solutionFilePath, true); SolutionDirectory = Path.GetDirectoryName(solutionFilePath); GetProjectsInSolution(solutionFilePath); } }
public void AssertVerbosity(LoggerVerbosity expected) { Verbosity.Should().Be(expected, "Logger verbosity mismatch"); }
public PSHostLogger(LoggerVerbosity verbosity) : base(verbosity) { }
/// <summary> /// Add a file logger with the appropriate parameters to the loggers list for each /// non-empty set of file logger parameters provided. /// </summary> private static void ProcessFileLoggers(string[][] groupedFileLoggerParameters, List<DistributedLoggerRecord> distributedLoggerRecords, LoggerVerbosity verbosity, int cpuCount, ArrayList loggers) { for (int i = 0; i < groupedFileLoggerParameters.Length; i++) { // If we had no, say, "/fl5" then continue; we may have a "/fl6" and so on if (groupedFileLoggerParameters[i] == null) continue; string fileParameters = "SHOWPROJECTFILE=TRUE;"; // Use a default log file name of "msbuild.log", "msbuild1.log", "msbuild2.log", etc; put this first on the parameter // list so that any supplied log file parameter will override it if (i == 0) { fileParameters += "logfile=msbuild.log;"; } else { fileParameters += "logfile=msbuild" + i + ".log;"; } if (groupedFileLoggerParameters[i].Length > 0) { // Join the file logger parameters into one string seperated by semicolons fileParameters = AggregateParameters(fileParameters, groupedFileLoggerParameters[i]); } FileLogger fileLogger = new FileLogger(); // Set to detailed by default, can be overidden by fileLoggerParameters LoggerVerbosity defaultFileLoggerVerbosity = LoggerVerbosity.Detailed; fileLogger.Verbosity = defaultFileLoggerVerbosity; if (cpuCount == 1) { // We've decided to use the MP logger even in single proc mode. // Switch it on here, rather than in the logger, so that other hosts that use // the existing ConsoleLogger don't see the behavior change in single proc. fileLogger.Parameters = "ENABLEMPLOGGING;" + fileParameters; loggers.Add(fileLogger); } else { fileLogger.Parameters = fileParameters; // For performance, register this logger using the forwarding logger mechanism, rather than as an old-style // central logger. DistributedLoggerRecord forwardingLoggerRecord = CreateForwardingLoggerRecord(fileLogger, fileParameters, defaultFileLoggerVerbosity); distributedLoggerRecords.Add(forwardingLoggerRecord); } } }
public ConsoleLogger(LoggerVerbosity verbosity) : this(LoggerVerbosity.Normal, null, null, null) { }
/// <summary> /// Executes the program. /// </summary> /// <returns>The exit code of the program.</returns> public int Execute() { LoggerVerbosity verbosity = ForwardingLogger.ParseLoggerVerbosity(_arguments.Verbosity?.LastOrDefault()); ConsoleForwardingLogger consoleLogger = new ConsoleForwardingLogger(_console) { NoWarn = _arguments.NoWarn, Parameters = _arguments.ConsoleLoggerParameters.Arguments.IsNullOrWhiteSpace() ? "ForceNoAlign=true;Summary" : _arguments.ConsoleLoggerParameters.Arguments, Verbosity = verbosity, }; ForwardingLogger forwardingLogger = new ForwardingLogger(GetLoggers(consoleLogger), _arguments.NoWarn) { Verbosity = verbosity, }; using (ProjectCollection projectCollection = new ProjectCollection( globalProperties: null, loggers: new ILogger[] { forwardingLogger, }, remoteLoggers: null, toolsetDefinitionLocations: ToolsetDefinitionLocations.Default, maxNodeCount: 1, #if NET46 onlyLogCriticalEvents: false)) #else onlyLogCriticalEvents : false, loadProjectsReadOnly : true)) #endif { try { forwardingLogger.LogMessageLow("Command Line Arguments: {0}", Environment.CommandLine); forwardingLogger.LogMessageLow("Using MSBuild from \"{0}\"", _msbuildExePath); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies().Where(i => i.FullName.StartsWith("Microsoft.Build"))) { forwardingLogger.LogMessageLow("Loaded assembly: \"{0}\" from \"{1}\"", assembly.FullName, assembly.Location); } (TimeSpan evaluationTime, int evaluationCount) = LoadProjects(projectCollection, forwardingLogger); if (forwardingLogger.HasLoggedErrors) { return(1); } (string solutionFileFullPath, int customProjectTypeGuidCount, int solutionItemCount, Guid solutionGuid) = GenerateSolutionFile(projectCollection.LoadedProjects.Where(i => !i.GlobalProperties.ContainsKey("TargetFramework")), forwardingLogger); if (_arguments.ShouldLaunchVisualStudio()) { bool loadProjectsInVisualStudio = _arguments.ShouldLoadProjectsInVisualStudio(); bool enableShellExecute = _arguments.EnableShellExecute(); string devEnvFullPath = _arguments.DevEnvFullPath?.LastOrDefault(); if (!enableShellExecute || !loadProjectsInVisualStudio || IsCorext) { if (devEnvFullPath.IsNullOrWhiteSpace()) { if (_instance == null) { forwardingLogger.LogError( Program.IsCorext ? $"Could not find a Visual Studio {Environment.GetEnvironmentVariable("VisualStudioVersion")} installation. Please do one of the following:\n a) Specify a full path to devenv.exe via the -vs command-line argument\n b) Update your corext.config to specify a version of MSBuild.Corext that matches a Visual Studio version you have installed\n c) Install a version of Visual Studio that matches the version of MSBuild.Corext in your corext.config" : "Could not find a Visual Studio installation. Please specify the full path to devenv.exe via the -vs command-line argument"); return(1); } if (_instance.IsBuildTools) { forwardingLogger.LogError("Cannot use a BuildTools instance of Visual Studio."); return(1); } devEnvFullPath = Path.Combine(_instance.InstallationPath, "Common7", "IDE", "devenv.exe"); } } VisualStudioLauncher.Launch(solutionFileFullPath, loadProjectsInVisualStudio, devEnvFullPath, forwardingLogger); } try { LogTelemetry(evaluationTime, evaluationCount, customProjectTypeGuidCount, solutionItemCount, solutionGuid); } catch (Exception) { } } catch (InvalidProjectFileException e) { forwardingLogger.LogError(e.Message, e.ErrorCode, e.ProjectFile, e.LineNumber, e.ColumnNumber); return(1); } catch (Exception e) { forwardingLogger.LogError($"Unhandled exception: {e}"); throw; } } return(0); }
public BootstrapperSettings(AnalysisPhase phase, IEnumerable <string> childCmdLineArgs, LoggerVerbosity verbosity, ILogger logger) { if (logger == null) { throw new ArgumentNullException("logger"); } this.analysisPhase = phase; this.childCmdLineArgs = childCmdLineArgs; this.verbosity = verbosity; this.logger = logger; }
public ConsoleLogger(LoggerVerbosity verbosity, WriteHandler write, ColorSetter colorSet, ColorResetter colorReset) { this.verbosity = verbosity; this.indent = 0; this.errorCount = 0; this.warningCount = 0; if (write == null) { this.writeHandler += new WriteHandler(WriteHandlerFunction); } else { this.writeHandler += write; } this.performanceSummary = false; this.showSummary = true; this.skipProjectStartedText = false; errors = new List <string> (); warnings = new List <string> (); this.colorSet = colorSet; this.colorReset = colorReset; events = new List <BuildEvent> (); errorsTable = new Dictionary <string, List <string> > (); warningsTable = new Dictionary <string, List <string> > (); targetPerfTable = new SortedDictionary <string, PerfInfo> (); tasksPerfTable = new SortedDictionary <string, PerfInfo> (); //defaults errorColor = ConsoleColor.DarkRed; warningColor = ConsoleColor.DarkYellow; eventColor = ConsoleColor.DarkCyan; messageColor = ConsoleColor.DarkGray; highMessageColor = ConsoleColor.White; // if message color is not set via the env var, // then don't use any color for it. no_message_color = true; use_colors = false; if (colorSet == null || colorReset == null) { return; } // color support string config = Environment.GetEnvironmentVariable("XBUILD_COLORS"); if (config == null) { use_colors = true; return; } if (config == "disable") { return; } use_colors = true; string [] pairs = config.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string pair in pairs) { string [] parts = pair.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { continue; } if (parts [0] == "errors") { TryParseConsoleColor(parts [1], ref errorColor); } else if (parts [0] == "warnings") { TryParseConsoleColor(parts [1], ref warningColor); } else if (parts [0] == "events") { TryParseConsoleColor(parts [1], ref eventColor); } else if (parts [0] == "messages") { if (TryParseConsoleColor(parts [1], ref messageColor)) { highMessageColor = GetBrightColorFor(messageColor); no_message_color = false; } } } }
public void FromString(string commandLine, LoggerVerbosity expected) { var result = VerbosityUtils.GetVerbosityLevel(expected); Assert.That(VerbosityUtils.GetVerbosityLevel(commandLine), Is.EqualTo(result), commandLine); }
/// <summary> /// Create a logger instance with a specific verbosity. This logs to /// the default console. /// </summary> /// <param name="verbosity">Verbosity level.</param> public ConsoleLogger(LoggerVerbosity verbosity) : this(verbosity, Console.Out.Write, BaseConsoleLogger.SetColor, BaseConsoleLogger.ResetColor) { // do nothing }
/// <summary> /// Instantiates the loggers that are going to listen to events from this build. /// </summary> /// <returns>List of loggers.</returns> private static ILogger[] ProcessLoggingSwitches ( string[] loggerSwitchParameters, string[] distributedLoggerSwitchParameters, string[] verbositySwitchParameters, bool noConsoleLogger, bool distributedFileLogger, string[] fileLoggerParameters, string[] consoleLoggerParameters, string[][] groupedFileLoggerParameters, out List<DistributedLoggerRecord> distributedLoggerRecords, out LoggerVerbosity verbosity, ref bool detailedSummary, int cpuCount ) { // if verbosity level is not specified, use the default verbosity = LoggerVerbosity.Normal; if (verbositySwitchParameters.Length > 0) { // Read the last verbosity switch found verbosity = ProcessVerbositySwitch(verbositySwitchParameters[verbositySwitchParameters.Length - 1]); } ArrayList loggers = ProcessLoggerSwitch(loggerSwitchParameters, verbosity); // Add any loggers which have been specified on the commandline distributedLoggerRecords = ProcessDistributedLoggerSwitch(distributedLoggerSwitchParameters, verbosity); ProcessConsoleLoggerSwitch(noConsoleLogger, consoleLoggerParameters, distributedLoggerRecords, verbosity, cpuCount, loggers); ProcessDistributedFileLogger(distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, cpuCount); ProcessFileLoggers(groupedFileLoggerParameters, distributedLoggerRecords, verbosity, cpuCount, loggers); if (verbosity == LoggerVerbosity.Diagnostic) { detailedSummary = true; } return (ILogger[])loggers.ToArray(typeof(ILogger)); }
protected string GetVerbositySwitch(LoggerVerbosity verbosity, bool useShortSwitchNames) { return($"{(useShortSwitchNames ? "v" : "Verbosity")}={(useShortSwitchNames ? verbosity == LoggerVerbosity.Diagnostic ? "diag" : verbosity.ToString().ToLowerInvariant().Substring(0, 1) : verbosity.ToString())}"); }
/// <summary> /// Process the noconsole switch and attach or not attach the correct console loggers /// </summary> internal static void ProcessConsoleLoggerSwitch ( bool noConsoleLogger, string[] consoleLoggerParameters, List<DistributedLoggerRecord> distributedLoggerRecords, LoggerVerbosity verbosity, int cpuCount, ArrayList loggers ) { // the console logger is always active, unless specifically disabled if (!noConsoleLogger) { // A central logger will be created for single proc and multiproc ConsoleLogger logger = new ConsoleLogger(verbosity); string consoleParameters = "SHOWPROJECTFILE=TRUE;"; if ((consoleLoggerParameters != null) && (consoleLoggerParameters.Length > 0)) { consoleParameters = AggregateParameters(consoleParameters, consoleLoggerParameters); } if (cpuCount == 1) { // We've decided to use the MP logger even in single proc mode. // Switch it on here, rather than in the logger, so that other hosts that use // the existing ConsoleLogger don't see the behavior change in single proc. logger.Parameters = "ENABLEMPLOGGING;" + consoleParameters; loggers.Add(logger); } else { logger.Parameters = consoleParameters; // For performance, register this logger using the forwarding logger mechanism, rather than as an old-style // central logger. DistributedLoggerRecord forwardingLoggerRecord = CreateForwardingLoggerRecord(logger, consoleParameters, verbosity); distributedLoggerRecords.Add(forwardingLoggerRecord); } } }
/// <summary> /// Get the name of a verbosity. /// </summary> /// <param name="verbosity"></param> /// <returns></returns> private static string GetVerbosityName(LoggerVerbosity verbosity) { return(Enum.GetName(typeof(LoggerVerbosity), verbosity)); }
/// <summary> /// Figures out which additional loggers are going to listen to build events. /// </summary> /// <returns>List of loggers.</returns> private static ArrayList ProcessLoggerSwitch(string[] parameters, LoggerVerbosity verbosity) { ArrayList loggers = new ArrayList(); foreach (string parameter in parameters) { string unquotedParameter = QuotingUtilities.Unquote(parameter); LoggerDescription loggerDescription = ParseLoggingParameter(parameter, unquotedParameter, verbosity); loggers.Add(CreateAndConfigureLogger(loggerDescription, verbosity, unquotedParameter)); } return loggers; }
public StubBuildEngine(LoggerVerbosity verbosity) { Verbosity = verbosity; }
/// <summary> /// Parse a command line logger argument into a LoggerDescription structure /// </summary> /// <param name="parameter">the command line string</param> /// <returns></returns> private static LoggerDescription ParseLoggingParameter(string parameter, string unquotedParameter, LoggerVerbosity verbosity) { ArrayList loggerSpec; string loggerClassName; string loggerAssemblyName; string loggerAssemblyFile; string loggerParameters = null; int emptySplits; // ignored // split each <logger type>;<logger parameters> string into two pieces, breaking on the first ; that is found loggerSpec = QuotingUtilities.SplitUnquoted(parameter, 2, true /* keep empty splits */, false /* keep quotes */, out emptySplits, ';'); ErrorUtilities.VerifyThrow((loggerSpec.Count >= 1) && (loggerSpec.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two."); // check that the logger is specified CommandLineSwitchException.VerifyThrow(((string)loggerSpec[0]).Length > 0, "InvalidLoggerError", unquotedParameter); // extract logger parameters if present if (loggerSpec.Count == 2) { loggerParameters = QuotingUtilities.Unquote((string)loggerSpec[1]); } // split each <logger class>,<logger assembly> string into two pieces, breaking on the first , that is found ArrayList loggerTypeSpec = QuotingUtilities.SplitUnquoted((string)loggerSpec[0], 2, true /* keep empty splits */, false /* keep quotes */, out emptySplits, ','); ErrorUtilities.VerifyThrow((loggerTypeSpec.Count >= 1) && (loggerTypeSpec.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two."); string loggerAssemblySpec; // if the logger class and assembly are both specified if (loggerTypeSpec.Count == 2) { loggerClassName = QuotingUtilities.Unquote((string)loggerTypeSpec[0]); loggerAssemblySpec = QuotingUtilities.Unquote((string)loggerTypeSpec[1]); } else { loggerClassName = String.Empty; loggerAssemblySpec = QuotingUtilities.Unquote((string)loggerTypeSpec[0]); } CommandLineSwitchException.VerifyThrow(loggerAssemblySpec.Length > 0, "InvalidLoggerError", unquotedParameter); loggerAssemblyName = null; loggerAssemblyFile = null; // DDB Bug msbuild.exe -Logger:FileLogger,Microsoft.Build.Engine fails due to moved engine file. // Only add strong naming if the assembly is a non-strong named 'Microsoft.Build.Engine' (i.e, no additional characteristics) // Concat full Strong Assembly to match v4.0 if (String.Compare(loggerAssemblySpec, "Microsoft.Build.Engine", StringComparison.OrdinalIgnoreCase) == 0) { loggerAssemblySpec = "Microsoft.Build.Engine,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"; } // figure out whether the assembly's identity (strong/weak name), or its filename/path is provided if (File.Exists(loggerAssemblySpec)) { loggerAssemblyFile = loggerAssemblySpec; } else { loggerAssemblyName = loggerAssemblySpec; } return new LoggerDescription(loggerClassName, loggerAssemblyName, loggerAssemblyFile, loggerParameters, verbosity); }
public CapturingLogger(LoggerVerbosity verbosity) : base(verbosity) { WriteHandler = Write; }
private static ExitType OldOMBuildProject(ExitType exitType, string projectFile, string[] targets, string toolsVersion, Dictionary<string, string> globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, bool needToValidateProject, string schemaFile, int cpuCount) { // Log something to avoid confusion caused by errant environment variable sending us down here Console.WriteLine(AssemblyResources.GetString("Using35Engine")); Microsoft.Build.BuildEngine.BuildPropertyGroup oldGlobalProps = new Microsoft.Build.BuildEngine.BuildPropertyGroup(); // Copy over the global properties to the old OM foreach (KeyValuePair<string, string> globalProp in globalProperties) { oldGlobalProps.SetProperty(globalProp.Key, globalProp.Value); } if (!BuildProjectWithOldOM(projectFile, targets, toolsVersion, oldGlobalProps, loggers, verbosity, null, needToValidateProject, schemaFile, cpuCount)) { exitType = ExitType.BuildError; } return exitType; }
private void LogMessage(LoggerVerbosity messageVerbosity, string message, params object[] args) { if (messageVerbosity == LoggerVerbosity.Info || (messageVerbosity == LoggerVerbosity.Debug && this.Verbosity == LoggerVerbosity.Debug)) { string finalMessage = this.GetFormattedMessage(message, args); Console.WriteLine(finalMessage); } }
/// <summary> /// Determines whether the current verbosity setting is at least the value /// passed in. /// </summary> private bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) { return(_verbosity >= checkVerbosity); }
internal bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) => Verbosity >= checkVerbosity;