How to log and trace exceptions for .net application

322 views Asked by At

I am tasked with logging and tracing exceptions in a .net application. The purpose is to have all data logged once the application is deployed. And information should be easily traceable to handle bugs. We are using azure services. To make the problem statement more clear here is little demo code

public bool Connect()
{
        try
        {
            while (!IsConnected())
            {
                _terminal = new TerminalClient("denaliTermClient", _terminalsrv_host, _terminalsrv_port);
                if (_terminal.KillTerminals())
                {
                    _logger.Log("Existing terminals killed successfully");
                }
                else
                {
                    _logger.Log("Failed killing existing terminals");
                }

                _connection.Connect(
                _terminalsrv_host,
                _terminalsrv_port,
                _broker,
                _account,
                _password);
                }
                return true;
            }
         catch (Exception ex)
         {
             long cid = DefaultLogger.CorrelationID;
             _logger.Log(cid, ex);
             if (ex.Message != null)
             {
                 if (ex.Message.Contains("No connection could be made because the target machine actively refused it"))
                 {
                    _logger.Log(cid, "Connection Failed. Please start the Nj4x Terminal Server.");
                 }
                 else if (ex.Message.Contains("Invalid user name or password"))

                 {
                    _logger.Log(cid, "Nj4x is running in trial mode. Cannot start trading.");
                 }
              }
              this.Connect();    // TODO !
         }

            return false;
}

Now how should I implement this ILogger interface. What services should I use? I have no experience in it so obviously I am not well informed about it. Hope I have made problem statement clear.

Edit: I don't like the idea of logging in a .txt file. That will contain thousands of logs, so it won't be easily traceable. I am looking for some nice framework that helps in tractability as well.

1

There are 1 answers

0
Sergy93 On

If you are using Azure Services I believe Application Insights is your way to go.

Without a lot of configuration it automatically detects your uncaught exceptions and logs them, among a lot of other things. You can add your own traces too.

Here you have a nice article written in the MSDN explaining the full process.

Hope it helps!