简体   繁体   English

在为.net core 2.1.5 Web应用程序生产时,Serilog不会在MSSqlServer数据库中创建日志

[英]Serilog doesn't create logs in MSSqlServer database when in production for .net core 2.1.5 web app

I created a web application in asp.net MVC with .net core 2.1.5. 我使用.net core 2.1.5在asp.net MVC中创建了一个Web应用程序。 This is the only configuration I created in the Startup.cs file for the Serilog: 这是我在Startup.cs文件中为Serilog创建的唯一配置:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{          
    ...

    loggerFactory.AddSerilog();
    Log.Logger = new LoggerConfiguration()
       .MinimumLevel.Verbose()
       .WriteTo.MSSqlServer(
            connectionString: Configuration.GetSection("SqlServerConnectionString").Get<string>(),
            tableName: "Logs",
            restrictedToMinimumLevel: LogEventLevel.Verbose,
            columnOptions: new ColumnOptions()
        )
       .CreateLogger();

    using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
        var context = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
        context.Database.Migrate();
        context.Database.EnsureCreated();
    }          
}

I've created manually the Logs table and I've created a separate migration for it. 我手动创建了Logs表,并为此创建了一个单独的迁移。 The Logs entity looks like follows: Logs实体如下所示:

public class Logs
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Message { get; set; }

    public string MessageTemplate { get; set; }

    [MaxLength(128)]
    public string Level { get; set; }

    [Required]
    public DateTime TimeStamp { get; set; }

    public string Exception { get; set; }

    public string Properties { get; set; }
}   

The sample of using the logger: 使用记录器的示例:

public class HomeController : Controller
{
    readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public async Task<IActionResult> Index()
    {
        var obj = new { blah = "test12345", blah2 = "fsdf" };
        _logger.LogInformation("sadfsadfsadf",obj);

        return View();
    }
}

The logger works when I run the app in the localhost- I can see the logs in the Logs table. 当我在localhost中运行应用程序时,记录器可以工作,我可以在“日志”表中看到日志。 However after I deployed the app to production(Azure and some other hosting platform which works based on IIS), I can see the Logs table has been created but it's always empty. 但是,在将应用程序部署到生产环境(Azure和其他基于IIS的托管平台)后,我可以看到Logs表已创建,但始终为空。 Even if I hit the Home/Index action no exception appears, just nothing happens. 即使我执行了“主页/索引”操作,也不会出现异常,什么也不会发生。 Any ideas what am I doing wrong and why the app doesn't create logs in the database? 有什么想法我做错了什么,为什么该应用程序没有在数据库中创建日志?

Ok, so I finally found a workaround. 好的,所以我终于找到了解决方法。 The solution for Azure was to add an Environment Variable with value Development in the Application Settings section in Azure. Azure的解决方案是在Azure的“ Application Settings部分中添加一个具有“ Development价值”的Environment Variable For the cheap hosting platform, I had to add a web.config file: 对于廉价的托管平台,我必须添加一个web.config文件:

<aspNetCore processPath="dotnet"
      arguments=".\MyApp.dll"
      stdoutLogEnabled="false"
      stdoutLogFile="\\?\%home%\LogFiles\stdout"
      hostingModel="InProcess">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
    <environmentVariable name="CONFIG_DIR" value="f:\application_config" />
  </environmentVariables>
</aspNetCore>

to the root directory of the .Web project because it works based on IIS. 到.Web项目的根目录,因为它基于IIS。 I fixed the problem based on this article Don't really like this solution with adding web.config file, because it's not that trivial to manage in the CD pipeline such as JSON file with all the app settings. 我已根据本文解决了该问题。添加web.config文件不是非常喜欢此解决方案,因为在CD管道(如具有所有应用程序设置的JSON文件)中管理它并不是那么简单。

Is your SqlServerConnectionString correct? 您的SqlServerConnectionString是否正确? Also make sure to call UseSerilog() when you are building the webhost in the Startup.cs. 在Startup.cs中构建Web主机时,还请确保调用UseSerilog()。 It might be added for dev environment only. 它可能仅在开发环境中添加。

May be you forgot to calling SeriLog in the Program class on application startup. 可能是您忘记了在应用程序启动时在Program类中调用SeriLog的原因。 So try with following: 因此,请尝试以下操作:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging => { logging.ClearProviders(); }) // clearing all other logging providers
                .UseSerilog(); // Using serilog

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

相关问题 Serilog MSSQL Sink 不会将日志写入数据库 - Serilog MSSQL Sink doesn't write logs to database OpenTracing不会使用Serilog发送日志 - OpenTracing doesn't send logs with Serilog 使用 NLog 或 Serilog 时 .NET Core 3.0 应用程序中的内存泄漏 - Memory leak in .NET Core 3.0 app when using NLog or Serilog 如何在.net core 中使用 Serilog 在日志中显示 ClientIp? - How to display ClientIp in logs using Serilog in .net core? Asp.Net Core 2.0.1的Serilog设置不生成日志 - Serilog setup for Asp.Net Core 2.0.1 not producing logs ASP NET核心Serilog:请求,响应和异常日志的不同文件 - ASP NET core Serilog : Different files for Request, Response and Exception logs Serilog ASP.Net Core 不在 MacOS 中将日志写入文件,但在 Windows 中工作 - Serilog ASP .Net Core not writing logs to file in MacOS but works in Windows Serilog 不使用 Serilog.Sinks.MssqlServer 将日志写入 SQL 服务器 - Serilog does not write logs to SQL Server using Serilog.Sinks.MssqlServer 如何在应用程序创建数据库之前保存 Serilog 事件日志? - How to save Serilog event logs before a database is created by the app? 我的网络应用程序在发布时找不到我的数据库 - My web app doesn't find my database when published
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM