Log console output in .NET Core Azure cloud service

When developing an Azure Cloud Service that receives messages from an IoT device using NB-IoT, DTLS and CoAP, there was some trouble with timeouts.
To properly troubleshoot the problems, I needed more information. The DTLS.Net library logs exceptions and some other useful data to the Console, using Console.WriteLine().

However, .NET Core Azure Cloud Services have the Console connected to Stream.Null by default, which means all that useful information goes to nowhere.

Thanks to this Stackoverflow post, I was able to redirect the console output to a System.Diagnostics.Trace and to a custom logger, making the DTLS log output visible through Azure Cloud Service diagnostics.

This was added to the OnStart() method

var outWriter = new LogWriter("Out", this);
var errorWriter = new LogWriter("Error", this);
Console.SetOut(outWriter);
Console.SetError(errorWriter);
Console.WriteLine("Console redirected");
Trace.TraceInformation("Trace: Console redirected");

This is the logging class:

public class LogWriter : TextWriter
{
    private string prefix;
    private WorkerRole parent;

    public LogWriter(string prefix, WorkerRole parent)
    {
        this.prefix = prefix;
        this.parent = parent;
    }

    public override void WriteLine(string message)
    {
        parent.LogText($"{prefix}:\t{message}");
    }

    public override Encoding Encoding
    {
        get { return Encoding.Default; }
    }
}

I hope this helps someone else in case you try debugging console on Azure Cloud Services.

Leave a Reply

Your email address will not be published. Required fields are marked *