【问题标题】:.Net Core Logging to PostgreSQL with Serilog Not Working.Net Core 使用 Serilog 将日志记录到 PostgreSQL 不工作
【发布时间】:2021-07-21 04:33:20
【问题描述】:

我正在使用 Serilog 记录 Postgresql 数据库 这是我的 Serilog 配置

  1. 这是我的 appsettings.json -> { 也尝试了不同的配置 }
"Serilog": {
    "Using": [ "Serilog.Sinks.PostgreSQL.Configuration" ],
    "MinimumLevel": "Debug",
    "Enrich": [ "WithMachineName" ],
    "WriteTo": [
      {
        "Name": "PostgreSQL",
        "Args": {
          "connectionString": "my-connection-string",
          "tableName": "log",
          "needAutoCreateTable": true
        }
      }
    ]
  },

  "Columns": {
    "message": "RenderedMessageColumnWriter",
    "message_template": "MessageTemplateColumnWriter",
    "level": {
      "Name": "LevelColumnWriter",
      "Args": {
        "renderAsText": true,
        "dbType": "Varchar"
      }
    },
    "raise_date": "TimestampColumnWriter",
    "exception": "ExceptionColumnWriter",
    "properties": "LogEventSerializedColumnWriter",
    "props_test": {
      "Name": "PropertiesColumnWriter",
      "Args": { "dbType": "Json" }
    },
    "machine_name": {
      "Name": "SinglePropertyColumnWriter",
      "Args": {
        "propertyName": "MachineName",
        "writeMethod": "Raw"
      }
    }
  },
  1. 这是 Program.cs
public class Program
    {
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();

            //Initialize Logger
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                .CreateLogger();
            try
            {
                Log.Information("Application Starting.");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "The Application failed to start.");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
  1. 这里是控制器
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace MyApp
{
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly IAuthenticationService _authenticationService;
        private readonly ILogger<AuthenticationController> _logger;
        public AuthenticationController(
            IAuthenticationService authenticationService,
            ILogger<AuthenticationController> logger)
        {
            this._authenticationService = authenticationService;
            this._logger = logger;
        }

        [Route("test-log")]
        [HttpGet]
        public IActionResult LOG()
        {
            _logger.LogInformation("Hello World");
            return Ok();
        }
    }
}

启动后表已创建,但没有记录。 还测试了 Serilog 日志记录是否比 Microsoft 但遇到了同样的问题。

【问题讨论】:

    标签: c# .net postgresql .net-core serilog


    【解决方案1】:

    不幸的是,Serilog.Sinks.PostgreSQL 包尚未更新以支持 Npgsql 5.0。事实上,他们仍在尝试以 .NET Framework 为目标,但 Npgsql 5.0 仅支持 .NET Core。

    这里有一个问题在 Github 上打开:https://github.com/b00ted/serilog-sinks-postgresql/issues/34

    顺便说一句,您可以通过将其添加到启动配置中来调试 Serilog 问题:

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

    【讨论】:

      【解决方案2】:

      我遇到了类似的情况,虽然我是通过 Program.cs 中的.WriteTo.PostgreSQL() 在 Program.cs 中配置它。

      就我而言,解决方案是将参数 'useCopy' 设置为 false

      例子:

      ...
      .WriteTo.PostgreSQL(
        connectionString: configuration.GetConnectionString("LoggerConnection").ToString(),
        tableName: "yourtable",
        columnOptions: columnWriters,
        restrictedToMinimumLevel: LogEventLevel.Information,
        needAutoCreateTable: true,
        respectCase: true,
        useCopy: false // <-----------------
      )
      ...
      

      也许你可以尝试在你的 appsettings.json 配置中做同样的事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        • 1970-01-01
        • 1970-01-01
        • 2020-03-13
        • 1970-01-01
        相关资源
        最近更新 更多