Similar to the previous post https://jaryl-lan.blogspot.com/2022/03/write-to-elasticsearch-with-serilog-in.html. Will be using Serilog library to write to Azure Blob Storage. Before we can start, you are required to have a Azure Storage Account up and running. Do not worry if you do not have an Azure account as you can actually run the emulator on your local machine. If you have Visual Studio 2022 installed on your machine, then Azurite (To replace Azure Storage Emulator) is included. Otherwise you will have to manually install it.
For those who has Visual Studio 2022. It is located at the following directory
Enterprise:
C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\Microsoft\Azure Storage Emulator
Professional:
C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\Extensions\Microsoft\Azure Storage Emulator
Pull the azurite image:
docker pull mcr.microsoft.com/azure-storage/azurite
Run the azurite:
docker run --rm -p 10000:10000 -p 10001:10001 -p 10002:10002 mcr.microsoft.com/azure-storage/azurite
Other than the Azurite, you are required to install Microsoft Azure Storage Explorer to browse the logs written into the blob storage.
Serilog.AspNetCore
Serilog.Sinks.AzureBlobStorage
You may use 1 of the following methods to be implemented into your Program.cs file.
Method 1: Configure Serilog in code.
loggerConfiguration
.WriteTo.Console()
.WriteTo.AzureBlobStorage(
"DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;",
storageContainerName: "writetoazureblobstoragewithserilog",
.UseSerilog((hostBuilderContext, loggerConfiguration) => {
loggerConfiguration
.WriteTo.Console()
.WriteTo.AzureBlobStorage(
"DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;",
storageContainerName: "writetoazureblobstoragewithserilog",
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Method 2: Configure Serilog from appSettings file.
"Name": "Console"
{
"Name": "AzureBlobStorage",
}
]
}
loggerConfiguration
.ReadFrom.Configuration(hostBuilderContext.Configuration));
.UseSerilog((hostBuilderContext, loggerConfiguration) =>
{
loggerConfiguration
.ReadFrom.Configuration(hostBuilderContext.Configuration);
SelfLog.Enable(Console.Error);
})
For more details on the setup and the ConnectionString, do refer this link https://docs.microsoft.com/en-us/azure/storage/common/storage-use-azurite?tabs=visual-studio
No comments:
Post a Comment