Search code examples
c#node.jsstdinspawntracelistener

Listening to ConsoleTraceListener logs from Node


I have written sample application which prints the logs to ConsoleTraceListener.

According to MSDN, the ConsoleTraceListener should redirect to standard output. I spawn this process from node and trying to listen to stdout and it's unable to get the information.

Any idea how to fix this? I want to stream TraceListener to node

C#:

Trace.Listeners.Add(new ConsoleTraceListener(true));
Trace.AutoFlush = true;
Console.WriteLine("This comes out");
Trace.WriteLine("oops");
Trace.TraceInformation("Getting lost");
Thread.Sleep(5000);
Console.WriteLine("Stopping comes out");

Node:

let proc = ps.spawn("sample.exe");
proc.stdout.on('data', (c) => {
    console.log(c.toString());
});

proc.stderr.on('err', (c) => {
    console.log(c.toString());
});

Solution

  • First, you redirect to stderr, not stdout, because of parameter you pass to ConsoleTraceListener:

    Trace.Listeners.Add(new ConsoleTraceListener(useErrorStream: true));// < note true here
    

    To redirect to stdout - change that to false:

    Trace.Listeners.Add(new ConsoleTraceListener(useErrorStream: false));
    

    Then you will see the output in your node.js app. If you want to see stderr, change your node.js app like this:

    proc.stderr.on('data', (c) => {
        console.log(c.toString());
    });
    

    Then you will see output even with your original .NET application which writes to stderr.

    If the above does not help - check if you define TRACE compile-time constant (project properties > checkbox "Define TRACE constant").