Reputation: 15
I am here with 2 proposals.. I have a windows application running. First proposal is that I should have the messages written directly to a console(command prompt),even though it is not a console application.
Second option is that I should create a console application in which it should read the log file produced by the windows application and write the same to the console. Please note the windows application will be updating the log file in real time while it is running and I want the console app to read each and every updated messages in log at the very next moment itself..Is it possible??
Which will be feasible?? and how I can achieve that?
Fast responses are really appreciated.. Thanks...
Upvotes: 0
Views: 751
Reputation: 236188
And third approach - use inter process communication to listen winforms application events from console application. For example, you can use .NET Remoting, WCF, or MSMQ.
Thus you need to write log from your windows forms application, and receive same data in your console application, then you can take advantage of NLog logging framework, which can write logs both to files and MSMQ. Get NLog.dll and NLog.Extended.dll from Nuget.0 Configure two targets in NLog.config file:
<?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>
Then obtain logger in your winforms application
private static Logger _logger = LogManager.GetCurrentClassLogger();
And use it to write log messages:
private void button1_Click(object sender, EventArgs e)
{
_logger.Debug("Click");
}
Now move to console application. You need to read messages from MSMQ queue, which are published by winforms application. Create queue and start listening:
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();
Write messages to console when they are received:
static void ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
Console.WriteLine(e.Message.message.Body);
var queue = (MessageQueue)sender;
queue.BeginReceive();
}
If you want to use Remoting, take a look on Building a Basic .NET Remoting Application article.
Upvotes: 1