Of course. This is a very common error in C#. Let's break down why it's happening and how to fix it.
The Problem: Why the Exception Occurs
The error System.NullReferenceException: 'Object reference not set to an instance of an object.' happens when you try to use a variable (in this case, call a method on it) that has a value of null.
In your code:
Log.Information("{ValueName}: {@ObjectValue}", valueName, objectValue);
The exception is being thrown on this line. This means that the object you are trying to call the .Information() method on is null. In this case, that object is Log.
The Log object has not been initialized before the LogValue method was called.
This Log object is almost certainly a static logger instance from a library like Serilog. This is a classic symptom of forgetting to configure the logger when your application starts.
The Fix: Initialize Your Logger
You need to configure and assign your logger object before you ever try to use it. This is typically done once at the very beginning of your application's lifecycle (e.g., in Program.cs or Startup.cs).
Assuming you are using Serilog, here is how you would fix it.
Step 1: Install Serilog packages
If you haven't already, make sure you have the necessary Serilog packages installed. You'll at least need Serilog and a "sink" (a place to write logs to, like the console).
dotnet add package Serilog
dotnet add package Serilog.Sinks.Console
Step 2: Configure the Logger at Application Startup
In your application's entry point (Program.cs), you must configure the static Log class.
Example for a Console Application (Program.cs)
using Serilog;
using System;
public class Program
{
public static void Main(string[] args)
{
// *** FIX IS HERE: Configure the static logger ***
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug() // Set the minimum log level
.WriteTo.Console() // Configure it to write to the console
.CreateLogger(); // Create the logger
Log.Information("Logger configured. Application starting up.");
try
{
// Your application logic here...
var myService = new MyLoggingService();
myService.DoSomething();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
// IMPORTANT: Flush any buffered logs before the application closes
Log.CloseAndFlush();
}
}
}
// This would be the class containing your method
public class MyLoggingService
{
public virtual void LogValue(string valueName, object objectValue)
{
// This line will now work because Log.Logger has been assigned.
Log.Information("{ValueName}: {@ObjectValue}", valueName, objectValue);
}
public void DoSomething()
{
Log.Information("Doing something important...");
var user = new { Name = "Alice", Id = 123 };
LogValue("CurrentUser", user);
}
}
Alternative: Using Dependency Injection (Recommended for Modern Apps)
While the static Log class is easy to use, the modern and more testable approach is to use dependency injection (DI). This is the standard in ASP.NET Core, MAUI, etc.
In this pattern, you don't use a static Log class. Instead, you inject an ILogger instance into your class's constructor.
Step 1: Configure Logging in your DI container
In an ASP.NET Core Program.cs:
// Program.cs
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog
builder.Host.UseSerilog((context, config) =>
{
config.ReadFrom.Configuration(context.Configuration);
});
// ... rest of builder configuration
var app = builder.Build();
// ...
Step 2: Inject and Use ILogger in Your Class
You would then refactor your class to accept an ILogger.
using Microsoft.Extensions.Logging; // Note the different namespace
public class MyLoggingService
{
// Store the logger in a private field
private readonly ILogger<MyLoggingService> _logger;
// The logger is "injected" via the constructor by the DI container
public MyLoggingService(ILogger<MyLoggingService> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
// This is the fixed method
public void LogValue(string valueName, object objectValue)
{
// Use the injected _logger instance, not a static class
_logger.LogInformation("{ValueName}: {@ObjectValue}", valueName, objectValue);
}
public void DoSomething()
{
_logger.LogInformation("Doing something important...");
var user = new { Name = "Alice", Id = 123 };
LogValue("CurrentUser", user);
}
}
Summary of Fixes
- For Static
Log (like Serilog): Initialize Log.Logger at the very start of your application in Program.cs. This is the direct fix for the code you provided.
- For Dependency Injection (Recommended): Don't use a static
Log class. Instead, add an ILogger<T> parameter to your class's constructor and use the instance (_logger) provided by the DI framework.