Skip to content

Proposal: Introduce a [DiLogger] attribute for automatic logger injection #60717

Open
@domoar

Description

@domoar

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

Ive been working on various ASP.NET Core projects, and Ive noticed that in basically every controller an ILogger gets injected. It starts to feel super repetitive when you have a lot of controllers or services.

Describe the solution you'd like

Ive tried to implement this idea using reflection, but considering the downsides i think a source generator would be better suited for this idea. I have a somewhat basic understanding how source generators work. So i think the steps would be:

  1. Look through the code during build time and find any fields marked with the Attribute [DiLogger].
  2. Automatically generate the constructor (or update it) to add an ILogger parameter if needed.
  3. Make sure the logger gets assigned to the field.

Possible solution:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [DiLogger]
    private readonly ILogger<WeatherForecastController> _logger;

    private readonly IWeatherService _weatherService;

    public WeatherForecastController(IWeatherService weatherService)
    {
        _weatherService = weatherService;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        _logger.LogInformation("Fetching weather forecast");
        return _weatherService.GetForecast();
    }
}

Problems: Not breaking the existing Di container and its infrastructure.

Additional context

I’ve also seen some codebases use a base class approach where the base controller has a logger, and child controllers reuse that. That works, but it still adds some complexity with inheritance, and you still need to inject the logger into the base class. I thought an attribute-based option might keep things simpler and more flexible.

Let me know your thoughts.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions