Algorithms, Blockchain and Cloud

C# Custom Logger Sample for MSBuild


The msbuild.exe is the core of the Visual Studio compiler. It has a switch option /verbosity which can be one of the values: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]. There is no such option if you just want to know how many compiler warnings and errors without listing the other messages.

To do this, you could use a customer logger, which can be written in .NET, such as C#.

using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

public class CustomLogger: Logger
{
  private int warnings = 0;
  private int errors = 0;

  public override void Initialize(IEventSource eventSource)
  {
    eventSource.WarningRaised += ( s, e ) => ++warnings;
    eventSource.ErrorRaised += ( s, e ) => ++errors;
    eventSource.BuildFinished += ( s, e ) =>
    {
      Console.WriteLine( errors == 0 ? "Build succeeded." : "Build failed." );
      Console.WriteLine( String.Format( "{0} Warning(s)", warnings ) );
      Console.WriteLine( String.Format( "{0} Error(s)", errors ) );
    };
  }
}

You can compile this file in Visual Studio or in command line:

csc /t:library CustomLogger.cs /reference:Microsoft.Build.Utilities.v4.0.dll;Microsoft.Build.Framework.dll

Then, specify this custom logger when you use msbuild.

msbuild /nologo /logger:CustomLogger.dll /noconsolelogger project.sln

That is it, it will just use the custom logger to print out the number of warnings and errors.

–EOF (The Ultimate Computing & Technology Blog) —

252 words
Last Post: How to Count The Number of General Exceptions (C#) using PowerShell to Adapter in Jenkins Build Server?
Next Post: How to Put Signature on PDF Document/File ?

The Permanent URL is: C# Custom Logger Sample for MSBuild (AMP Version)

Exit mobile version