【问题标题】:Serilog does not write logs to SQL Server using Serilog.Sinks.MssqlServerSerilog 不使用 Serilog.Sinks.MssqlServer 将日志写入 SQL Server
【发布时间】:2022-01-27 12:41:55
【问题描述】:

我正在尝试使用 Serilog 设置日志记录机制。我想将日志写入文件和 SQL Server 数据库。

目前我可以将日志写入文件系统,但无法写入数据库。我也做了与 Serilog 文档中相同的简单设置

谢谢。

public class Program
{
        public static void Main(string[] args)
        {
            var logDB = @"Server=localhost;Initial Catalog=SHARED_NOTE;User ID=sa;Password=sql123;";
            var sinkOpts = new MSSqlServerSinkOptions();
            sinkOpts.TableName = "Logs";
            var columnOpts = new ColumnOptions();
            columnOpts.Store.Remove(StandardColumn.Properties);
            columnOpts.Store.Add(StandardColumn.LogEvent);
            columnOpts.LogEvent.DataLength = 2048;
            columnOpts.TimeStamp.NonClusteredIndex = true;

            Log.Logger = new LoggerConfiguration()
                .WriteTo.File(new CompactJsonFormatter(), "Log.json", rollingInterval: RollingInterval.Day)
                .WriteTo.Console(restrictedToMinimumLevel:Serilog.Events.LogEventLevel.Information)
                .WriteTo.MSSqlServer(
                        connectionString: logDB,
                        sinkOptions: sinkOpts,
                        columnOptions: columnOpts
                 )
                .CreateLogger();

            try
            {
                Log.Information("Application starting up.");

                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "The application failed to start up correctly.");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

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

我将AddLogging 添加到startup.cs

services.AddLogging();

所有包都是为 Web API 项目设置的:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="FluentValidation" Version="10.3.6" />
    <PackageReference Include="FluentValidation.AspNetCore" Version="10.3.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.12">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
    <PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
    <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
    <PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.6.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\Core\SharedNote.Application\SharedNote.Application.csproj" />
    <ProjectReference Include="..\..\Infrastructure\SharedNotes.Persistence\SharedNotes.Persistence.csproj" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="wwwroot\Images\" />
    <Folder Include="wwwroot\Docs\" />
  </ItemGroup>

</Project>

【问题讨论】:

  • 您的应用程序中是否有任何错误(启用跟踪日志记录)?您的数据库连接有任何错误吗?另外,请查看 sink 的自述文件 (github.com/serilog/serilog-sinks-mssqlserver),例如超时/批处理的说明。然后还要查看示例文件夹并使它们适用于您的场景。如果示例也不起作用,请在 repo 中创建一个问题并将其链接到此处:)
  • 应用程序没有给我任何错误。我的数据库连接是正确的。例如,我使用了其他可以使用 repo 的连接“数据源 = localhost;初始目录 = SHARED_NOTE;用户 ID = sa;密码 = sql123”。 logDB 字符串也是正确的。
  • 您可以查看Serilog.Sinks.MSSqlServer documentation for the master branch:如果您不使用自动建表功能,则需要在数据库中创建日志事件表。而且,如果您提前创建日志事件表,则接收器配置必须与该表完全匹配,否则可能会发生错误。因此,您可以尝试启用自动创建表功能并格式化日志格式。由于该问题与 Serilog.Sinks.MSSqlServer 有关,如果有任何其他问题,您可以将其发布在 Github 问题上。

标签: c# .net asp.net-core-webapi serilog asp.net-core-5.0


【解决方案1】:

评论没有足够的声誉,您是否尝试过关注这篇文章? Serilog log to SQL.

您尚未添加日志记录表,但我将假设您关注了 Sink 并且它与此相似或匹配?

TABLE [Log] (

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

   CONSTRAINT [PK_Log]
     PRIMARY KEY CLUSTERED ([Id] ASC)

)

另外,在同一篇文章中,您可以在 Logger 设置之后添加以下代码来调试 SQL 连接

Serilog.Debugging.SelfLog.Enable(msg =>
{
    Debug.Print(msg);
    Debugger.Break();
});

所以在你的代码中它会是

Log.Logger = new LoggerConfiguration()
    .WriteTo.File(new CompactJsonFormatter(),
    "Log.json",
    rollingInterval: RollingInterval.Day)
            .WriteTo.Console(restrictedToMinimumLevel:Serilog.Events.LogEventLevel.Information)
            .WriteTo.MSSqlServer(
                    connectionString: logDB,
                    sinkOptions: sinkOpts,
                    columnOptions: columnOpts
             )
            .CreateLogger();

Serilog.Debugging.SelfLog.Enable(msg =>
{
    Debug.Print(msg);
    Debugger.Break();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多