1

I usually have methods returning IList. I need to log the result coming back in this list.

Is there a better way than looping on the items inside the list and printing them one by one like this?

foreach(string productName in productsNames)
            {
                prodsNames.Append(productName + " ");
            }
Logger.Debug("Loading data for Producers: " + prodsNames);

is there some way of making this easier?

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Emad Gabriel
  • 3,677
  • 7
  • 37
  • 49

4 Answers4

1

I would write a wrapper for log4net that exposes a method like this:

void Debug(string message, IList elements);

The implementation could look be as follows (some details are omitted):

public Debug(string message, IList elements)
{
    // this.Logger returns a reference to ILog object
    if (this.Logger.IsDebugEnabled)
    {            
        string logMessage;
        // build the string that you want to write to the log
        this.Logger.Debug(logMessage);      
    }
}

That is just an example: You can design your interface the way that is best suited for you.

Here you can find some ideas what a wrapper might look like.

Community
  • 1
  • 1
Stefan Egli
  • 17,398
  • 3
  • 54
  • 75
  • maybe also consider this, if you write a wrapper: http://stackoverflow.com/questions/2049992/when-using-wrapper-how-to-preserve-class-and-method-name-for-log4net-to-log/3448439#3448439 – Stefan Egli Aug 11 '10 at 18:57
1

Serialize the list to XML, log the XML string.

Ashley
  • 129
  • 8
  • Thanks, I've added serialized my list into json before I pass it to my dynamic object and then to serilog and it worked. It was just a basic string list I was hoping serilog would handle it but seems like it's not sadly. – Shino Lex Apr 06 '22 at 08:14
1

Is there any reason to not to use string.Join()?

Logger.Debug("Loading data for Producers: " + string.Join(" ", productsNames));
Anubis
  • 6,995
  • 14
  • 56
  • 87
  • This definitely works, but has the side effect of spending CPU cycles/heap allocations on the formatting, even if the debug logging level isn't enabled (whether this matters depends on the perf requirements of the situation, of course :-)) – Nicholas Blumhardt Oct 25 '18 at 21:37
1

With NLog and Serilog you can do this:

Logger.Debug("Loading data for Producers: {producers}", prodsNames);

See also https://messagetemplates.org/

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
  • Unlike the string-formatting options, this has the benefit of the elements being nicely searchable using queries like `producers[?] = 'apples'`, if you send the events to a JSON-capable log server. – Nicholas Blumhardt Oct 25 '18 at 21:35