如何调用参数类型为ILogger的方法

时间:2018-10-07 10:48:01

标签: c#

我想调用一个定义如下的方法

public async Task SomeMethod(string name, bool isWindowsOs, ILogger log)
{
    this.Name = name;
    this.isWindows = isWindowsOs;
    this.logger = log;   
    string configPath = 
        Utility.GetFilePathAsPerOs(this.ConfigurationFilePath, isWindows);

    if (!System.IO.File.Exists(ConfigPath))
    {
        Console.WriteLine($"{ConfigPath} was not found");
        logger.Error($"[{this.Name}] : Configuration file not found");
        await Task.CompletedTask;
    }  
    // Rest of the Code
}

由于在调用Initialise方法时,对于为ILogger类型传递什么参数感到困惑,我还没有处理日志记录。有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

ASP.NET Core受依赖项注入支持,为此,ILogger旨在鼓励最佳实践(DI) 但是,如果要在.net Core中实现此目的,则必须执行以下步骤:

Install-Package Microsoft.Extensions.Logging

在这里我想使用控制台进行日志记录

Install-Package Microsoft.Extensions.Logging.Console

,您可以尝试执行以下操作:

 class Program
    {
        private  static ILogger logger;
        private bool isWindows;

        static async Task Main(string[] args)
        {
          ILoggerFactory loggerFactory = new LoggerFactory().AddConsole();



            logger = loggerFactory.CreateLogger<Program>();

            logger.LogError("ooops");
            await new Program().SomeMethod("name", true, logger);

           Console.ReadLine();



        }
        public async Task SomeMethod(string name, bool isWindowsOs, ILogger log)
        {
            this.Name = name;
            this.isWindows = isWindowsOs;
            logger = log;
            //string configPath =
            //    Utility.GetFilePathAsPerOs(this.ConfigurationFilePath,
            //        isWindows);

            //if (!System.IO.File.Exists(ConfigPath))
            //{
            //    Console.WriteLine($"{ConfigPath} was not found");
            //    logger.Error($"[{this.Name}] : Configuration file not found");
            //    await Task.CompletedTask;
            //}
             logger.LogInformation("this is just confirmation for a successfull task");
            logger.LogError("ooops");

            // Rest of the Code
        }

        public string Name { get; set; }
    }

结果

fail: ConsoleApp1.Program[0]
      ooops
info: ConsoleApp1.Program[0]
      this is just confirmation for a successfull task
fail: ConsoleApp1.Program[0]
      ooops

注意
此示例使用控制台作为提供程序,您可以添加其他提供程序,例如Serilog或Nlog

此示例使用async Task Main,它需要启用c#7.1支持功能

答案 1 :(得分:0)

我建议您在这里查找Logging best practices,但是由于Logger实现了ILogger(并且我猜您正在使用Log4Net),因此对该方法的调用应如下所示:

//class code
Logger log = LogManager.GetCurrentClassLogger()
var result = AsyncContext.RunTask(MyAsyncMethod("", true, log).Result;

//log method
public async Task SomeMethod(string name, bool isWindowsOs, ILogger log)
{
            this.Name = name;
            this.isWindows = isWindowsOs;
            this.logger = log;   
            string configPath = 
            Utility.GetFilePathAsPerOs(this.ConfigurationFilePath, 
                       isWindows);

            if (!System.IO.File.Exists(ConfigPath))
            {
                Console.WriteLine($"{ConfigPath} was not found");
                logger.Error($"[{this.Name}] : Configuration file not found");
                await Task.CompletedTask;
            }  
            // Rest of the Code
}

这是基本代码段,您可以通过多种方式调用异步方法,并将其带到任何需要的地方。