0

I have written a Windows Service in C#/.NET but so far it does not start yet. An excpetion is thrown in its OnStart method.

As I haven't found any information about the unhandled exception the Windows Event log (except a not very helpful P4: System.Data), I'm looking for another simple way of getting hold of the stack trace and exception message.

I know, I can try and debug the Windows Service but since it fails in the OnStart method which runs under a timeout, debugging is not fun. Also, it requires starting VS as admin.

Or should I wrap everything in a try-catch and log the exception somewhere? And if so, where to? What would be best practice?

Dejan
  • 9,150
  • 8
  • 69
  • 117

1 Answers1

2

Wrap all critical parts of your code in separate try/catch blocks, write your logs to the windows event log, install a global exception handler. Write these exceptions to the windows event log as well.

You should do all this in a service even if it does not crash anyway.

DrKoch
  • 9,556
  • 2
  • 34
  • 43
  • See https://msdn.microsoft.com/en-us/library/f6567h1s(v=vs.110).aspx on how to do that. – Dejan Apr 05 '15 at 14:57
  • Why install a global exception handler *and* using try/catch blocks? I would simply do `AppDomain.CurrentDomain.UnhandledException += ...EventLog.WriteEntry...`. Seems this is enough. – Dejan Apr 05 '15 at 15:50
  • 1
    You want to log as much information about each exception as possible. that's why you have _local_ try/catch blocks where you can add more information about the state of your program. You want to catch Exceptions globally, because there is always a chance to get an exception you did not provide a try/catch block for. Bottom line: Write as much detailed info as possible to the event log. This will minimize the time you need to debug your service and get it running in a stable way. – DrKoch Apr 05 '15 at 17:32
  • Sounds a bit counter http://stackoverflow.com/a/4827646/331281 also because I wouldn't know what information to add to the unhandled exceptions. But I get your point in general. – Dejan Apr 05 '15 at 18:12
  • Well, the main goal is to find the causes why your service crashed **quickly** (Not only today but in the months and years to come). So I'd have two or three try/catch blocks at the **top level** of your service to produce meaningful log entries (as said before) – DrKoch Apr 05 '15 at 18:24
  • I really can't think about what kind of information to add in the catch-clause. The information about where the exception has happened (OnStart, Initialize, ...) is already contained in the StackTrace. What else are you adding as an information to simplifies your debugging? – Dejan Apr 05 '15 at 19:06