Reputation: 13633
I have general purpose Log method that writes entries to Log File, Event Log, etc.
public static void Log(string logEntry)
{
// Write DateTime and logEntry to Log File, Event Log, etc.
}
I created overload to provide String.Format() functionality using the following:
public static void Log(params object[] logEntry)
{
// Purpose: Overload Log method to provide String.Format() functionality
// with first parameter being Format string.
// Example: Log("[{0:yyyy-MM-dd}] Name: {1}, Value: {2:#,##0.00}", DateTime.Now, "Blah, Blah, Blah", 12345.67890)
string formatString = logEntry[0].ToString();
object[] values = new object[logEntry.Length - 1];
for (int i = 1; i < logEntry.Length; i++)
{
values[i - 1] = logEntry[i];
}
Log(String.Format(formatString, values));
}
This works okay, but is there a better way to reference remaining array items to pass to the String.Format() function? Or better way to remove element 0 from the array?
I know I could also just use Log(String.Format(..., but am providing this for more formal purposes.
Upvotes: 1
Views: 3347
Reputation: 33738
I'd match the parameters to String.Format()
.
public static void Log(string logEntry)
{
Log(logEntry, null);
}
public static void Log(string logEntry, params object[] values)
{
// Do whatever extra processing you need here.
Log(String.Format(logEntry, values));
}
Upvotes: 3
Reputation: 18068
You could use
public void Log(string message, params object[] args)
or better yet, use an existing framework e.g. NLog or Log4Net, which have APIs like
public void Log(LogLevel level, string message, param object[] args)
and
public void Log(LogLevel level, Exception exception, string message, param object[] args)
Upvotes: 6