Search code examples
c#.netserilog

Serilog log certain object attributes of a list of objects


Given a list of objects, I'd like to log a specific attribute of each element in the list (say, its name). The only thing I can think of is logging in a forloop. Is there a better way to achieve what I want?

Small example:

public class Dog
{
    public string Name { get; set; }

    public int Id { get; set; }

    public bool CanBark{ get; set; }
}

and then somewhere else in my code

public void GetAllDogsWithLogs(){
    List<Dog> barkingDogs = GetBarkingDogs();
    foreach(var dog in barkingDogs){  // ---> I'd like to avoid a forloop just for logging
        Log.Debug("Found barking dog {Name} with Id {Id}", dog.Name, dog.Id);
    }
}

Note that I cannot log all attributes of my objects, since that would introduce way too much noise into my logs.


Solution

  • For posterity: I ended up solving this using LINQ:

    Log.Debug("Found barking dogs with name and ID {NameIds}", 
                barkingDogs.Select(dog => (dog.Name, dog.Id));