首页 > 解决方案 > Serilog dotnet core function app 和 sql sink

问题描述

我需要将 dotnet5 与 Azure Functions 一起使用,因此请按照指南创建新解决方案:https ://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide 。

这很好用,所以接下来的工作是为控制台和 sql 服务器添加带有接收器的 serilog。

我添加了 nuget 包:

这是 Program.Main:

static void Main(string[] args)
{
    string EventName = "Main";
    var columnOptions = new ColumnOptions
    {
        AdditionalColumns = new Collection<SqlColumn>
        {
            new SqlColumn
                {ColumnName = "EventName", DataType = SqlDbType.NVarChar, DataLength = 32, NonClusteredIndex = true}
        }
    };

    Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft.Azure", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.MSSqlServer(
                    logEventFormatter: new RenderedCompactJsonFormatter(),
                    restrictedToMinimumLevel: LogEventLevel.Debug,
                    connectionString: "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SmsRouter",
                    sinkOptions: new MSSqlServerSinkOptions
                    {
                        TableName = "LogEvents",
                        AutoCreateSqlTable = true,
                    },
                    columnOptions: columnOptions)
                .CreateLogger();

    try
    {
        Log.Information("Starting up {EventName}", EventName);
        var host = new HostBuilder()
        .UseSerilog()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices(s =>
        {
            //services configured here
        })
        .Build();

        host.Run();
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Application start-up failed");
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

您可以看到Log.Information("Starting up {EventName}", EventName);行 这有效并记录到控制台和 Sql Server :)

应用程序启动后,它将等待 Http 请求 - 如下所示:

[Function("SendSimpleSms")]
public async Task<QueueAndHttpOutputType> RunSimple([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
    FunctionContext executionContext)
{
    string EventName = "SendSimpleSms";
    try
    {
        Log.Information("Starting: {EventName}", EventName);

我的问题是,这个日志请求“开始:SendSimpleSms”被记录到控制台窗口而不是 Sql Server。

有人看到我有什么问题吗?

标签: asp.net-coreserilog

解决方案


感谢 Panagiotis Kanavos 让我了解了 Serilog 自记录。

在 LoggerConfiguration 之后,我在 program.main 中添加了以下内容:

Serilog.Debugging.SelfLog.Enable(Console.Error);

这让我意识到 sql sink 无法记录,因为自定义属性的长度超过了其列的长度


推荐阅读