第三种方法 - 使用进程间通信来监听来自控制台应用程序的 winforms 应用程序事件。例如,您可以使用 .NET Remoting、WCF 或 MSMQ。
因此,您需要从 Windows 窗体应用程序写入日志,并在控制台应用程序中接收相同的数据,然后您可以利用 NLog 日志框架,它可以写入日志both to files and MSMQ。从 Nuget.0 获取 NLog.dll 和 NLog.Extended.dll 在 NLog.config 文件中配置两个目标:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target xsi:type="MSMQ" name="msmq" queue=".\private$\CoolQueue"
useXmlEncoding="true" recoverable="true" createQueueIfNotExists="true"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}"/>
<target xsi:type="File" name="file" fileName="logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="msmq" />
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
</nlog>
然后在你的winforms应用程序中获取记录器
private static Logger _logger = LogManager.GetCurrentClassLogger();
并用它来写日志消息:
private void button1_Click(object sender, EventArgs e)
{
_logger.Debug("Click");
}
现在转到控制台应用程序。您需要从 MSMQ 队列中读取消息,这些消息由 winforms 应用程序发布。创建队列并开始监听:
string path = @".\private$\CoolQueue";
MessageQueue queue = MessageQueue.Exists(path) ?
new MessageQueue(path) :
MessageQueue.Create(path);
queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
queue.ReceiveCompleted += ReceiveCompleted;
queue.BeginReceive();
收到消息后将消息写入控制台:
static void ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
Console.WriteLine(e.Message.message.Body);
var queue = (MessageQueue)sender;
queue.BeginReceive();
}
如果您想使用 Remoting,请查看 Building a Basic .NET Remoting Application 文章。