简体   繁体   English

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

[英]Serilog setup for Asp.Net Core 2.0.1 not producing logs

I am trying to set up Serilog as my logger in a multi project solution using Asp.Net Core 2.0.1, EF 2.0.1 and MVC 6. 我正在尝试使用Asp.Net Core 2.0.1,EF 2.0.1和MVC 6在多项目解决方案中将Serilog设置为记录器。

I have set up Serilog, mostly following the guidelines from this blog post Set up Serilog post 我已经按照此博客文章中的指南设置了Serilog。

There is a problem with the json in that post, which I've corrected and is shown here 该帖子中的json存在问题,我已对其进行了更正,并在此处显示

appsettings.json file 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" 
    }
  }
}
}

I have the logger configuration work in the Main method of Program.cs 我在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();

And in my Startup method 在我的启动方法中

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

I was assuming Serilog would create the Logs folder once I ran the application, but no Log folder or logs. 我以为Serilog一旦运行应用程序便会创建Logs文件夹,但是没有Log文件夹或日志。 I added a Logs folder to both the root of the solution, and the web app project and ran it again. 我在解决方案的根目录和Web应用程序项目中都添加了一个Logs文件夹,然后再次运行它。 No logs. 没有日志。 The blog post author suggested looking in the machines root folder. 博客文章作者建议在计算机的根文件夹中查找。 I looked both in C and OneDrive main folders (Solution Files stored on OneDrive) but there were no logs there either. 我同时查看了C和OneDrive主文件夹(解决方案文件存储在OneDrive中),但那里也没有日志。

I then noticed a stack trace warning 然后我注意到了堆栈跟踪警告

System.IO.FileNotFoundException occurred HResult=0x80070002 Message=The configuration file 'appsettings.json' was not found and is not optional. 发生System.IO.FileNotFoundException HResult = 0x80070002消息=找不到配置文件'appsettings.json',它不是可选的。 The physical path is 'C:\\Users\\OneDrive\\TestingConfigurationAspNetCore2\\TestMvcApp\\bin\\Debug\\netcoreapp2.0\\appsettings.json'. 物理路径为“ 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() Source = StackTrace:在Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(布尔值重载)在Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList 1提供者)处。 Extensions.Configuration.ConfigurationBuilder.Build()

I was getting this warning before, which is why I added the set bath path method in the configuration set up, because the application was failing at the code line 我之前收到此警告,这就是为什么我在配置设置中添加set bath path方法的原因,因为应用程序在代码行失败

.AddJsonFile("appsettings.json")

which was fairly obvious because in the bin folder the file isn't called appsettings.json, its called TestMvcApp.runtimeconfig.json. 这非常明显,因为在bin文件夹中,该文件未称为appsettings.json,而名为TestMvcApp.runtimeconfig.json。

Once I added .SetBasePath, the code ran through so I put a breakpoint after the configuration setup. 添加.SetBasePath之后,代码就会通过,因此在配置设置后放置了一个断点。 The configuration object contains all the settings from my appsettings.json file, so why I am getting that stack trace error? 配置对象包含我的appsettings.json文件中的所有设置,那么为什么会出现该堆栈跟踪错误? I don't know but I'll bet a dollar it is why there are no logs (no log messages appear in the console either) 我不知道,但我敢打赌,这就是为什么没有日志(控制台中也没有日志消息)的原因

Any help on why the stack trace error or why there are no log messages being written to the log file or displayed on the console would be most appreciated. 对于为什么堆栈跟踪错误或为什么没有日志消息写入日志文件或在控制台上显示的任何帮助,将不胜感激。

which was fairly obvious because in the bin folder the file isn't called appsettings.json, its called TestMvcApp.runtimeconfig.json. 这非常明显,因为在bin文件夹中,该文件未称为appsettings.json,而名为TestMvcApp.runtimeconfig.json。

TestMvcApp.runtimeconfig.json is not your appsettings.json , it's a runtime configuration file as it's clear from the file name. TestMvcApp.runtimeconfig.json不是您的appsettings.json ,它是一个运行时配置文件,因为从文件名可以明显看出。

I bet that your appsettings.json is just not copied to the output directory during the build. 我敢打赌,您的appsettings.json不会在构建过程中复制到输出目录中。 To fix that select appsettings.json in Visual Studio Solution explorer, in context menu select properties and set 'Copy to Output Directory' to 'Copy always' or 'Copy if newer': 要在Visual Studio解决方案资源appsettings.json中修复选择appsettings.json问题,请在上下文菜单中选择属性,然后将“复制到输出目录”设置为“始终复制”或“如果更新则复制”:

Also your json configuration has several issues: 另外,您的json配置有几个问题:

  1. Serilog section should not be inside ApplicationConfiguration section. Serilog部分不应位于ApplicationConfiguration部分中。 It should be on the same level, ie top-level section. 它应该在同一级别,即顶级部分。
  2. You also has suspicious WriteTo section with one sink ( RollingFile ) inside another ( Async ). 您还有一个可疑的WriteTo部分,其中一个接收器( RollingFile )位于另一个接收器( Async )中。 Check here sample json configuration for Serilog. 在此处检查Serilog的示例json配置
  3. In order to use all those sinks ( Serilog.Sinks.RollingFile , Serilog.Sinks.Console ) you should install corresponding sink NuGets: Serilog.Sinks.RollingFile , Serilog.Sinks.Console , etc. 为了使用所有这些接收器( Serilog.Sinks.RollingFileSerilog.Sinks.Console ),您应该安装相应的接收器NuGets: Serilog.Sinks.RollingFileSerilog.Sinks.Console等。

Here is configuration file (with RollingFile sink only) that works fine for me: 这是适合我的配置文件(仅适用于RollingFile接收器):

{
    "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"
        }
    }
}

在此处输入图片说明

The accepted answer only logged some messages for my project. 接受的答案仅记录了我的项目的一些消息。 I'm not sure why. 我不知道为什么。 Ondrej Balas's approach worked better for me. Ondrej Balas的方法对我来说更好。

Install these Nuget packages: 安装以下Nuget软件包:

  • Serilog 塞里洛格
  • Serilog.AspNetCore Serilog.AspNetCore
  • Serilog.Settings.Configuration Serilog.Settings.Configuration
  • Serilog.Sinks.Console Serilog.Sinks.Console
  • Serilog.Sinks.RollingFile Serilog.Sinks.RollingFile

Program.cs needs .UseSerilog() added: Program.cs需要添加.UseSerilog()

    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>

        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            })
            .UseStartup<Startup>()
            .UseSerilog()
            .Build();

Startup.cs needs a couple of changes Startup.cs需要进行一些更改

one in the constructor: 构造函数中的一个:

    public Startup(IConfiguration configuration)
    {
        Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();

        Configuration = configuration;
    }

another in Configure() : Configure()另一个:

    loggerFactory.AddSerilog();

    if (env.IsDevelopment())
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    }

appsettings.json needs a Serilog config entry in root : appsettings.jsonroot中需要一个Serilog配置条目:

"Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
        }
    },
    "WriteTo": [
        { "Name": "Console" },
        {
            "Name": "RollingFile",
            "Args": {
                "pathFormat": "logs\\log-{Date}.log",
                "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}"
            }
        }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
        "Application": "My Application"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM