---
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.
---

<a class="nodinite-release-notes" href="https://portal.nodinite.com/marketplace/15" data-url="https://portal.nodinite.com/marketplace/15"><i class="fal fa-fw fa-file-alt" aria-hidden="true"></i> Release Notes</a>

# How To Start Logging With Serilog

<sup><span class="nodinite-new-badge">New 2.0.14</span></sup>

<aside aria-label="Info" class="nodinite-note nodinite-note--info">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-square-info"></i> Info</p>
<div class="nodinite-note__content"><p>This document applies to <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Serilog sinks versions &gt;= 2.0.14 and assumes you use the <a href="https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-in-process-differences">isolated worker model</a><sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup> with Azure Functions using .NET 8 or later.</p></div>
</aside>

If you want to log using the [Microsoft.Extensions.Logging.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger)<sup><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></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]

<aside aria-label="Info" class="nodinite-note nodinite-note--info">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-square-info"></i> Info</p>
<div class="nodinite-note__content"><p>The <strong>Settings</strong> section is documented on a shared page. Read more at <a href="https://docs.nodinite.com/logging-and-monitoring/serilog/settings-section/">Settings Section (appsettings.json)</a></p></div>
</aside>

## 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><i class="fal fa-arrow-up-right-from-square" aria-hidden="true"></i></sup> (if you use the Blob sink, choose any other <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> 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.

<aside aria-label="Important" class="nodinite-note nodinite-note--important">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-message-exclamation"></i> Important</p>
<div class="nodinite-note__content"><p><strong>Always set OriginalMessageType for searchable business data</strong> - The <code>OriginalMessageType</code> property determines which <a href="https://docs.nodinite.com/administration/log-management/search-fields/features/search-field-expressions/overview/">Search Field Expressions</a> will extract business data (Order Numbers, Customer IDs, Invoice amounts, Transaction codes) from your logged messages. Without the correct <a href="https://docs.nodinite.com/repository-model/message-types/overview/">Message Types</a>, features like <a href="https://docs.nodinite.com/logging-and-monitoring/non-events/overview/">Non-Events Monitoring</a>, <a href="https://docs.nodinite.com/repository-model/bpms/overview/">Business Process Modeling (BPM)</a>, and business-data searches in <a href="https://docs.nodinite.com/administration/log-management/log-views/features/what-is-a-log-view/">Log Views</a> won't work. Plan your Message Types before writing production code - they cannot be changed after logging.</p></div>
</aside>

```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)
  * [<i class="fal fa-hand-point-right" aria-hidden="true"></i> Next Steps](#fa-hand-point-right-next-steps)
  * [<i class="fal fa-link-horizontal" aria-hidden="true"></i> Related Topics](#fa-link-horizontal-related-topics)

### Blob

<aside aria-label="Tip" class="nodinite-note nodinite-note--tip">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-lightbulb"></i> Tip</p>
<div class="nodinite-note__content"><p>Authentication and connection options for for <strong>Azure Blob Storage</strong> (recommended option!).</p></div>
</aside>

#### 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)

<sup><span class="nodinite-new-badge">New 2.0.16</span></sup>

``` 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

<aside aria-label="Tip" class="nodinite-note nodinite-note--tip">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-lightbulb"></i> Tip</p>
<div class="nodinite-note__content"><p>Authentication and connection options for for <strong>Azure Event Hub</strong>.</p></div>
</aside>

#### 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

<aside aria-label="Tip" class="nodinite-note nodinite-note--tip">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-lightbulb"></i> Tip</p>
<div class="nodinite-note__content"><p>Connection options for for <strong>SMB Shares and Folders</strong>.</p></div>
</aside>

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

### Log API

<aside aria-label="Warning" class="nodinite-note nodinite-note--warning">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-triangle-exclamation"></i> Warning</p>
<div class="nodinite-note__content"><p><strong>BREAKING CHANGE in version 7.10.9</strong> - Set <code>NodiniteApiUrl</code> to the complete <a href="https://docs.nodinite.com/core-services/log-event/overview/">Log Event</a> address of your <a href="https://docs.nodinite.com/core-services/log-api/overview/">Log API</a>, ending in <code>/api/LogEvent</code>, in the Nodinite v7 format <code>https://{host}:{port}/LogAPI/api/LogEvent</code>. Read more in <a href="https://docs.nodinite.com/logging-and-monitoring/serilog/features/log-api/#log-event-address-nodiniteapiurl">Log Event address (NodiniteApiUrl)</a>.</p></div>
</aside>

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

### Service Bus

<aside aria-label="Tip" class="nodinite-note nodinite-note--tip">
<p class="nodinite-note__label" aria-hidden="true"><i class="far fa-fw fa-lightbulb"></i> Tip</p>
<div class="nodinite-note__content"><p>Authentication and connection options for <a href="https://docs.nodinite.com/logging-and-monitoring/serilog/features/servicebus/">Azure Service Bus</a>.</p></div>
</aside>

#### 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)

<sup><span class="nodinite-new-badge">New 2.0.27</span></sup>

``` 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}"
        }
      }
    ]
  }
}
```

___

## <i class="fal fa-hand-point-right" aria-hidden="true"></i> Next Steps

<i class="fal fa-file" aria-hidden="true"></i> [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]  

<i class="fal fa-truck-pickup" aria-hidden="true"></i> [Pickup Log Events Service Logging Agent][Pickup Service]  
<i class="fal fa-bolt" aria-hidden="true"></i> [Log Events][Log Event]  
<i class="fal fa-file-code" aria-hidden="true"></i> [JSON Log Event][]  

## <i class="fal fa-link-horizontal" aria-hidden="true"></i> Related Topics

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

[Azure Costs for Blob Storage and Event Hub]:https://docs.nodinite.com/logging-and-monitoring/custom-logging/troubleshooting/azure-costs-for-blob-storage-and-event-hub/
[BPM]:https://docs.nodinite.com/repository-model/bpms/overview/
[JSON Log Event]:https://docs.nodinite.com/core-services/log-event/features/json-log-event/
[Log API]:https://docs.nodinite.com/core-services/log-api/overview/
[Log Event]:https://docs.nodinite.com/core-services/log-event/overview/
[Log Views]:https://docs.nodinite.com/administration/log-management/log-views/features/what-is-a-log-view/
[Logging]:https://docs.nodinite.com/logging/
[Message Types]:https://docs.nodinite.com/repository-model/message-types/overview/
[Non-Events Monitoring]:https://docs.nodinite.com/logging-and-monitoring/non-events/overview/
[Pickup Service]:https://docs.nodinite.com/logging-and-monitoring/pickup-logevents-service/overview/
[Reduce Azure API Management Logging Costs]:https://docs.nodinite.com/logging-and-monitoring/azure-api-management/troubleshooting/reduce-azure-api-management-logging-costs/
[Reduce Azure Functions Logging Costs]:https://docs.nodinite.com/logging-and-monitoring/serilog/troubleshooting/reduce-azure-functions-logging-costs/
[Reduce Azure Logic Apps Run History Retention to Lower TCO]:https://docs.nodinite.com/logging-and-monitoring/azure-logic-apps/troubleshooting/reduce-azure-logic-apps-run-history-retention-to-lower-tco/
[Search Field Expressions]:https://docs.nodinite.com/administration/log-management/search-fields/features/search-field-expressions/overview/
[Search Fields]:https://docs.nodinite.com/administration/log-management/search-fields/features/what-is-a-search-field/
[Serilog]:https://docs.nodinite.com/logging-and-monitoring/serilog/overview/
[Serilog - ILogger]:https://docs.nodinite.com/logging-and-monitoring/serilog/how-to-start-logging-extending-ilogger/
[Serilog - LogAPI - Address]:https://docs.nodinite.com/logging-and-monitoring/serilog/features/log-api/#log-event-address-nodiniteapiurl
[Serilog - Service Bus]:https://docs.nodinite.com/logging-and-monitoring/serilog/features/servicebus/
[Serilog - Shared Section]:https://docs.nodinite.com/logging-and-monitoring/serilog/settings-section/