2008-09-25 73 views
6

我想在我的SharePoint Web部件登錄的東西,但我想它去到ULS。我發現的大多數例子都是登錄到事件日誌或其他文件中的,但是我沒有真正找到一個用於登錄ULS的例子。編程登錄到SharePoint ULS

煩人,Microsoft.SharePoint.Diagnostics類無不打上內部。我確實發現one example反正如何使用它們,但看起來確實有風險和不穩定,因爲微軟可能會用他們想要的任何修補程序更改該類。

在SharePoint文檔是不是真的有幫助的任何 - 大量的關於什麼是ULS以及如何配置它,但我還沒有找到支持的代碼示例實際登錄我自己的事件管理信息。

任何提示或建議?

編輯:正如您可以從這個問題的年齡看,這是SharePoint 2007在SharePoint 2010中,您可以使用SPDiagnosticsService.Local然後WriteTrace。請參閱下面Jürgen的答案。

回答

8

是的,這是可能的,看到這個MSDN文章:http://msdn2.microsoft.com/hi-in/library/aa979595(en-us).aspx

,這裏是在C#中的一些示例代碼:

using System; 
using System.Runtime.InteropServices; 
using Microsoft.SharePoint.Administration; 

namespace ManagedTraceProvider 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     TraceProvider.RegisterTraceProvider(); 

     TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.High, Guid.Empty, "MyExeName", "Product Name", "Category Name", "Sample Message"); 
     TraceProvider.WriteTrace(TraceProvider.TagFromString("abcd"), TraceProvider.TraceSeverity.Monitorable, Guid.NewGuid(), "MyExeName", "Product Name", "Category Name", "Sample Message"); 

     TraceProvider.UnregisterTraceProvider(); 
    } 
} 

static class TraceProvider 
{ 
    static UInt64 hTraceLog; 
    static UInt64 hTraceReg; 

    static class NativeMethods 
    { 
     internal const int TRACE_VERSION_CURRENT = 1; 
     internal const int ERROR_SUCCESS = 0; 
     internal const int ERROR_INVALID_PARAMETER = 87; 
     internal const int WNODE_FLAG_TRACED_GUID = 0x00020000; 

     internal enum TraceFlags 
     { 
      TRACE_FLAG_START = 1, 
      TRACE_FLAG_END = 2, 
      TRACE_FLAG_MIDDLE = 3, 
      TRACE_FLAG_ID_AS_ASCII = 4 
     } 

     // Copied from Win32 APIs 
     [StructLayout(LayoutKind.Sequential)] 
     internal struct EVENT_TRACE_HEADER_CLASS 
     { 
      internal byte Type; 
      internal byte Level; 
      internal ushort Version; 
     } 

     // Copied from Win32 APIs 
     [StructLayout(LayoutKind.Sequential)] 
     internal struct EVENT_TRACE_HEADER 
     { 
      internal ushort Size; 
      internal ushort FieldTypeFlags; 
      internal EVENT_TRACE_HEADER_CLASS Class; 
      internal uint ThreadId; 
      internal uint ProcessId; 
      internal Int64 TimeStamp; 
      internal Guid Guid; 
      internal uint ClientContext; 
      internal uint Flags; 
     } 

     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 
     internal struct ULSTraceHeader 
     { 
      internal ushort Size; 
      internal uint dwVersion; 
      internal uint Id; 
      internal Guid correlationID; 
      internal TraceFlags dwFlags; 
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] 
      internal string wzExeName; 
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] 
      internal string wzProduct; 
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] 
      internal string wzCategory; 
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 800)] 
      internal string wzMessage; 
     } 

     [StructLayout(LayoutKind.Sequential)] 
     internal struct ULSTrace 
     { 
      internal EVENT_TRACE_HEADER Header; 
      internal ULSTraceHeader ULSHeader; 
     } 

     // Copied from Win32 APIs 
     internal enum WMIDPREQUESTCODE 
     { 
      WMI_GET_ALL_DATA = 0, 
      WMI_GET_SINGLE_INSTANCE = 1, 
      WMI_SET_SINGLE_INSTANCE = 2, 
      WMI_SET_SINGLE_ITEM = 3, 
      WMI_ENABLE_EVENTS = 4, 
      WMI_DISABLE_EVENTS = 5, 
      WMI_ENABLE_COLLECTION = 6, 
      WMI_DISABLE_COLLECTION = 7, 
      WMI_REGINFO = 8, 
      WMI_EXECUTE_METHOD = 9 
     } 

     // Copied from Win32 APIs 
     internal unsafe delegate uint EtwProc(NativeMethods.WMIDPREQUESTCODE requestCode, IntPtr requestContext, uint* bufferSize, IntPtr buffer); 

     // Copied from Win32 APIs 
     [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] 
     internal static extern unsafe uint RegisterTraceGuids([In] EtwProc cbFunc, [In] void* context, [In] ref Guid controlGuid, [In] uint guidCount, IntPtr guidReg, [In] string mofImagePath, [In] string mofResourceName, out ulong regHandle); 

     // Copied from Win32 APIs 
     [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] 
     internal static extern uint UnregisterTraceGuids([In]ulong regHandle); 

     // Copied from Win32 APIs 
     [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] 
     internal static extern UInt64 GetTraceLoggerHandle([In]IntPtr Buffer); 

     // Copied from Win32 APIs 
     [DllImport("advapi32.dll", SetLastError = true)] 
     internal static extern uint TraceEvent([In]UInt64 traceHandle, [In]ref ULSTrace evnt); 
    } 

    public enum TraceSeverity 
    { 
     Unassigned = 0, 
     CriticalEvent = 1, 
     WarningEvent = 2, 
     InformationEvent = 3, 
     Exception = 4, 
     Assert = 7, 
     Unexpected = 10, 
     Monitorable = 15, 
     High = 20, 
     Medium = 50, 
     Verbose = 100, 
    } 

    public static void WriteTrace(uint tag, TraceSeverity level, Guid correlationGuid, string exeName, string productName, string categoryName, string message) 
    { 
     const ushort sizeOfWCHAR = 2; 
     NativeMethods.ULSTrace ulsTrace = new NativeMethods.ULSTrace(); 

     // Pretty standard code needed to make things work 
     ulsTrace.Header.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTrace)); 
     ulsTrace.Header.Flags = NativeMethods.WNODE_FLAG_TRACED_GUID; 
     ulsTrace.ULSHeader.dwVersion = NativeMethods.TRACE_VERSION_CURRENT; 
     ulsTrace.ULSHeader.dwFlags = NativeMethods.TraceFlags.TRACE_FLAG_ID_AS_ASCII; 
     ulsTrace.ULSHeader.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTraceHeader)); 

     // Variables communicated to SPTrace 
     ulsTrace.ULSHeader.Id = tag; 
     ulsTrace.Header.Class.Level = (byte)level; 
     ulsTrace.ULSHeader.wzExeName = exeName; 
     ulsTrace.ULSHeader.wzProduct = productName; 
     ulsTrace.ULSHeader.wzCategory = categoryName; 
     ulsTrace.ULSHeader.wzMessage = message; 
     ulsTrace.ULSHeader.correlationID = correlationGuid; 

     // Pptionally, to improve performance by reducing the amount of data copied around, 
     // the Size parameters can be reduced by the amount of unused buffer in the Message 
     if (message.Length < 800) 
     { 
      ushort unusedBuffer = (ushort) ((800 - (message.Length + 1)) * sizeOfWCHAR); 
      ulsTrace.Header.Size -= unusedBuffer; 
      ulsTrace.ULSHeader.Size -= unusedBuffer; 
     } 

     if (hTraceLog != 0) 
      NativeMethods.TraceEvent(hTraceLog, ref ulsTrace); 
    } 

    public static unsafe void RegisterTraceProvider() 
    { 
     SPFarm farm = SPFarm.Local; 
     Guid traceGuid = farm.TraceSessionGuid; 
     uint result = NativeMethods.RegisterTraceGuids(ControlCallback, null, ref traceGuid, 0, IntPtr.Zero, null, null, out hTraceReg); 
     System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS); 
    } 

    public static void UnregisterTraceProvider() 
    { 
     uint result = NativeMethods.UnregisterTraceGuids(hTraceReg); 
     System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS); 
    } 

    public static uint TagFromString(string wzTag) 
    { 
     System.Diagnostics.Debug.Assert(wzTag.Length == 4); 
     return (uint) (wzTag[0] << 24 | wzTag[1] << 16 | wzTag[2] << 8 | wzTag[3]); 
    } 

    static unsafe uint ControlCallback(NativeMethods.WMIDPREQUESTCODE RequestCode, IntPtr Context, uint* InOutBufferSize, IntPtr Buffer) 
    { 
     uint Status; 
     switch (RequestCode) 
     { 
      case NativeMethods.WMIDPREQUESTCODE.WMI_ENABLE_EVENTS: 
       hTraceLog = NativeMethods.GetTraceLoggerHandle(Buffer); 
       Status = NativeMethods.ERROR_SUCCESS; 
       break; 
      case NativeMethods.WMIDPREQUESTCODE.WMI_DISABLE_EVENTS: 
       hTraceLog = 0; 
       Status = NativeMethods.ERROR_SUCCESS; 
       break; 
      default: 
       Status = NativeMethods.ERROR_INVALID_PARAMETER; 
       break; 
     } 

     *InOutBufferSize = 0; 
     return Status; 
    } 
} 

}

+1

我以前使用過這個MSDN文章中的代碼,它可以爲我有效地工作。 – barryd 2008-09-27 16:42:56

+0

在SharePoint 2010中不起作用 – 2010-03-26 07:26:55

+0

對於Microsoft而言,另一個問題又如何呢?爲什麼這個功能已經不是內置的?爲什麼需要我們自己的封裝類? – 2012-08-14 14:50:21

-1

這並沒有爲我工作,掛了我的webpart始終如一。我讓它工作了一秒鐘,然後沒有。只有當我刪除跟蹤註冊/取消註冊/等聲明它會工作。

因此,我建議這裏面爲我工作的優秀文章: http://sharepoint.namics.com/2008/05/logging_in_webparts.html

從本質上講,你應該使用:

通用基礎架構庫的.NET。

我下載它從這裏: http://netcommon.sourceforge.net/

我用GACUTIL(或控制面板/管理工具/ .NET配置工具),以2.0 /釋放的dll添加到GAC。

我添加引用我的代碼DLL的(從下載)。一切編譯完成

我不得不創建一個目錄和空日誌文件,然後咣!在第一個Web部件加載它的工作。我嘗試了幾個小時來爲我的Web部件進行日誌記錄,並且這個工作非常好,而且它是一個很好的標準,比如log4j。

+0

鏈接已損壞。你能指出什麼不起作用嗎?您可能意味着原始問題的解僱解決方案或MSDN文章由另一個答案建議。 – 2010-08-16 20:59:37

2

的榮譽屬於:http://msdn.microsoft.com/en-us/library/gg512103(v=office.14).aspx
我剛剛發表在我的博客後,但在這裏粘貼代碼。

在代碼中定義您的解決方案的名稱,下面一行:

private const string PRODUCT_NAME = "My Custom Solution"; 

以下是關於如何使用它的示例代碼:

UlsLogging.LogInformation("This is information message"); 
UlsLogging.LogInformation("{0}This is information message","Information:"); 

UlsLogging.LogWarning("This is warning message"); 
UlsLogging.LogWarning("{0}This is warning message", "Warning:"); 

UlsLogging.LogError("This is error message"); 
UlsLogging.LogError("{0}This is error message","Error:"); 

以下是代碼:

using System; 
using System.Collections.Generic; 
using Microsoft.SharePoint.Administration; 
namespace MyLoggingApp 
{ 
    public class UlsLogging : SPDiagnosticsServiceBase 
    { 
     // Product name 
     private const string PRODUCT_NAME = "My Custom Solution"; 

     #region private variables 

     // Current instance 
     private static UlsLogging _current; 

     // area 
     private static SPDiagnosticsArea _area; 

     // category 
     private static SPDiagnosticsCategory _catError; 
     private static SPDiagnosticsCategory _catWarning; 
     private static SPDiagnosticsCategory _catLogging; 

     #endregion 

     private static class CategoryName 
     { 
      public const string Error = "Error"; 
      public const string Warning = "Warning"; 
      public const string Logging = "Logging"; 
     } 

     private static UlsLogging Current 
     { 
      get 
      { 
       if (_current == null) 
       { 
        _current = new UlsLogging(); 
       } 
       return _current; 
      } 
     } 

     // Get Area 
     private static SPDiagnosticsArea Area 
     { 
      get 
      { 
       if (_area == null) 
       { 
        _area = UlsLogging.Current.Areas[PRODUCT_NAME]; 
       } 
       return _area; 
      } 
     } 

     // Get error category 
     private static SPDiagnosticsCategory CategoryError 
     { 
      get 
      { 
       if (_catError == null) 
       { 
        _catError = Area.Categories[CategoryName.Error]; 
       } 
       return _catError; 
      } 
     } 

     // Get warning category 
     private static SPDiagnosticsCategory CategoryWarning 
     { 
      get 
      { 
       if (_catWarning == null) 
       { 
        _catWarning = Area.Categories[CategoryName.Warning]; 
       } 
       return _catWarning; 
      } 
     } 

     // Get logging category 
     private static SPDiagnosticsCategory CategoryLogging 
     { 
      get 
      { 
       if (_catLogging == null) 
       { 
        _catLogging = Area.Categories[CategoryName.Logging]; 
       } 
       return _catLogging; 
      } 
     } 

     private UlsLogging() 
      : base(PRODUCT_NAME, SPFarm.Local) 
     { 
     } 

     protected override IEnumerable<SPDiagnosticsArea> ProvideAreas() 
     { 
      var cat = new List<SPDiagnosticsCategory>{ 
       new SPDiagnosticsCategory(CategoryName.Error, TraceSeverity.High,EventSeverity.Error), 
       new SPDiagnosticsCategory(CategoryName.Warning, TraceSeverity.Medium,EventSeverity.Warning), 
       new SPDiagnosticsCategory(CategoryName.Logging,TraceSeverity.Verbose,EventSeverity.Information) 
      }; 
      var areas = new List<SPDiagnosticsArea>(); 
      areas.Add(new SPDiagnosticsArea(PRODUCT_NAME, cat)); 

      return areas; 
     } 

     // Log Error 
     public static void LogError(string msg) 
     { 
      UlsLogging.Current.WriteTrace(0, CategoryError, TraceSeverity.High, msg); 
     } 
     public static void LogError(string msg,params object[] args) 
     { 
      UlsLogging.Current.WriteTrace(0, CategoryError, TraceSeverity.High, msg,args); 
     } 

     // Log Warning 
     public static void LogWarning(string msg) 
     { 
      UlsLogging.Current.WriteTrace(0, CategoryWarning, TraceSeverity.Medium, msg); 
     } 
     public static void LogWarning(string msg, params object[] args) 
     { 
      UlsLogging.Current.WriteTrace(0, CategoryWarning, TraceSeverity.Medium, msg,args); 
     } 

     // Log Information 
     public static void LogInformation(string msg) 
     { 
      UlsLogging.Current.WriteTrace(0, CategoryLogging, TraceSeverity.Verbose, msg); 
     } 
     public static void LogInformation(string msg,params object[] args) 
     { 
      UlsLogging.Current.WriteTrace(0, CategoryLogging, TraceSeverity.Verbose, msg,args); 
     } 

    } 
} 
1

以下代碼: (增加這一參考數據: usi ng Microsoft.SharePoint.Administration;)

try 
     { 

      SPSecurity.RunWithElevatedPrivileges(delegate() 
      { 
       SPDiagnosticsService diagSvc = SPDiagnosticsService.Local; 
       diagSvc.WriteTrace(123456, new SPDiagnosticsCategory("Category_Name_Here", TraceSeverity.Monitorable, EventSeverity.Error), TraceSeverity.Monitorable, "{0}:{1}", new object[] { "Method_Name", "Error_Message"}); 
      }); 
     } 
     catch (Exception ex) 
     { 
     } 

現在打開uls查看器並按類別名稱篩選。