Home > Software engineering >  Serilog difference between Log.Information and Log.Logger.Information when logging potentially null
Serilog difference between Log.Information and Log.Logger.Information when logging potentially null

Time:11-18

I'd like to know if there's a specific syntax that I'm supposed to use when using Serilog.

The documentation shows Log.Debug([...]) in pretty much every example.

However, given the following demo code:

using Serilog;

internal record User(
    string FirstName, 
    string? LastName, 
    string Email, 
    int Id, 
    int Age, 
    string NickName
);

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();

        var user = new User("First", null, "", 1, 2, "Test");


        Log.Debug("User: {firstName} {lastName} {email} {id} {age} {nickname}", user.FirstName, user.LastName, user.Email, user.Id, user.Age, user.NickName);
        Log.Logger.Debug("User: {firstName} {lastName}", user.FirstName, user.LastName, user.Email, user.Id, user.Age, user.NickName);
    }

}

I get compiler warnings (warning CS8604: Possible null reference argument for parameter 'propertyValues' in 'void Log.Debug(string messageTemplate, params object[] propertyValues)'.) for the first Log.Debug call because user.LastName could be null. The Log.Debug method shows the following parameters:

Log.Debug method

Whereas the Log.Logger.Debug call does not give me this compiler warning, because it has a different signature:

Log.Logger.Debug method

This makes me want to use the second method, instead of the global Log class. Is this difference intentional and should I be using the Log class over the Log.Logger setup, or is it simply an oversight/bug in the Serilog library?

During runtime I haven't noticed a difference.

I've used both methods, one gives me the compiler warnings, the other doesn't. I don't care if I have to use Log.Logger to make the warnings go away, but I'd just like to confirm that one isn't better than the other.

CodePudding user response:

The latest source code uses the same arguments and won't generate any nullability warnings :

[MessageTemplateFormatMethod("messageTemplate")]
public static void Debug(string messageTemplate, params object?[]? propertyValues)
{
    Logger.Debug(messageTemplate, propertyValues);
}

Github's Blame shows that this line was last modified in August 2022. The fix should be included in Serilog 2.12 which was released in September 2022

  • Related