---
title: How To Start Logging With Serilog - Nodinite Sinks Configuration
description: Step-by-step guide to configure Nodinite Serilog sinks for Azure Functions using Blob Storage, Event Hub, File, Log API, and Service Bus with Managed Identity and connection string options.
---

:ReleaseNotes(https://portal.nodinite.com/marketplace/15):

# How To Start Logging With Serilog

:new2.0.14:

>[!INFO]
>This document applies to :Nodinite: Serilog sinks versions >= 2.0.14 and assumes you use the [isolated worker model](https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-in-process-differences)<sup>:fa-arrow-up-right-from-square:</sup> with Azure Functions using .NET 8 or later.

If you want to log using the [Microsoft.Extensions.Logging.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger)<sup>:fa-arrow-up-right-from-square:</sup>, see ['How To Start Logging With Microsoft.Extensions.Logging.ILogger in Azure Functions'][Serilog - ILogger].

You can use different settings examples (appsettings.json); the rest of the code examples below are the same regardless of which method you choose.

* [Required NuGet packages](#required-nuget-packages)
* [Dependencies in Project (.csproj)](#dependencies-in-project.csproj)
* [Startup file (Program.cs)](#startup-file-program.cs)
* [Log (Function.cs)](#log-function.cs)
* [appsettings.json](#appsettings.json)  
  * [Settings section][Serilog - Shared Section]

>[!INFO]
>The **Settings** section is documented on a shared page. Read more at [Settings Section (appsettings.json)][Serilog - Shared Section]

## Required NuGet packages

To enable Serilog Logging, add the required NuGet packages to your project. You can do this using the NuGet Package Manager in Visual Studio or by editing the .csproj file directly:

* [Nodinite.Serilog.AzureBlobStorageSink](https://www.nuget.org/packages/Nodinite.Serilog.AzureBlobStorageSink/)<sup>:fa-arrow-up-right-from-square:</sup> (if you use the Blob sink, choose any other :Nodinite: sink you like)
* Serilog.Settings.Configuration  

## Dependencies in Project (.csproj)

Update the **version** when you update the NuGet packages. The versions below are examples. Always update to the latest version.

``` xml
    <ItemGroup>
      ...
      <PackageReference Include="Nodinite.Serilog.AzureBlobStorageSink" Version="2.0.27" />
      <PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
  </ItemGroup>
```

## Startup file (Program.cs)

```csharp
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices((context, services) =>
    {
        // Create configuration object and read settings
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        // Create the logger object 
        var logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        // Register the logger object as a singleton using dependency injection to achieve great performance when you write multiple logs
        services.AddSingleton<Serilog.ILogger, Serilog.Core.Logger>(sp => logger);
    })
    .Build();

host.Run();
```

## Log (Function.cs)

Inject the Logger inside the constructor instead of the method level.

>[!IMPORTANT]
>**Always set OriginalMessageType for searchable business data** - The `OriginalMessageType` property determines which [Search Field Expressions][] will extract business data (Order Numbers, Customer IDs, Invoice amounts, Transaction codes) from your logged messages. Without the correct [Message Types][], features like [Non-Events Monitoring][], [Business Process Modeling (BPM)][BPM], and business-data searches in [Log Views][] won't work. Plan your Message Types before writing production code - they cannot be changed after logging.

```csharp
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Serilog.Core.Enrichers;

namespace Nodinite.Demo.Azure.Functions
{
    public class Function1
    {
        private readonly Serilog.ILogger _logger;

        public Function1(Serilog.ILogger logger)
        {
            _logger = logger;
        }

        [Function("Function1")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
        {

            #region Nodinite Serilog sample code (should be refactored into a reusable component injected using dependency injection; all part of your documented asynchronous Logging Strategy)
            
            string payload = await new StreamReader(req.Body).ReadToEndAsync();
            string correlationId = Guid.NewGuid().ToString();
            
            if (req.Headers.TryGetValue("x-ms-client-tracking-id", out Microsoft.Extensions.Primitives.StringValues id))
            {
                correlationId = id[0];
            }
        
            _logger.ForContext(new PropertyEnricher("ApplicationInterchangeId", $"{correlationId}"))
              .Enrich.WithProperty("Color", "Yellow")
              .ForContext(new PropertyEnricher("Body", JsonConvert.SerializeObject(payload)))
              .ForContext(new PropertyEnricher("OriginalMessageType", "OrderMessage#1.0"))
              .Information("Hello from Function");
            
            #endregion

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
            response.WriteString("Welcome to Azure Functions!");

            return response;
        }
    }
}
```

## appsettings.json

Depending on the type of sink you use, apply the appropriate configuration using any of the following
  
* [How To Start Logging With Serilog](#how-to-start-logging-with-serilog)
  * [Required NuGet packages](#required-nuget-packages)
  * [Dependencies in Project (.csproj)](#dependencies-in-project.csproj)
  * [Startup file (Program.cs)](#startup-file-program.cs)
  * [Log (Function.cs)](#log-function.cs)
  * [appsettings.json](#appsettings.json)
    * [Blob](#blob)
      * [Blob (Using the default Managed Identity)](#blob-using-the-default-managed-identity)
      * [Blob (Using an explicit Managed Identity)](#blob-using-an-explicit-managed-identity)
      * [Blob (Using a Connection string)](#blob-using-a-connection-string)
    * [Event Hub](#event-hub)
      * [Event Hub (Using Managed Identity)](#event-hub-using-managed-identity)
      * [Event Hub (Using a Connection string)](#event-hub-using-a-connection-string)
    * [File](#file)
    * [Log API](#log-api)
    * [Service Bus](#service-bus)
      * [Service Bus (Using the default Managed Identity)](#service-bus-using-the-default-managed-identity)
      * [Service Bus (Using an explicit Managed Identity)](#service-bus-using-an-explicit-managed-identity)
      * [Service Bus(Using a Connection string)](#service-bus-using-a-connection-string)
    * [Advanced settings using multiple sinks](#advanced-settings-using-multiple-sinks)
  * [:fa-hand-point-right: Next Steps](#fa-hand-point-right-next-steps)
  * [:fa-link-horizontal: Related Topics](#fa-link-horizontal-related-topics)

### Blob

>[!TIP]
>Authentication and connection options for for **Azure Blob Storage** (recommended option!).

#### Blob (Using the default Managed Identity)

``` json
{
  "Serilog": {
    "Using": ["Nodinite.Serilog.AzureBlobStorageSink"],
    "WriteTo": [
      {
        "Name": "AzureBlobStorageSink",
        "Args": {
          "StorageAccountName": "Contoso",
          "ContainerName": "logevents",
          "Settings": {
            ...
          }
        }
      }
    ]
  }
}
```  

#### Blob (Using an explicit Managed Identity)

:new2.0.16:

``` json
{
  "Serilog": {
    "Using": ["Nodinite.Serilog.AzureBlobStorageSink"],
    "WriteTo": [
      {
        "Name": "AzureBlobStorageSink",
        "Args": {
          "StorageAccountName": "Contoso",
          "ContainerName": "logevents",
          "ManagedIdentityClientId": "00000000-0000-0000-0000-000000000000",
          "Settings": {
            ...
          }
        }
      }
    ]
  }
}
```  

#### Blob (Using a Connection string)

Copy the ConnectionString from the Azure Portal (Access keys) for the Storage Account in use.

```json
{
  "Serilog": {
    "Using": [ "Nodinite.Serilog.AzureBlobStorageSink" ],
    "WriteTo": [
      {
        "Name": "NodiniteAzureBlobStorageSinkWithConnectionString",
        "Args": {
          "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=Contoso;AccountKey=xyz;EndpointSuffix=core.windows.net",
          "ContainerName": "logevents",
          "Settings": {
            ...
                     }
        }
      }
    ]
  }
}
```

### Event Hub

>[!TIP]
>Authentication and connection options for for **Azure Event Hub**.

#### Event Hub (Using Managed Identity)

``` json
{
  "Serilog": {
    "Using": ["Nodinite.Serilog.EventHubSink"],
    "WriteTo": [
      {
        "Name": "NodiniteEventHubSink",
        "Args": {
          "eventHubNameSpace": "Contoso.servicebus.windows.net",
          "eventHubName": "eventhub-01",
          "Settings": {
           ...
          }
        }
      }
    ]
  }
}
```  

#### Event Hub (Using a Connection string)

Use a dedicated **Shared access policy** to create a connectionstring including the `EntityPath=%name%`.

```json
{
  "Serilog": {
    "Using": [ "Nodinite.Serilog.EventHubSink" ],
    "WriteTo": [
      {
        "Name": "NodiniteEventHubSink",
        "Args": {
          "ConnectionString": "Endpoint=sb://xyz.servicebus.windows.net/;SharedAccessKeyName=Default;SharedAccessKey=secretstuff;EntityPath=yourentityname
",
          "Settings": {
            ...
            }
        }
      }
    ]
  }
}
```

### File

>[!TIP]
>Connection options for for **SMB Shares and Folders**.

```json
{
  "Serilog": {
    "Using": [ "Nodinite.Serilog.FileSink" ],
    "WriteTo": [
      {
        "Name": "NodiniteFileSink",
        "Args": {
          "Folder": "\\FancyUNCSrv01\\DaShare\\In",
          "Settings": {
            ...
            "FileExtension": ".json"
          }
        }
      }
    ]
  }
}
```  

### Log API

>[!WARNING]
>**BREAKING CHANGE in version 7.10.9** - Set `NodiniteApiUrl` to the complete [Log Event][] address of your [Log API][], ending in `/api/LogEvent`, in the Nodinite v7 format `https://{host}:{port}/LogAPI/api/LogEvent`. Read more in [Log Event address (NodiniteApiUrl)][Serilog - LogAPI - Address].

```json
{
  "Serilog": {
    "Using": [ "Nodinite.Serilog.ApiSink" ],
    "WriteTo": [
      {
        "Name": "NodiniteApiSink",
        "Args": {
          "NodiniteApiUrl": "https://fancysrv01:50002/LogAPI/api/LogEvent",
          "Settings": {
            ...
          }
        }
      }
    ]
  }
}
```

### Service Bus

>[!TIP]
>Authentication and connection options for [Azure Service Bus][Serilog - Service Bus].

#### Service Bus (Using the default Managed Identity)

``` json
{
  "Serilog": {
    "Using": ["Nodinite.Serilog.ServiceBusSink"],
    "WriteTo": [
      {
        "Name": "NodiniteServiceBusSink",
        "Args": {
          "NamespaceName": "Contoso.servicebus.windows.net",
          "QueueName": "sbq01",
          "Settings": {
            ...
          }
        }
      }
    ]
  }
}
```  

#### Service Bus (Using an explicit Managed Identity)

:new2.0.27:

``` json
{
  "Serilog": {
    "Using": ["Nodinite.Serilog.ServiceBusSink"],
    "WriteTo": [
      {
        "Name": "NodiniteServiceBusSink",
        "Args": {
          "NamespaceName": "Contoso.servicebus.windows.net",
          "QueueName": "sbq01",
          "ManagedIdentityClientId": "00000000-0000-0000-0000-000000000000",
          "Settings": {
            ...
          }
        }
      }
    ]
  }
}
```  

#### Service Bus (Using a Connection string)

Copy the ConnectionString from the Azure Portal (Access keys) for the Storage Account in use.

```json
{
  "Serilog": {
    "Using": [ "Nodinite.Serilog.ServiceBusSink" ],
    "WriteTo": [
      {
        "Name": "NodiniteServiceBusSinkWithConnectionString",
        "Args": {
          "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=Contoso;AccountKey=xyz;EndpointSuffix=core.windows.net",
          "QueueName": "sqb01",
          "Settings": {
            ...
          }
        }
      }
    ]
  }
}
```

### Advanced settings using multiple sinks

In this example multiple sinks are used. The example uses the **Azure Blob Storage Sink** and the **Service Bus Sink**. The settings for each sink are specified in the [Settings section][Serilog - Shared Section] of the configuration file.  

```json
{
  "Serilog": {
    "Using": [ "Nodinite.Serilog.AzureBlobStorageSink", "Nodinite.Serilog.ServiceBusSink" ],
    "WriteTo": [
      {
        "Name": "AzureBlobStorageSink",
        "Args": {
          "StorageAccountName": "Contoso",
          "ContainerName": "logevents",
          "Settings": {
            ...
          }
        }
      },
      {
        "Name": "NodiniteServiceBusSink",
        "Args": {
          "NamespaceName": "Contoso.servicebus.windows.net",
          "QueueName": "sbq01",
          "Settings": {
            ...
          }
        }
      },
      {
        "Name": "Console",
        "Args": {
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      }
    ]
  }
}
```

___

## :fa-hand-point-right: Next Steps

:fa-file: [Configure Message Types][Message Types] - Critical for making your [Serilog][] data searchable and enabling business intelligence features  

❔['How To Start Logging With Microsoft.Extensions.Logging.ILogger in Azure Functions'][Serilog - ILogger]  

:fa-truck-pickup: [Pickup Log Events Service Logging Agent][Pickup Service]  
:fa-bolt: [Log Events][Log Event]  
:fa-file-code: [JSON Log Event][]  

## :fa-link-horizontal: Related Topics

:fa-hard-drive: [Logging][]  
:fa-file: [Message Types][] - Critical for [Search Field][Search Fields] extraction from Serilog events  
:fa-magnifying-glass-plus: [Search Fields][] - Extract business data from logged messages  
:fa-magnifying-glass-plus: [Search Field Expressions][] - Define extraction patterns for Order Numbers, Customer IDs, Invoice amounts  
:fa-table-list: [Log Views][] - Search logged data by business identifiers  
:fa-stopwatch: [Non-Events Monitoring][] - Track message volumes and detect missing messages  
:fa-project-diagram: [Business Process Modeling (BPM)][BPM] - End-to-end transaction tracking across Azure Functions and other systems  
:fa-coins: [Reduce Azure Functions Logging Costs][] - Lower the Azure cost of logging Azure Functions  
:fa-coins: [Azure Costs for Blob Storage and Event Hub][] - What staging log events in Azure costs  
:fa-clock: [Reduce Azure Logic Apps Run History Retention to Lower TCO][] - The same approach for Logic Apps  
:fa-cloud-arrow-down: [Reduce Azure API Management Logging Costs][] - The same approach for API Management  

[Azure Costs for Blob Storage and Event Hub]:{ndr}/Logging%20and%20Monitoring/Custom%20Logging/Troubleshooting/Azure%20Costs%20for%20Blob%20Storage%20and%20Event%20Hub.md
[BPM]:{ndr}/Repository%20Model/BPMs/Overview.md
[JSON Log Event]:{ndr}/Core%20Services/Log%20Event/Features/JSON%20Log%20Event.md
[Log API]:{ndr}/Core%20Services/Log%20API/Overview.md
[Log Event]:{ndr}/Core%20Services/Log%20Event/Overview.md
[Log Views]:{ndr}/Administration/1.%20Log%20Management/1.%20Log%20Views/Features/What%20is%20a%20Log%20View.md
[Logging]:nodiniteDoc:/Logging
[Message Types]:{ndr}/Repository%20Model/Message%20Types/Overview.md
[Non-Events Monitoring]:{ndr}/Logging%20and%20Monitoring/Non-Events/Overview.md
[Pickup Service]:{ndr}/Logging%20and%20Monitoring/Pickup%20LogEvents%20Service/Overview.md
[Reduce Azure API Management Logging Costs]:{ndr}/Logging%20and%20Monitoring/Azure%20API%20Management/Troubleshooting/Reduce%20Azure%20API%20Management%20Logging%20Costs.md
[Reduce Azure Functions Logging Costs]:{ndr}/Logging%20and%20Monitoring/Serilog/Troubleshooting/Reduce%20Azure%20Functions%20Logging%20Costs.md
[Reduce Azure Logic Apps Run History Retention to Lower TCO]:{ndr}/Logging%20and%20Monitoring/Azure%20Logic%20Apps/Troubleshooting/Reduce%20Azure%20Logic%20Apps%20Run%20History%20Retention%20to%20Lower%20TCO.md
[Search Field Expressions]:{ndr}/Administration/1.%20Log%20Management/2.%20Search%20Fields/Features/Search%20Field%20Expressions/Overview.md
[Search Fields]:{ndr}/Administration/1.%20Log%20Management/2.%20Search%20Fields/Features/What%20is%20a%20Search%20Field.md
[Serilog]:{ndr}/Logging%20and%20Monitoring/Serilog/Overview.md
[Serilog - ILogger]:{ndr}/Logging%20and%20Monitoring/Serilog/How%20To%20Start%20Logging%20Extending%20ILogger.md
[Serilog - LogAPI - Address]:{ndr}/Logging%20and%20Monitoring/Serilog/Features/Log%20API.md#log-event-address-nodiniteapiurl
[Serilog - Service Bus]:{ndr}/Logging%20and%20Monitoring/Serilog/Features/ServiceBus.md
[Serilog - Shared Section]:{ndr}/Logging%20and%20Monitoring/Serilog/Settings%20Section.md