Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect if I'm running in the console

Is there a simple way to have a code library automatically detect if it's being called from a console application or a windows application? I'd like my library not to report to the Windows Event log if it's being called from a console window, but instead report to the console window. If however, it's not being run from within a console window, it should report to the Windows Event Log.

I thought about requiring my the logging component to be passed the log target, but it would be neat if it could just automatically handle these two targets natively. I don't yet require something as extensive as log4net, indeed, if it becomes necessary to provide support to log to a database/file and other as yet unknown logging targets, then I may recommend such a solution. For now though, just having my component auto-detect the environment and log to the console or the event log according to the environment would be plenty.

like image 548
BenAlabaster Avatar asked Apr 13 '09 17:04

BenAlabaster


2 Answers

Just discovered that "Console.Title" will be a blank string in a windows application and it will be automatically set in a console application.

Still a hack though.

like image 63
Fozzedout Avatar answered Oct 22 '22 13:10

Fozzedout


Architecturally, passing the logging context into the library component is the right choice. The library doesn't, and indeed shouldn't, know that much context about the environment it's being run in.

Because you want to support these two special cases natively within the library, I'd suggest a unified approach.

  1. Go ahead and create the more generalized logging entry point/knob that the caller controls.
  2. Create a separate entry point/knob that automatically sets the generalized one for the cases that you want to automatically support.

Even that seems too complicated based on your description, though. Have you considered simply using appropriate TraceListeners in your Diagnostics collection, where your console app adds the appropriate TraceListener to output to the console and the non-console app adds the appropriate EventLog TraceListener to output to the Windows event log? This has the added advantage of working well with all the built-in .net logging support without assuming any external dependencies (e.g., log4net).

like image 34
Greg D Avatar answered Oct 22 '22 13:10

Greg D