2010-07-09 84 views
1

我已將所有服務邏輯封裝在類庫中。當我在命令行應用程序中實例化類庫時,會收到我的跟蹤信息。.Net Windows服務和自定義跟蹤監聽器

當我在Windows服務中實例化類時,看到我的自定義跟蹤偵聽器已創建日誌目錄並啓動一個文件,但它保持0 KB。

兩個應用程序有這個在.config:

<system.diagnostics> 
<switches> 
    <add name="PTraceSwitch" value="Verbose" /> 
</switches> 
<trace autoflush="true"> 
    <listeners> 
    <add name="CustomXmlWriterTraceListener" /> 
    <add name="MyServiceEventListener" /> 
    <remove name="Default" /> 
    </listeners> 
</trace> 
<sharedListeners> 
    <add 
    type="CustomUtilities.CustomXmlWriterTraceListener, CustomUtilities" 
    name="CustomXmlWriterTraceListener" 
    initializeData="Logs\MyService.svclog" 
    RollLogAtMidnight="True" 
    DateFormat="yyyy.MM.dd" 
    MaxFileSizeMB="1" 
    CompressLogsOlderThanTimeSpan="1.00:0:00" 
    DeleteLogsOlderThanTimeSpan="30.00:00:00"/> 

    <add name="MyServiceEventListener" 
     type="System.Diagnostics.EventLogTraceListener" 
     initializeData="MyServiceEventLog"> 
    <filter type="System.Diagnostics.EventTypeFilter" 
     initializeData="Warning" /> 
    </add> 
</sharedListeners> 

+0

您是否缺少'Trace.Flush()'? – 2010-07-09 22:49:45

+0

你確定'Logs \ MyService.svclog'文件是相對於你的exe創建的嗎?服務通常以'\ Windows'或'\ Windows \ System32'作爲其工作目錄。 – 2010-07-09 22:51:22

+0

@ Rubens Farias,我將它設置爲Autoflush,Flush()似乎沒有幫助 – mittio 2010-07-09 23:36:10

回答

0

看來,當比一個類庫或EXE運行服務我CustomXmlWriterTraceListener表現不同。

我將此添加到我的服務調試的主要切入點,通過我的聽衆的初始化走:

Debugger.Launch(); 

底層作家爲空,當我跑我的服務,通常基中填充構造函數。我使用.NET Reflector來查看XmlWriterTraceListener的功能。有一個內部方法EnsureWriter()。這個方法應該創建Writer。我克隆了微軟的方法並將其添加到我的聽衆中,似乎都沒問題。我的聽衆現在適合一種服務。

internal bool EnsureWriter() 
    { 
     bool flag = true; 
     if (Writer == null) 
     { 
      flag = false; 
      if (baseFileName == null) 
      { 
       return flag; 
      } 
      Encoding encodingWithFallback = new UTF8Encoding(false); 
      string fullPath = Path.GetFullPath(baseFileName); 
      string directoryName = Path.GetDirectoryName(fullPath); 
      string fileName = Path.GetFileName(fullPath); 
      for (int i = 0; i < 2; i++) 
      { 
       try 
       { 
        Writer = new StreamWriter(fullPath, true, encodingWithFallback, 0x1000); 
        flag = true; 
        break; 
       } 
       catch (IOException) 
       { 
        fileName = Guid.NewGuid().ToString() + fileName; 
        fullPath = Path.Combine(directoryName, fileName); 
       } 
       catch (UnauthorizedAccessException) 
       { 
        break; 
       } 
       catch (Exception) 
       { 
        break; 
       } 
      } 
      if (!flag) 
      { 
       baseFileName = null; 
      } 
     } 
     return flag; 
    } 
+0

我不確定我現在寫的東西是否適用於這個問題,但我正在尋找類似問題的解決方案(在初始化後,偵聽器的Writer屬性保持爲null),並且它稍後才從我的帖子開始互聯網),我的服務是從本地服務帳戶運行的,這是一個具有特權限制的帳戶,當然這是禁止寫入我的PC上的所有路徑的。 – 2011-01-31 18:51:21