简体   繁体   English

Serilog 不写入文件(.net core 2.2)

[英]Serilog not writing to File (.net core 2.2)

I am writing a web service that is using Serilog.我正在编写一个使用 Serilog 的 Web 服务。 I was having problems getting files to write out (but console logging worked).我在获取要写出的文件时遇到问题(但控制台日志记录有效)。 I noticed that the setup changed when .net core 2.0 came out based on this and this pages' explanation.我注意到当 .net core 2.0 基于这个这个页面的解释出来时,设置发生了变化。

However, now, I can't see any logging (perhaps in the past the default M$ loggers were actually what I was seeing).但是,现在,我看不到任何日志记录(也许过去默认的 M$ 记录器实际上就是我所看到的)。

Here's how program.cs is set up:以下是program.cs的设置方式:

public class Program
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .AddUserSecrets<Startup>()
            .Build();

        public static int Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration.GetSection("Serilog"))
                .CreateLogger();

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

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

My appsettings.json has this section in the root:我的 appsettings.json 在根目录中有这个部分:

"Serilog": {
    "Using" : ["Serilog.Sinks.Console", "Serilog.Sinks.File"], 
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      },
      "Enrich" :  ["FromLogContext"],
      "WriteTo":  [
        {"Name": "Console" },
        {"Name": "Debug" },
        {"Name": "File", "Args":  {"path": "%LogDir%\\sampleapp\\log-{Date}.txt", "rollingInterval":  "Day", "shared": true }  }
      ] 
    },
    "Properties": {
      "Application": "sampleapp"
    }
  },

Note that %LogDir% is an environment variable on my machine and resolves fine in other applications.请注意, %LogDir%是我机器上的环境变量,在其他应用程序中也能正常解析。 The path is already created and the Logs folder has full RW permissions for the credentials this app uses.该路径已创建,并且 Logs 文件夹对此应用程序使用的凭据具有完全 RW 权限。

I call logging like so...我这样称呼日志记录...

    private readonly ILogger<PartnerController> _logger;
    private readonly IPartnerDao _partnerDao;

    public PartnerController(ILogger<PartnerController> logger, IPartnerDao partnerDao)
    {
        _logger = logger;
        _partnerDao = partnerDao;
    }

    [HttpGet]
    [Route("{titleCode}")]
    public async Task<IActionResult> Get(string titleCode)
    {
        _logger.LogInformation("Test logging");
    }

Yet, somehow nothing shows in the ASP.NET Core Web Server window and not file is created on my machine when running the service.然而,在运行服务时, ASP.NET Core Web Server窗口中没有显示任何内容,也没有在我的机器上创建文件。

Am I missing something obvious?我错过了一些明显的东西吗?

Turns out I had copied some of the JSON from documentation incorrectly.结果我错误地从文档中复制了一些 JSON。 It's hard to tell but in the original question I actually had Enrich , WriteTo , and Properties sections embedded within the MinimumLevel section.很难说,但在最初的问题中,我实际上在MinimumLevel部分中嵌入了EnrichWriteToProperties部分。

Obviously this prevented Serilog from correctly knowing which Sinks to write to.显然,这阻止了 Serilog 正确知道要写入哪个接收器。

Here's my corrected settings JSON:这是我更正的设置 JSON:

"Serilog": {
    "Using": ["Serilog.Sinks.Console", "Serilog.Sinks.File"],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": ["FromLogContext"],
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "Debug" },
      {
        "Name": "File",
        "Args": {
          "path": "%LogDir%\\sampleapp\\log-.txt",
          "rollingInterval": "Day",
          "shared": true
        }
      }
    ],
    "Properties": {
      "Application":  "sampleapp" 
    } 
  },

Note that I also removed the {Date} from the filename.请注意,我还从文件名中删除了{Date} Apparently it'll tack that on if you set the rolling interval to day....显然,如果您将滚动间隔设置为天,它就会坚持下去......

appsettings.Development.json overwrite settings in appsettings.json appsettings.Development.json覆盖设置appsettings.json

I repeat again, configuration in appsettings.Development.json will take precedence over appsettings.json .我再次重申, appsettings.Development.json配置将优先appsettings.json I know that sounds obvious but I bet someone could overlook this in the future just like I did.我知道这听起来很明显,但我敢打赌,将来有人会像我一样忽略这一点。

I spent nearly an hour scratching my head why no log was being written to the file, only to notice later I had only Console sink in my appsettings.Development.json (effectively removing my File sink in appsettings.json duh!).我花了将近一个小时摸不着头脑,为什么没有将日志写入文件,后来才注意到我的appsettings.Development.json只有Console器(有效地删除了appsettings.json Fileappsettings.json !)。

Here is a sample of a proper configuration (modify according to your needs):以下是正确配置的示例(根据您的需要进行修改):

ASP.NET Core 3.1 ASP.NET 核心 3.1

Program.cs程序.cs

using Microsoft.AspNetCore.Hosting;
using Serilog;
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog.Core;

namespace My.App
{
    public class Program
    {
        private static bool IsDevelopment =>
            Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";

        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false, true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
            .AddEnvironmentVariables()
            .Build();

        public static Logger Logger { get; } = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .Enrich.FromLogContext()
            .CreateLogger();

        public static int Main(string[] args)
        {
            Log.Logger = Logger;

            try
            {
                Log.Information("Starting...");
                var host = CreateHostBuilder(args).Build();                      
                host.Run();                        
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var host = Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .UseServiceProviderFactory(
                    new AutofacMultitenantServiceProviderFactory(Startup.ConfigureMultitenantContainer))
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .UseIISIntegration()
                        .UseStartup<Startup>();
                });

            return host;
        }
    }
}

ASP.NET Core 2.2 ASP.NET 核心 2.2

Program.cs程序.cs

public class Program
{
    public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .AddEnvironmentVariables()
        .Build();

    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .Enrich.FromLogContext()
            .CreateLogger();

        try
        {
            Log.Information("Starting...");
            CreateWebHostBuilder(args).Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

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

appsettings.json appsettings.json

{  
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
  }
}

appsettings.Development.json appsettings.Development.json

{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "Console"
            },
            {
              "Name": "Debug"
            },
            {
              "Name": "DiagnosticTrace"
            },
            {
              "Name": "File",
              "Args": {
                "path": "/home/log/api-log-.txt",
                "rollingInterval": "Day",
                "retainedFileCountLimit": 7,
                "buffered": true
              }
            }
          ]
        }
      }
    ]
  }
}

appsettings.Production.json appsettings.Production.json

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information"
    },
    "WriteTo": [
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "ApplicationInsights",
              "Args": {
                "restrictedToMinimumLevel": "Information",
                "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
              }
            },
            {
              "Name": "Email",
              "Args": {
                "EmailConnectionInfo": {
                  "EmailSubject": "PRODUCTION error logs",
                  "FromEmail": "xxxxxxx",
                  "ToEmail": "xxxxxxx",
                  "MailServer": "xxxx",
                  "NetworkCredentials": {
                    "username": "xxxxxx",
                    "password": "xxxxxx",
                    "domain": "xxxxx"
                  },
                  "Port": 25
                },
                "restrictedToMinimumLevel": "Error"
              }
            },
            {
              "Name": "File",
              "Args": {
                "path": "/home/log/api-log-.txt",
                "rollingInterval": "Day",
                "retainedFileCountLimit": 15,
                "buffered": true
              }
            }
          ]
        }
      }
    ]
  }
}

Here's my corrected settings JSON:这是我更正的设置 JSON:

In Startup class:启动类中:

Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(config)
                         .Enrich.With<EventTypeEnricher>()
                         .CreateLogger();

In appsettings.jsonappsettings.json 中

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.Seq",
      "Serilog.Sinks.Async",
      "Serilog.Sinks.File",
      "Serilog.Sinks.Debug"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "ApplicationName": "AppSim Crawler"
    },
    "WriteTo": [
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "http://localhost:5341",
          "apiKey": "none"
        }
      },
      {
        "Name": "Debug",
        "Args": {
          "outputTemplate": "{Timestamp:dd-MM-yyyy HH:mm:ss.fff} [{EventType:x8} {Level:u3}] <s:[{SourceContext}]> <method:[{FileName} > {MemberName}]>{NewLine}at {FilePath}:{LineNumber}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}"
        }
      },
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "Console",
              "Args": {
                "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
                "outputTemplate": "{Timestamp:dd-MM-yyyy HH:mm:ss.fff} [{EventType:x8} {Level:u3}] <c:[%COMPUTERNAME%]> <s:[{SourceContext}]> <method:[{FileName} > {MemberName}]>{NewLine}at {FilePath}:{LineNumber}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}"
              }
            }
          ]
        }
      },
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "File",
              "Args": {
                "path": "C:/appsim/logs/appSimCrawler.log",
                "outputTemplate": "{Timestamp:dd-MM-yyyy HH:mm:ss.fff} [{EventType:x8} {Level:u3}] <s:[{SourceContext}]>  <method:[{FileName} > {MemberName}]>{NewLine}at {FilePath}:{LineNumber}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}",
                "rollingInterval": "Day",
                "retainedFileCountLimit": 30,
                "shared": true,
                "rollOnFileSizeLimit": true
              }
            }
          ]
        }
      }
    ]
  }
}

For me, serilog did not write to log file because I was missing one of the many nuget packages (Serilog.Sinks.Async).对我来说,serilog 没有写入日志文件,因为我丢失了许多 nuget 包之一(Serilog.Sinks.Async)。 So besides making sure that your config in appsettings.json is correct - and that you are using the right file for dev vs prod, also:因此,除了确保您在 appsettings.json 中的配置是正确的 - 并且您正在为 dev vs prod 使用正确的文件之外,还要:

I recommend looking at the documentation, or tutorial, again and make sure you add every nuget package that it says in the instructions.我建议再次查看文档或教程,并确保添加说明中提到的每个 nuget 包。

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

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