The System.NullReferenceException you're encountering in your LogValue method typically means that either valueName or objectValue is null, and the logging library (like Serilog) is not handling it gracefully, or some internal state is missing.
Let’s break down what could be going wrong and how to fix it:
✅ Original Code
public override void LogValue(string valueName, object objectValue)
{
Log.Information("{ValueName}: {@ObjectValue}", valueName, objectValue);
}
This uses Serilog syntax for structured logging. The {@ObjectValue} indicates a destructured object.
🚨 Problem: NullReferenceException
A NullReferenceException here can happen due to:
Log is null – i.e., the logger hasn't been initialized.
- One of the parameters (
valueName or objectValue) is null, and something in the logging pipeline fails on null values.
- A custom sink or formatter has a bug when handling nulls.
🔍 How to Fix
✅ 1. Check if Log is initialized
Make sure that you have initialized the static Log class before calling Log.Information(...).
Example:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
If this line is missing somewhere early in your app startup, then Log will be null, and trying to call Log.Information(...) will throw a NullReferenceException.
✅ 2. Add null checks in your method
You can guard against null inputs like this:
public override void LogValue(string valueName, object objectValue)
{
if (Log.Logger == null) return;
valueName ??= "<null>";
objectValue ??= "<null>";
Log.Information("{ValueName}: {@ObjectValue}", valueName, objectValue);
}
This avoids issues from either parameter being null.
✅ 3. Use conditional logging or fallbacks
Alternatively, log only if inputs are non-null:
public override void LogValue(string valueName, object objectValue)
{
if (Log.Logger == null) return;
if (valueName == null || objectValue == null)
{
Log.Warning("LogValue called with null: valueName={ValueName}, objectValue={@ObjectValue}",
valueName, objectValue);
return;
}
Log.Information("{ValueName}: {@ObjectValue}", valueName, objectValue);
}
✅ 4. Verify dependencies and logger configuration
If you're using dependency injection (e.g., in ASP.NET Core), consider injecting ILogger instead of using the static Log class directly.
Example:
private readonly ILogger _logger;
public MyClass(ILogger<MyClass> logger)
{
_logger = logger;
}
Then use _logger.LogInformation(...) instead of Log.Information(...).
🧪 Summary Checklist
| Step | Action |
|---|
| ✅ | Ensure Log.Logger is initialized before usage. |
| ✅ | Add null checks for valueName and objectValue. |
| ✅ | Consider using injected logger (ILogger) instead of static Log. |
| ✅ | Test by passing nulls to see how your logger behaves. |
Let me know your environment (e.g., ASP.NET Core? Console app? Which version of Serilog?) if you'd like a more tailored fix!