当我 运行 .NET 5 中的应用程序时,Serilog 没有创建日志 SQL table

Serilog is not creating log SQL table when I run the application in .NET 5

我有 appsettings.json 设置,可以使用 "autoCreateSqlTable": true

自动创建日志 table

但是,我检查了 SQL,但找不到 table。我似乎找不到导致它无法创建和记录信息的原因。

Program.cs :

public class Program
{
    public static void Main(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>().UseSerilog();
            });
}

appsettings.json:

"Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "****",
          "tableName": "Log",
          "autoCreateSqlTable": true
        }
      }
    ]
  },

我的项目基于 .Net5.0 核心 MVC,项目安装了以下 nuget 包。

    <PackageReference Include="Serilog" Version="2.10.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
    <PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.6.0" />

下面的配置和 program.cs 文件适合我。

Make sure your Serilog in appsettings.json has this line "Using":["Serilog.Sinks.MSSqlServer"] as shown below:

"Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": "Information",
    "Override": {
      "Microsoft.EntityFrameworkCore.Database.Command": "Error",
      "Microsoft": "Error",
      "Microsoft.AspNetCore.Mvc": "Warnning"
    },
    "WriteTo": [         
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=dbserverhost.domain.com;Database=DBName; Trusted_Connection=True; MultipleActiveResultSets=true",
          "schemaName": "dbo",
          "tableName": "AppLogs",
          "autoCreateSqlTable": true
          //,
          //"columnOptionsSection": {
          //  "removeStandardColumns": [ "Properties" ]
          //  //,
          //  //"customColumns": [
          //  //  {
          //  //    "ColumnName": "EventType",
          //  //    "DataType": "int",
          //  //    "AllowNull": false
          //  //  },
          //  //  {
          //  //    "ColumnName": "Release",
          //  //    "DataType": "varchar",
          //  //    "DataLength": 32
          //  //  }
          //  //]
          //}
        }
        ,
        "restrictedToMinimumLevel":  "Warning"
      }
    ]
  }

My Program.cs file

using Serilog;
public class Program
    {
        public static void Main(string[] args)
        {


            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();


            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                //.WriteTo.File("Logs/log-.txt", rollingInterval: RollingInterval.Day)
                .CreateLogger();
            
            Log.Information("Hello {Name} from thread {ThreadId}", Environment.GetEnvironmentVariable("USERNAME"), Thread.CurrentThread.ManagedThreadId);

            

            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService<ILoggerFactory>();
            }

            host.Run();

            // CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

Serilog Default Create Table, For more details click here

CREATE TABLE [Logs] (

   [Id] int IDENTITY(1,1) NOT NULL,
   [Message] nvarchar(max) NULL,
   [MessageTemplate] nvarchar(max) NULL,
   [Level] nvarchar(128) NULL,
   [TimeStamp] datetime NOT NULL,
   [Exception] nvarchar(max) NULL,
   [Properties] nvarchar(max) NULL

   CONSTRAINT [PK_Logs] PRIMARY KEY CLUSTERED ([Id] ASC) 
);

在 SQL 服务器中创建 table 需要您的用户可能没有的某些权限,并且由于权限错误,接收器可能无法创建 table。

还有其他一些原因可能会阻止接收器甚至连接到数据库,例如连接字符串上的拼写错误或不正确的 user/password 等。

用于日志记录的 Serilog 接收器在默认情况下是安全的,不会抛出异常,因此如果您想解决正在发生的问题,您应该查看 Serilog's SelfLog

例如

Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));

这将在控制台中打印来自接收器的任何错误(如果您没有控制台应用程序,请更改为其他内容)

请确认您已创建 databaseschema。在我的例子中,当使用 Serilog.sinks.postgresql 时,不会自动创建数据库和模式。

使用脚本 https://gist.github.com/mivano/10429656 或设置 AutoCreateSqlTable=True

.WriteTo.MSSqlServer(
                connectionString: connectionString
                , sinkOptions: new Serilog.Sinks.MSSqlServer.MSSqlServerSinkOptions() { 
                    TableName = "Logs", 
                    SchemaName="dbo", 
                    AutoCreateSqlTable=true 
                }
        )