項目開發過程寫過幾個WPF的小工具,在使用過程中就需要把軟件運行的情況以日誌的形式輸出到界面上,這裏就把用過的幾種方式總結一下。
1.直接輸出到RichTextBox
輸出到RichTextBox很簡單直接了,代碼如下:
/// <summary>
/// 日誌輸出
/// </summary>
/// <param name="message"></param>
public void WriteToLog(string message)
{
if (!(txtRich.CheckAccess()))
{
this.Dispatcher.Invoke(() =>
WriteToStatus(message)
);
return;
}
string strTime = "[" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ";
txtRich.AppendText(strTime + message + "\r");
if (txtRich.ExtentHeight > 200)
{
txtRich.Document.Blocks.Clear();
}
}
其中txtRich就是界面UI上RichTextBox的名稱,在需要輸出日誌的地方調用方法WriteToLog()即可。
2.使用Nlog輸出到文件
上面的方法只能算是“僞日誌”,畢竟只是將信息輸出到UI控件上,正統的日誌還是要靠NLog、log4net這樣的日誌組件。
2.1.安裝NLog.Config
打開項目的Nuget管理器,搜索NLog.Config並安裝。
其實只安裝NLog也是可以的。但是NLog.Config已經包含了NLog,而且有了NLog.Config編寫配置文件更方便些。
2.2.配置NLog
NLog.Config安裝成功後,項目跟目錄下會增加NLog.config和NLog.xsd兩個文件。修改NLog.config文件,對輸出日誌的格式、輸出形式、跟蹤級別進行配置。
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<variable name="myvar" value="myvalue"/>
<!-- 輸出目標 -->
<targets>
<!- 輸出至文件 -->
<target name="info_file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
<target name="error_file" xsi:type="File" fileName="${basedir}/logs/${shortdate}_error.log"
layout="${longdate} ${uppercase:${level}} ${message} ${exception:stacktrace}" />
</targets>
<!-- 日誌規則 -->
<rules>
<logger name="*" minlevel="Info" writeTo="info_file" />
<logger name="*" minlevel="Error" writeTo="error_file" />
</rules>
</nlog>
在代碼中定義日誌管理器,直接調用。
//定義日誌
private Logger logger = LogManager.GetCurrentClassLogger();
//調用日誌
private void BtnLog_Click(object sender, RoutedEventArgs e)
{
logger.Info("開始輸出日誌!");
}
啓動程序,在運行過程中產生的信息就會輸出到指定目錄的文件中。也可以通過修改配置文件,將日誌輸出到其他目標位置。
3.將日誌輸出到UI控件
將上述兩種方法結合起來,既可以在UI界面實時顯示,也能在後臺穩定輸出。幸運的是可以使用NLog.wpf.RichTextBox這個庫,雖然時間比較久遠了,但是用起來還是很方便的。打開Nuget管理器,安裝NLog.wpf.RichTextBox。安裝完成後項目會增加WpfRichTextBoxTarget.cs、WpfRichTextBoxRowColoringRule.cs、WpfRichTextBoxWordColoringRule.cs三個文件,具體使用方法可以參考附帶的txt文件。
在需要輸出日誌的地方修改代碼如下:
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(() =>
{
var target = new WpfRichTextBoxTarget
{
Name = "RichText",
Layout = "[${longdate:useUTC=false}] :: [${level:uppercase=true}] :: ${logger}:${callsite} :: ${message} ${exception:innerFormat=tostring:maxInnerExceptionLevel=10:separator=,:format=tostring}",
ControlName = "你的控件名稱",
FormName = GetType().Name,
AutoScroll = true,
MaxLines = 1000,
UseDefaultRowColoringRules = true,
};
var asyncWrapper = new AsyncTargetWrapper { Name = "RichTextAsync", WrappedTarget = target };
LogManager.Configuration.AddTarget(asyncWrapper.Name, asyncWrapper);
LogManager.Configuration.LoggingRules.Insert(0, new LoggingRule("*", LogLevel.Info, asyncWrapper));
LogManager.ReconfigExistingLoggers();
});
}
同樣是把日誌輸出到RichTextBox,結合了上兩種方法,對於軟件運行的監測和問題檢查會有很大的幫助。