如何在服务器IIS上实现iLoggerFactory?

时间:2019-04-03 08:51:07

标签: iis logging asp.net-core-2.1

我在.Net Core API上实现iLoggerFactory,步骤:

  • 创建我的文件夹“日志”
  • 在“日志”文件夹(在 startup.ts 中)中的日志实现

    public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
    {
        // log implementation
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        loggerFactory.AddEventSourceLogger();
        loggerFactory.AddFile("logs/app-{Date}.txt");
    
        app.UseStaticFiles();
        app.UseCors("AnyOrigin");
        app.UseSwagger();
    
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebToolAPI");
            c.RoutePrefix = string.Empty;
        });
        app.UseMvc();
    }
    
  • 然后我创建一些登录控制器,如下所示:

    _log.LogError("\r\n -- \r\n Datetime : {0} \r\n ERROR : id'" + id + "' not found \r\n --", DateTime.Now);
    

当我在本地计算机上对其进行测试时,它可以工作,但是当我将代码放入IIS服务器时,它就无法工作。它不会在我的日志文件夹中创建日志。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

Startup.cs 中:

public class Startup
{
    string LogFilePath;
    public Startup(IHostingEnvironment env)
    {
        // location of the logs
        var exePath = Assembly.GetEntryAssembly().Location.ToString();
        var directoryPath = Path.GetDirectoryName(exePath);
        LogFilePath = Path.Combine(directoryPath + "\\logs\\"); // you can replace "logs" by an other folder name
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
    {
        loggerFactory.AddDebug();
        loggerFactory.AddFile(LogFilePath + "api-{Date}.txt",LogLevel.Debug,null,false,null,30); // you can replace "api" by an other file name for your log
    }
}

Program.cs 中:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseKestrel()
        .UseIISIntegration()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>();
}