[英]Redirect stdout+stderr on a C# Windows service
I've written a Windows service in C# using the ServiceBase
helper.我已经使用
ServiceBase
帮助程序在 C# 中编写了一个 Windows 服务。 During its execution, some procedures in an external native DLL are called.在其执行过程中,会调用外部本机 DLL 中的某些过程。 Annoyingly, those procedures write to stdout and/or stderr in an uncontrolled manner as no sources are given for this DLL.
令人讨厌的是,这些过程以不受控制的方式写入 stdout 和/或 stderr,因为没有为此 DLL 提供源。
Is it possible to redirect those outputs from the C# service to a log file?是否可以将这些输出从 C# 服务重定向到日志文件?
You can do this via PInvoke to SetStdHandle :您可以通过 PInvoke 到SetStdHandle执行此 操作:
[DllImport("Kernel32.dll", SetLastError = true) ]
public static extern int SetStdHandle(int device, IntPtr handle);
// in your service, dispose on shutdown..
FileStream filestream;
StreamWriter streamwriter;
void Redirect()
{
int status;
IntPtr handle;
filestream = new FileStream("logfile.txt", FileMode.Create);
streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
handle = filestream.Handle;
status = SetStdHandle(-11, handle); // set stdout
// Check status as needed
status = SetStdHandle(-12, handle); // set stderr
// Check status as needed
}
Check out the Console.SetOut method.查看Console.SetOut方法。
It will allow you to redirect console output to a TextWriter.它将允许您将控制台输出重定向到 TextWriter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.