在非控制器模型上传递Ilogger

时间:2019-07-11 00:46:16

标签: c# asp.net-core asp.net-core-mvc nlog

我正在.net核心中创建一个应用,并且正在尝试输出日志。

我能够记录控制器的输出,我也想记录模型的输出,如下所示。

不幸的是,我不知道将什么作为参数传递给构造函数。我的猜测与控制器Ilogger<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;
    }
}

型号:

    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;
        }
    }

道:

    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;
        }
    }

1 个答案:

答案 0 :(得分:1)

您应该将注入记录器的类作为通用参数传递。所以你应该使用:

在您的道中

ILogger<SampleDao> logger

在您的模型中

ILogger<SampleModel> logger

有关更多信息,您可以检查: Logging in ASP.NET core