简体   繁体   中英

How to configure Serilog settings in Azure Function?

I'm in the process of creating my first production Azure Function and I'm trying to write log information to a local file and then eventually to Blob Storage. The local file is more for development troubleshooting and then ultimately I would like to have production information stored in Blob Storage. I'm not only new with Azure Functions but I'm also new with Serilog. I've used NLog in all my other applications but couldn't get it to work with Azure Functions.

Currently I'm trying to get the local log working. I actually seem to have it working but I'm not understanding how I can tweak a couple things.

The first thing I'm trying to change is the amount of information that is getting logged. It seems to be logging a whole bunch of system type of information like Request info to the blob storage. There is so much stuff getting logged that what entry I'm adding in code gets lost. It looks like all the system entries are marked as Information which is why it's probably showing up in my log. However, I would like to see if I could get it to only log data from when I specifically call the logger.Information(“some text”) in my code. Is there a way to suppress all of the Microsoft system information?

Second thing is how I can I make the Serilog configuration come from my local.settings.json file. Below is a sample of my file and I'm not sure if I would add the configuration information in the Values: property or if I would put it outside of that property into its own property? I'm assuming it would be in it's own property but so far all my custom settings have been coming from the Values: property?

Do I need to add the Serilog.Settings.Configuration NuGet package? If so, then I'm not understanding how I configure my Startup.cs file to get the information from the local settings file instead of configuring the settings directly in code. Eventually, I would like to add it to Dependency Injection so I can use the logger in other classes as well.

Startup.cs

public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddTransient<IDataManager, DataManager>();

            ConfigureServices(builder.Services).BuildServiceProvider(true);
        }

        private IServiceCollection ConfigureServices(IServiceCollection services)
        {
            services
                .AddLogging(loggingBuilder =>
                    loggingBuilder.AddSerilog(
                        new LoggerConfiguration()
                            .MinimumLevel.Information()
                            .WriteTo.Console()
                            .WriteTo.File(@"D:\logs\AzureFunction\log_.txt", rollingInterval: RollingInterval.Day)
                            .CreateLogger())
                );

            return services;
        }

Local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "ProcessLookBackDays": "90",
    "SqlConnection": "connection info",
    "StorageConnection": "connection info"
    "AzureWebJobsStorage": "connection info"
    "InputContainer": "test-files",
    "InputFolder": "input",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information"
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "D:\\logs\\AzureFunction\\log_.log",
          "rollingInterval": "Day",
          "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3}] {Username} {Message:lj}{NewLine}{Exception}"
        }
      }
    ]
  }
}
  • Setting up configuration in local-setting. Json local-setting. Json will not reflect in the azure function app. local-setting as the name suggest is for local use only while with azure you need to use the app setting and read them.

在此处输入图像描述

  • Just add a new setting in the app setting and you can then use the below code to read the settings.
var appsettings = Environment.GetEnvironmentVariable("Name of the setting");
  • When you want to use the external configuration with serilog then you can use the Serilog.Settings.Configuration .

  • Now you can configure the minimum level of a log event so all the log event with less importance than the specified minimum level will not be logged.

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
    .CreateLogger();
  • Here we specify two things the .MinimumLevel.Debug() and restrictedToMinimumLevel this attribute dictates the minimum level for the that particular sink. A sink is just a place where you can log, they are configured using the Writeto tag. for eg, in the above code the sink is a console. There are other sink too.

The minimum levels are verbose Debug, information, warning, error, fatal.

Reference:-

Read configuration from app setting by Ashish Patel

Use serilog to filter the logs

Serilog setting configuration

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