kisetu
kisetu

Reputation: 187

Pass Ilogger on non-controller models

I am creating an app in .net core and I'm trying to output a log.

I was able to log output from the controller and I also want to log output from the model, which is shown below.

Unfortunately, I don't know what to pass as arguments to the constructor. My guess is the same Ilogger<controller> as the controller, but I would like to know if there is a correct way.

Thanks in advance.

Controller:

public class SampleController : Controller {
    public readonly ILogger<SampleController > _logger;
    public SampleController (ILogger<SampleController > logger)
    {
        _logger = logger;
    }


    [HttpGet("[action]")]
    public string FindSample()
    {
        _logger.LogInformation("FindSample Start");

        // ***** Is it necessary to carry over the log of the sample controller to a much lower DAO from here? *****
        var model = new SampleModel(_logger);
        var result = model.Find();

        _logger.LogInformation("FindSample End");
        return result;
    }
}

Model:

    public class SampleModel
    {
        public readonly ILogger<SampleController> _logger;
        public SampleModel(ILogger<SampleController> logger)
        {
            _logger = logger;
        }

        public string Find()
        {
            _logger.LogInformation("FindModel Start");

            var dao = new SampleDao(_logger);
            var code = dao.GetCode();

            _logger.LogInformation("FindModel End");
            return code;
        }
    }

Dao:

    public class SampleDao
    {
        public readonly ILogger<SampleController> _logger;
        public SampleContext SampleContext;

        // ***** Should I pass it as an argument forever? *****
        public SampleDao(ILogger<SampleController> logger)
        {
            _logger = logger;
            if (SampleContext == null)
            {
                SampleContext = new SampleContext();
            }
        }

        public string GetCode()
        {
            _logger.LogInformation("GetCode Start");

            var code = SampleContext.SampleTable.FirstOrDefault().code;

            _logger.LogInformation("GetCode End");
            return code;
        }
    }

Upvotes: 6

Views: 2870

Answers (1)

carlos chourio
carlos chourio

Reputation: 873

You should pass as a generic argument the class in which the logger is being injected. So you should use:

In your Dao

ILogger<SampleDao> logger

In your Model

ILogger<SampleModel> logger

For more information you could check: Logging in ASP.NET core

Upvotes: 4

Related Questions