
In this guide, we’ll create a structured solution with two projects: a common project, Common
, responsible for logging setup and constants, and an MVC web project, SerilogMultipleProject
, which retrieves logging configurations from the common project.
You can download the complete source code here: SerilogMultipleProject on GitHub
Step 1: Create the Solution and Common Project
1.1 Create Solution
- Open Visual Studio and go to File -> New -> Project.
- Select ASP.NET Core Web Application as the project type.
- Name the solution SerilogMultipleProject.
1.2 Add Common Project
- Inside the solution, add a new project named Common (choose Class Library as the project type).
- In the Common project, create two classes:
LoggingHelper.cs
andApplicationConstants.cs
.
Step 2: Configure Serilog in the Common Project
2.1 Install Serilog Packages
In the Common project:
- Right-click on the project and select Manage NuGet Packages.
- Install the following packages:
Serilog.AspNetCore
Serilog.Sinks.Async
2.2 Implement Logging Configuration
Define LoggingHelper
with Serilog configuration in LoggingHelper.cs
.
LoggingHelper.cs (located in Common.Helpers
):
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Common.Constants;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
namespace Common.Helpers
{
public static class LoggingHelper
{
public static IHostBuilder UseSerilog(this IHostBuilder builder)
{
return builder.UseSerilog((context, services, config) =>
{
config.ReadFrom.Configuration(context.Configuration);
config.WriteTo.Console(levelSwitch: ApplicationConstants.ConsoleLogLevel);
config.Enrich.FromLogContext();
});
}
public static void InitializeLogger(string[] args)
{
var configRoot = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile(ApplicationConstants.AppSettingsFileName, optional: false)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configRoot)
.WriteTo.Async(a => a.Console(levelSwitch: ApplicationConstants.ConsoleLogLevel))
.Enrich.FromLogContext()
.CreateBootstrapLogger();
}
public static void LogStartupMessages(string[] args)
{
var argsText = args.Length switch
{
> 1 => $"with arguments '{string.Join(' ', args)}'",
> 0 => $"with argument '{args[0]}'",
_ => "without any arguments"
};
Log.Information($"{ApplicationConstants.ApplicationName} is starting {argsText}.");
Log.Information("Process Id: {ProcessId}", ApplicationConstants.ProcessId);
Log.Information("Base directory path: {BaseDirectory}", AppContext.BaseDirectory);
LogJenkinsBuildInfo();
}
private static void LogJenkinsBuildInfo()
{
string buildInfoPath = Path.Combine(ApplicationConstants.ExecutionPath, "BuildInfo.properties");
if (!File.Exists(buildInfoPath))
{
Log.Warning("Couldn't find the BuildInfo.properties file.");
return;
}
var buildInfo = File.ReadLines(buildInfoPath)
.Where(line => line.Contains('='))
.ToDictionary(line => line.Split('=')[0], line => line.Split('=')[1]);
buildInfo.Add("machineName", Environment.MachineName);
buildInfo.Add("machineIP", GetLocalIPAddress());
Log.Information("Build info of the application: {FraudApiBuildInfo}", buildInfo);
}
private static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return host.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString() ?? "No IP";
}
}
}
2.3 Define Constants in Common Project
Define constants used in the ApplicationConstants.cs
file.
ApplicationConstants.cs (located in Common.Constants
):
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Common.Constants
{
public static class ApplicationConstants
{
public static readonly string ApplicationName = System.Reflection.Assembly.GetEntryAssembly()!.GetName().Name!;
public static readonly string EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
public static readonly string OperatingSystem = Environment.OSVersion.Platform.ToString();
public static readonly string ProcessId = Environment.ProcessId.ToString();
public static readonly string AppSettingsFileName = "appsettings.json";
public static readonly LoggingLevelSwitch ConsoleLogLevel = new();
public static readonly string ExecutionPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)!;
public static readonly List<string> AllowedDomainList = new() { "localhost", "mybestman" };
static ApplicationConstants()
{
// Initialize environment-specific settings or other constants here if needed.
}
}
}
Step 3: Create an MVC Web Project
3.1 Add MVC Project
- Add a new project to the solution, named SerilogMultipleProject (ASP.NET Core Web Application).
- Choose the Web Application template.
3.2 Configure Logging in MVC Project
In Program.cs
of the SerilogMultipleProject project, integrate the logging configurations from the Common project.
Program.cs (located in SerilogMultipleProject
):
using Common.Helpers;
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Initialize Serilog Logger
LoggingHelper.InitializeLogger(args);
builder.Host.UseSerilog();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
3.3 Update appsettings.json for Serilog
In the SerilogMultipleProject project, add the following configuration to appsettings.json
to configure Serilog’s logging settings:
"Serilog": {
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "Async",
"Args": {
"Configure": [
{
"Name": "File",
"Args": {
"Formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact",
"RollingInterval": "Day",
"Path": "C:/Logs/SerilogMultipleProject/SerilogMultipleProject..log",
"RestrictedToMinimumLevel": "Debug",
"RollOnFileSizeLimit": true,
"FileSizeLimitBytes": 10485760
}
}
]
}
}
]
}
Step 4: Run the Application
Run the SerilogMultipleProject application to ensure the logging setup is functioning as expected. You should see logs in the specified file location as well as in the console output.
For more details, download the full source code here: SerilogMultipleProject on GitHub