How to capture console output from a service C#?

后端 未结 7 1580
无人及你
无人及你 2021-02-07 06:12

We have a C# service that is deployed to a remote customer system. The application writes a substantial amount of \"diagnostic\" information to the console (i.e. Console.WriteL

7条回答
  •  孤街浪徒
    2021-02-07 06:35

    In general, you should avoid writing diagnostic information directly to Console, the Event Log, MSMQ or elsewhere from your application code. Instead call a logging API, and use configuration to redirect the output wherever you want.

    For example, you could replace all the Console.WriteLine by Trace.WriteLine (*). Then you can redirect output to the console, a file or elsewhere by modifying the application configuration file: for example to output to the console, use a ConsoleTraceListener, something like:

    
      
        
          
            
          
        
      
     
    

    While debugging, you'll get your output on the console - on the customer site you'd configure it to redirect the trace output to a file, to the event log or similar.

    Even better, use a 3rd party logging framework (I'd recommend Log4Net) which will give you more options than System.Diagnostics.Trace.

    (*) Trace.Write/Trace.WriteLine are the same as Debug.Write/Debug.WriteLine, except that the latter are only compiled if the DEBUG symbol is defined. So prefer Trace to Debug if you want the output to be available in Release builds.

提交回复
热议问题