2017-06-13 28 views
0

我有将条目写入日志文件中,事件日志通用Log方法等用的String.Format能力测井方法

public static void Log(string logEntry) 
{ 
    // Write DateTime and logEntry to Log File, Event Log, etc. 
} 

我创建过载使用以下提供的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)); 
} 

这工作不错,但有参考剩余数组项传递到的String.Format()函数更好的办法?或者更好的方法来从数组中删除元素0?

我知道我也可以只使用日志(的String.Format(...,但我提供此较正式的用途。

回答

4

你可以使用

public void Log(string message, params object[] args) 

或更好,但使用现有框架例如NLOG或log4net的,其具有的API等

public void Log(LogLevel level, string message, param object[] args) 

public void Log(LogLevel level, Exception exception, string message, param object[] args) 
+0

谢谢,有时最简单的办法是忽视! –

3

我会匹配参数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)); 
}