dotnet / dotnet/msbuild

[Proposal] Add adapter for `TaskLoggingHelper` and `ILogger`

Open
#8,061 6 comments 1 reaction 0 assignees View on GitHub
backlog Feature Request triaged
Dominant language
C#
Stars
5.5k
Forks
1.5k
Avg merge
1d 8h
Merged PRs (30d)
141

Description

## Context
A common setup that we have is that we have some business logic in some library. We want to then call into this logic from different entrypoints:
- CLI tool
- Web service
- MSBuild tasks

The usual way to approach this is to use `Microsoft.Extensions.DependencyInjection` to build the classes and `Microsoft.Extensions.Logging.ILogger` for generic logging. Then, in various environments, we inject the right logger:
- The CLI will usually plug in the console logger via `.AddConsole()`
- The web service can for instance make the service log into Application Insights via `.AddApplicationInsightsTelemetry()`

The MSBuild environment uses the `Microsoft.Build.Utilities.Task.Log` member (`TaskLoggingHelper` class) but it is not possible to plug this well together with the `ILogger` interface that is quite native to .NET these days.

## Goal

Ideally, similarly to the other options, we would have:
- [ ] An adapter that would get an instance of the `TaskLoggingHelper` as a parameter and would implement the `ILogger` interface.
- [ ] An easy way how to inject task's `Log` as the `ILogger` interface through the dependency injection.

The adapter should ideally adhere to verbosity rules and similar setting.

## Example

Something like this comes to mind:
```csharp
public class CustomTask : Task
{
private readonly IServiceProvider _serviceProvider;

public VirtualMonoRepo_Initialize()
{
_serviceProvider = CreateServiceProvider();
}

public override bool Execute()
{
var myCustomLogic = _serviceProvider.GetRequiredService();
return myCustomLogic.DoSomething();
}

private IServiceProvider CreateServiceProvider() =>
new ServiceCollection()
.AddBusinessLogic() // this registers my app's classes into DI
.AddTaskLogging(Log) // this registers current task's logger as ILogger
.BuildServiceProvider();
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.