Console.WriteLine() inside a Windows Service?

流过昼夜 提交于 2019-11-29 02:51:11
dtech

The output will simply be discarded.

In a Windows Service there is no Console so Console.Write* output is discarded. There are a number of alternatives:

  1. The System.Diagnostics.Trace class has a similar interface to the Console class so you could migrate your code quite easily to this.
  2. It can then be configured to output to a file. You can use the System.Diagnostics.EventLog class to write to the Event Log which you can then monitor using Event Viewer.
  3. You can use the third-party open-source log4net library which is very flexible.

No, the console class will safely write to the STDOUT, but you will just not see the output.

If you use the System.Diagnostics.Trace functionality, you can redirect the output using the listeners and switches. If you compile with the TRACE symbol, then code will be included. If you don't add the TRACE, then it won't be compiled into the project.

If you run your services as console for debugging, the Trace will output to the console by default. I've taken to using Trace instead of Debug or Console writes since I can, from the config file, output the trace information to any combination of files, screen, database, etc.

The output was always discarded until Windows Server 2008R2. Leave a console.writeline() in a service installed on that OS, and you'll get an error 1067 when starting/running the service, depending on the position of the writeline().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!