C# 如何指导EventLogTraceListener在特定日志中创建

C# 如何指导EventLogTraceListener在特定日志中创建,c#,.net,config,event-log,listeners,C#,.net,Config,Event Log,Listeners,调用Trace.WriteLine时,以下侦听器将创建一个事件条目。如果源不存在,他将在默认日志通道“应用程序”中创建它。我想指定另一个默认日志通道,但在搜索45分钟后,我似乎没有找到解决方案。有什么想法吗 <configuration> <system.diagnostics> <trace autoflush="false" indentsize="4"> <listeners> <add n

调用Trace.WriteLine时,以下侦听器将创建一个事件条目。如果源不存在,他将在默认日志通道“应用程序”中创建它。我想指定另一个默认日志通道,但在搜索45分钟后,我似乎没有找到解决方案。有什么想法吗

<configuration>   
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="myListener"               
          type="System.Diagnostics.EventLogTraceListener"
          initializeData="Source">          
        </add>
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

不确定是否可以通过配置

尽管EventLogTraceListener在构造函数中接受不同的eventlog作为参数。不幸的是,该类是密封的,因此不能简单地从中派生并为构造函数传递不同的值

尽管您可以按照这种方法构造自己的类(看起来相当简单)。然后在配置中引用该类型。

你可以在这篇博文中找到解决方案:


它真的有效

您可以在第一行代码中重新指向侦听器

Trace.Listeners["MyListener"].Attributes["EventLog"] = ConfigurationManager.AppSettings["MyCustomEventLogName"];
该值可以存储在配置文件的
部分,因此它仍然是基于配置的:

<appSettings>
    <add key="MyCustomEventLogName" value="CustomEventLogName" />
</appSettings>

我自己刚刚遇到了这个问题,并找到了一个不需要自定义代码的解决方案-您可以通过Powershell事先创建“源代码”,这将允许您设置要使用的日志

  • 通过Powershell初始化源:
  • #以管理员身份运行
    #仅当您以前运行过应用程序且源已与应用程序通道关联时:
    删除事件日志-源MyCustomSource
    #创建新的日志通道源映射
    新建事件日志-LogName CustomLog-Source MyCustomSource
    
  • 如果您使用的“源”与以前登录到“应用程序”的“源”相同,请重新启动计算机-在重新启动之前,更改不会应用

  • 将诊断XML中的“源”与新创建的源匹配


  • 您应该将重要部分放在答题帖中,并添加链接作为参考。
    # Run as administrator
    
    # ONLY If you previously ran the application and the source is already associated with the Application channel:
    Remove-EventLog -Source MyCustomSource
    
    # Create new log channel <-> source mapping
    New-EventLog -LogName CustomLog -Source MyCustomSource