c# - Asp.Net Core 2.0.1 的 Serilog 设置不生成日志

标签 c# json logging asp.net-core-2.0 serilog

我正在尝试使用 Asp.Net Core 2.0.1、EF 2.0.1 和 MVC 6 在多项目解决方案中将 Serilog 设置为我的记录器。

我已经设置了 Serilog,主要遵循这篇博文中的指南 Set up Serilog post

那篇文章中的 json 有问题,我已经更正并显示在这里

appsettings.json 文件

{
"ApplicationConfiguration": {
  "ConnectionStrings": {
    "DevelopmentConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Development;Trusted_Connection=True;MultipleActiveResultSets=true"      
  },      
  "ApplicationInfo": {
    "VersionNumber": "1.0.0",
    "Author": "Jimbo",
    "ApplicationName": "CustomTemplate",
    "CreatedOn": "November 20, 2017"
  },
  "Serilog": {
    "Using": [
      "Serilog.Sinks.RollingFile",
      "Serilog.Sinks.Async",
      "Serilog.Sinks.ApplicationInsights",
      "Serilog.Sinks.Console",
      "Serilog.Sinks.Seq"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "RollingFile",
              "Args": { "pathFormat": "Logs/log-{Date}.log" }
           }
          ]
        }
      }
    ],
    "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],
    "Properties": {
      "Application": "CustomTemplate" 
    }
  }
}
}

我在 Program.cs 的 Main 方法中进行记录器配置工作

public static int Main(string[] args)
{
    var currentEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); 

    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{currentEnv}.json", optional: true)
        .AddEnvironmentVariables()
        .Build();

    //Configure logger
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        //do this for now
        //TODO:figure out how to add to Serilog config in appsettings.json
        .WriteTo.Seq("http://localhost:5341")
        .CreateLogger();

    Log.Information("Logger created");

    try
    {
        Log.Information("Starting web host");
        BuildWebHost(args).Run();
        return 0;
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Web Host terminated unexpectedly");
        return 1;
    }
    finally
    {
        Log.CloseAndFlush();
    }
    //BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();

在我的启动方法中

services.AddLogging(loggingBuilder =>
            loggingBuilder.AddSerilog(dispose: true));

我假设 Serilog 会在我运行应用程序后创建 Logs 文件夹,但没有 Log 文件夹或日志。我在解决方案的根目录和 Web 应用程序项目中添加了一个 Logs 文件夹,然后再次运行它。没有日志。博文作者建议查看机器根文件夹。我查看了 C 和 OneDrive 主文件夹(存储在 OneDrive 上的解决方案文件),但那里也没有日志。

然后我注意到堆栈跟踪警告

System.IO.FileNotFoundException occurred HResult=0x80070002 Message=The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\Users\OneDrive\TestingConfigurationAspNetCore2\TestMvcApp\bin\Debug\netcoreapp2.0\appsettings.json'. Source= StackTrace: at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload) at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load() at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers) at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()

我之前收到过这个警告,这就是我在配置设置中添加 set bath path 方法的原因,因为应用程序在代码行失败

.AddJsonFile("appsettings.json")

这很明显,因为在 bin 文件夹中,文件不叫 appsettings.json,它叫 TestMvcApp.runtimeconfig.json。

一旦我添加了 .SetBasePath,代码就会运行,所以我在配置设置之后放置了一个断点。配置对象包含我的 appsettings.json 文件中的所有设置,那么为什么我会收到堆栈跟踪错误?我不知道,但我敢打赌这就是为什么没有日志的原因(控制台中也没有日志消息出现)

对于堆栈跟踪错误的原因或为什么没有日志消息写入日志文件或显示在控制台上的任何帮助,我们将不胜感激。

最佳答案

which was fairly obvious because in the bin folder the file isn't called appsettings.json, its called TestMvcApp.runtimeconfig.json.

TestMvcApp.runtimeconfig.json 不是您的 appsettings.json,它是一个运行时配置文件,从文件名中可以​​清楚地看出。

我敢打赌,您的 appsettings.json 在构建期间并未复制到输出目录。要解决此问题,请在 Visual Studio 解决方案资源管理器中选择 appsettings.json,在上下文菜单中选择属性并将“复制到输出目录”设置为“始终复制”或“如果更新则复制”:

您的 json 配置也有几个问题:

  1. Serilog 部分不应位于 ApplicationConfiguration 部分内。它应该在同一级别,即顶级部分。
  2. 您还有一个可疑的 WriteTo 部分,其中一个接收器 (RollingFile) 位于另一个接收器 (Async) 中。点这里sample json configuration用于 Serilog。
  3. 为了使用所有这些接收器(Serilog.Sinks.RollingFileSerilog.Sinks.Console),您应该安装相应的接收器 NuGets:Serilog.Sinks.RollingFile , Serilog.Sinks.Console

这是适合我的配置文件(仅限 RollingFile sink):

{
    "ApplicationConfiguration": {
        "ConnectionStrings": {
            "DevelopmentConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Development;Trusted_Connection=True;MultipleActiveResultSets=true"
        },
        "ApplicationInfo": {
            "VersionNumber": "1.0.0",
            "Author": "Jimbo",
            "ApplicationName": "CustomTemplate",
            "CreatedOn": "November 20, 2017"
        }
    },
    "Serilog": {
        "Using": [
            "Serilog.Sinks.RollingFile"
        ],
        "MinimumLevel": {
            "Default": "Information",
            "Override": {
                "Microsoft": "Warning"
            }
        },
        "WriteTo": [
            {
                "Name": "RollingFile",
                "Args": { "pathFormat": "c:\\log-{Date}.log" }
            }
        ],
        "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
        "Properties": {
            "Application": "CustomTemplate"
        }
    }
}

enter image description here

关于c# - Asp.Net Core 2.0.1 的 Serilog 设置不生成日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47511440/

相关文章:

python - 以编程方式读取 Django Logger 数据?

java - 如何在JavaFX TextArea中显示日志?

c# - MVC C# 多个异步 ajax 调用

c# - 如何附加到进程并调试未构建的代码?

ios - 获取 JSON 时文件名/路径无效

json - Postgresql 从 Json 对象到数组

php - Silverstripe:作为 JSON 的 CMS 页面?

java - 使用 Jetty Websocket 客户端时如何抑制日志输出到标准输出?

c# - 只允许特定字母到 DataGridView 单元格

c# - 如何根据多列对DataTable进行排序?