Internet Sellout

Demand Unearned Rewards

ASP.NET Write to Windows Event Logs

I like applications to write to the Windows Event Logs unless they are going to be verbose. Windows Event Logs can be collected and forwarded with a variety of tools for continuous monitoring. Sometimes logging errors is going to be way to noisy and an alternative is needed. But it is a good idea to write at least some things to the Windows Event Logs. .NET has a framework for the config files that can be used so that if you need to change the logging behavior it is somewhat configurable as opposed to a code change. The basic way to write is this System.Diagnostics http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.110).aspx technique. But App.config and web.config can have something like:

  <system.diagnostics>
    <sources>
      <source name="DefaultSource" switchName="DefaultSwitch">
        <listeners>
          <add name="EventLog"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="DefaultSwitch" value="Information"/>
    </switches>
    <sharedListeners>
      <add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="MyLogs"/>
    </sharedListeners>
    <trace autoflush="true" indentsize="4"></trace>
  </system.diagnostics>

 

 in this example, MyLogs is the event source. Not all users, especially weak web app pool users can create an event source and you need one before you can write. If it is a windows app, maybe you can do that in the app code or maybe you can push it with group policy. If it is a web server then maybe just running this command:

eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO MyLogs /D "MyLogs Event Source exists now if it didn't before."

This will create the Event Source.

Now in ASP.NET VB.NET, this works: 

        Try
            My.Log.WriteException(exCurrentException, Diagnostics.TraceEventType.Warning, System.Configuration.ConfigurationManager.AppSettings("ApplicationName"))
        Catch
        End Try

Or for a Windows application 

        Try
            My.Application.Log.WriteException(exCurrentException, Diagnostics.TraceEventType.Warning, System.Configuration.ConfigurationManager.AppSettings("ApplicationName"))
        Catch
        End Try

 It is not clear to me if a C# developer needs to use the Microsoft.VisualBasic namespace and assembly or if these settings in the config files mean anything for anything out of this namespace.

Comments are closed