Skip to content

Instantly share code, notes, and snippets.

@KerryRitter
Created October 29, 2015 17:15
Show Gist options
  • Save KerryRitter/7bf65023a3dc6122f981 to your computer and use it in GitHub Desktop.
Save KerryRitter/7bf65023a3dc6122f981 to your computer and use it in GitHub Desktop.
Listens to the event log to detect when app pool recycle events are triggered (IIS must be configured to write these to the logs)
using System;
using System.Diagnostics;
using System.Net;
namespace EventLogListener
{
class Program
{
static void Main(string[] args)
{
var listener = new ApplicationPoolRecycleListener("StreamingServer")
{
OnTargetApplicationRecycled = (entry, recycleReason) =>
{
// do something
return true;
},
OnNonTargetApplicationRecycled = (entry, recycleReason) =>
{
// do something
return true;
}
};
listener.StartListening();
}
}
public class ApplicationPoolRecycleListener
{
public enum RecycleReason
{
IisReset = 3202,
ReachedProcessingTimeLimit = 5074,
ReachedAllowedRequestLimit = 5075,
ReachedScheduledRecycleTime = 5076,
ReachedVirtualMemoryLimit = 5077,
ReachedPrivateBytesMemoryLimit = 5117,
AdministratorRequest = 5079,
AppPoolConfigurationChange = 5080,
IisConfigurationError = 5081
}
private readonly string _targetApplicationPoolName;
private bool _stopListening;
public Func<EntryWrittenEventArgs, RecycleReason, bool> OnTargetApplicationRecycled { get; set; }
public Func<EntryWrittenEventArgs, RecycleReason, bool> OnNonTargetApplicationRecycled { get; set; }
public ApplicationPoolRecycleListener(string targetApplicationPoolName)
{
_targetApplicationPoolName = targetApplicationPoolName;
_stopListening = false;
}
public void StartListening()
{
var eventLog = new EventLog { Log = "System", EnableRaisingEvents = true };
eventLog.EntryWritten += EventWrittenCallback;
var eventLog2 = new EventLog { Log = "Application", EnableRaisingEvents = true };
eventLog2.EntryWritten += EventWrittenCallback;
while (_stopListening == false) { }
}
private void EventWrittenCallback(object sender, EntryWrittenEventArgs e)
{
var eventId = e.Entry.EventID;
if (Enum.IsDefined(typeof (RecycleReason), eventId))
{
var recycleReason = (RecycleReason)eventId;
if (recycleReason == RecycleReason.IisReset)
{
_stopListening = OnTargetApplicationRecycled?.Invoke(e, recycleReason) ?? false;
}
else
{
if (e.Entry.Message.ToLower().Contains($"serving application pool '{_targetApplicationPoolName.ToLower()}'"))
{
_stopListening = OnTargetApplicationRecycled?.Invoke(e, recycleReason) ?? false;
}
else
{
_stopListening = OnNonTargetApplicationRecycled?.Invoke(e, recycleReason) ?? false;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment