在開發Sharepoint Solution時,我們可以使用Attach to process來Debug我們的方案,然而一旦我們把Solution部署到了生產機上,我們就難以再使用這個最直接的方法了,如果Solution出錯,我們就需要足夠的手段來擷取盡量明細的錯誤資訊,USL log(Unified Logging Service)則為我們提供了一條途徑來協助我們定位使用者的跟蹤資訊。在早期的Sharepoint2007中,雖然也有ULS隨著一起發布,但我們卻不能使用它,這在SharePoint2007的SDK 中明確說明了這點,它僅限於內部使用。到了SharePoint 2010則改變了這一切,我們現在也可以在我們的代碼中使用它來寫入我們需要捕獲的跟蹤資訊了。
請建立一個Sharepoint項目,在項目中建立一個Visual Web Part,如下
在按鈕的Click後台代碼中寫入(需要引入 Microsoft.SharePoint.Administration)
protected void btnLogin_Click(object sender, EventArgs e)
{
try { var i = 0; var a = 2 / i; }
catch (Exception ex) { LoggingService.LogError("WebParts", ex.Message); }
}
Built 此項目並部署到測試網站,然後運行WebPart上的Button的Click事件,就會有錯誤資訊寫到ULS log中 (請在目錄
\Program files\Common Files\Microsoft Shared\Web Server Extensions\14\Logs 下去找相關Log, 預設情況下,跟蹤log名由電腦名稱加上日期和時間資訊組成,檔案類型為“文字文件”。),通常你可以使用SharePoint ULS Log Viewer開啟對應的Log檔案可以看到錯誤事件記錄如下(你也可以用微軟提供的ULSViewer來查看,它的用法會有一些不同):
你會注意到,在開啟的Log檔案中,對應的按鈕事件的報錯記錄的Area地區值為Unkown,如果我們有多個Solution部署到伺服器上,這會讓我們很難識別到底是哪個Solution註冊的錯誤,因此我們需要進一步改進我們的作法,所以,請在原項目中新建立一個類,此類繼承自SPDiagnosticsServiceBase基類,如
此類的定義代碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration; //需要引入
namespace CopyListContent
{
public class LoggingService : SPDiagnosticsServiceBase
{
public static string MyDiagnosticAreaName = "MyDiagnosticTest";
private static LoggingService _Current;
public static LoggingService Current
{
get
{
if (_Current == null)
{ _Current = new LoggingService(); }
return _Current;
}
}
private LoggingService()
: base("MyDiagnosticTest Logging Service", SPFarm.Local)
{ }
protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
{
List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea> {
new SPDiagnosticsArea(MyDiagnosticAreaName, new List<SPDiagnosticsCategory>
{new SPDiagnosticsCategory("WebParts", TraceSeverity.Unexpected, EventSeverity.Error) })};
return areas;
}
public static void LogError(string categoryName, string errorMessage)
{
SPDiagnosticsCategory category = LoggingService.Current.Areas[MyDiagnosticAreaName].Categories[categoryName];
LoggingService.Current.WriteTrace(0, category, TraceSeverity.Unexpected, errorMessage);
}
}
}
在此類中,我們在Area地區寫入了我們當前Solution的標識名"MyDiagnosticTest",重新修改按鈕事件的定義,引用我們上面定義的類來寫入ULS log
protected void btnLogin_Click(object sender, EventArgs e)
{
try { var i = 0; var a = 2 / i; }
catch (Exception ex)
{ SPDiagnosticsService.Local.WriteTrace(0,
new SPDiagnosticsCategory("My Category", TraceSeverity.Unexpected, EventSeverity.Error),
TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}
重新Built Solution並部署運行,回到ULS log中用SharePoint ULS Log Viewer查看,可以看到如下
我們可以通過識別Area欄位來更加容易的找到屬於我們的Solution寫入的報錯資訊了。當然你還可以靈活的組織你需要寫入的內容從而方便你更加容易地定位Solution的使用者跟蹤資訊。