2010-07-09 78 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