开发者

What is a simple way to log all items in a list using log4net (or other logging frameworks)?

开发者 https://www.devze.com 2023-01-10 20:17 出处:网络
I usually have me开发者_C百科thods returning IList. I need to log the result coming back in this list.

I usually have me开发者_C百科thods 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?


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.


Serialize the list to XML, log the XML string.


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

Logger.Debug("Loading data for Producers: " + string.Join(" ", productsNames));


With NLog and Serilog you can do this:

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

See also https://messagetemplates.org/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号