简体   繁体   中英

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. This is the only configuration I created in the Startup.cs file for the 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. The Logs entity looks like follows:

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. 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. 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. For the cheap hosting platform, I had to add a web.config file:

<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. 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.

Is your SqlServerConnectionString correct? Also make sure to call UseSerilog() when you are building the webhost in the Startup.cs. It might be added for dev environment only.

May be you forgot to calling SeriLog in the Program class on application startup. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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