I have general purpose Log method that writes entries to Log File, Event Log, etc.
我有通用的Log方法,它将条目写入日志文件,事件日志等。
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:
我使用以下方法创建了重载以提供String.Format()功能:
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?
这没关系,但有没有更好的方法来引用剩余的数组项以传递给String.Format()函数?或者更好的方法从数组中删除元素0?
I know I could also just use Log(String.Format(..., but am providing this for more formal purposes.
我知道我也可以使用Log(String.Format(...,但我提供这个用于更正式的目的)。
2 个解决方案
#1
4
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
或者更好的是,使用现有框架,例如NLog或Log4Net,它们都有API
public void Log(LogLevel level, string message, param object[] args)
and
和
public void Log(LogLevel level, Exception exception, string message, param object[] args)
#2
3
I'd match the parameters to String.Format()
.
我将参数与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));
}
#1
4
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
或者更好的是,使用现有框架,例如NLog或Log4Net,它们都有API
public void Log(LogLevel level, string message, param object[] args)
and
和
public void Log(LogLevel level, Exception exception, string message, param object[] args)
#2
3
I'd match the parameters to String.Format()
.
我将参数与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));
}