public void Attach() { try { _projectsLookup.Clear(); const BindingFlags InterfacePropertyFlags = BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance; var buildManager = Microsoft.Build.Execution.BuildManager.DefaultBuildManager; var buildHostType = buildManager.GetType().Assembly.GetType("Microsoft.Build.BackEnd.IBuildComponentHost"); var loggingSeviceProperty = buildHostType.GetProperty("LoggingService", InterfacePropertyFlags); object loggingServiceObj; try { // Microsoft.Build.BackEnd.ILoggingService loggingServiceObj = loggingSeviceProperty.GetValue(buildManager, null); } catch (TargetInvocationException ex) { _logger.Error(ex, "Microsoft.Build.BackEnd.ILoggingService is not available."); LoggerState = RegisterLoggerResult.FatalError; return; } var loggersProperty = loggingServiceObj.GetType().GetProperty("Loggers", InterfacePropertyFlags); var loggers = (ICollection <ILogger>)loggersProperty.GetValue(loggingServiceObj, null); var logger = loggers.FirstOrDefault(x => x is BuildOutputLogger && ((BuildOutputLogger)x)._loggerId.Equals(_loggerId)); if (logger != null) { LoggerState = RegisterLoggerResult.AlreadyExists; return; } var registerLoggerMethod = loggingServiceObj.GetType().GetMethod("RegisterLogger"); var registerResult = (bool)registerLoggerMethod.Invoke(loggingServiceObj, new object[] { this }); LoggerState = registerResult ? RegisterLoggerResult.RegisterSuccess : RegisterLoggerResult.RegisterFailed; } catch (Exception ex) { _logger.Error(ex, "Error registering MSBuild Logger"); LoggerState = RegisterLoggerResult.FatalError; } }
private void RegisterLogger() { _buildLogger = null; // Same Verbosity as in the Error List. const LoggerVerbosity LoggerVerbosity = LoggerVerbosity.Quiet; RegisterLoggerResult result = BuildOutputLogger.Register(_parsingErrorsLoggerId, LoggerVerbosity, out _buildLogger); if (result == RegisterLoggerResult.RegisterSuccess) { var eventSource = _buildLogger.EventSource; eventSource.MessageRaised += (s, e) => EventSource_ErrorRaised(_buildLogger, e, ErrorLevel.Message); eventSource.WarningRaised += (s, e) => EventSource_ErrorRaised(_buildLogger, e, ErrorLevel.Warning); eventSource.ErrorRaised += (s, e) => EventSource_ErrorRaised(_buildLogger, e, ErrorLevel.Error); } else if (result == RegisterLoggerResult.AlreadyExists) { _buildLogger.Projects?.Clear(); } }