Home News What’s the easiest way to log C # errors and the right...

What’s the easiest way to log C # errors and the right way to repair it?



The next information will make it easier to when you’ve got a C # error logging greatest observe.



On the earth of software program growth, logging usually takes a again seat to unit testing and documentation. Nevertheless, logging is a strong debugging device in a manufacturing surroundings that gives necessary knowledge concerning the precise utilization of your software. When one thing stops working, it is knowledge within the logs that the developer and operations workforce use to rapidly troubleshoot and resolve the problem.

In fact, newspapers are necessary. Sadly, not all protocols are the identical. Finest practices ought to be adopted of their creation in order that they include the right data when crucial. This text introduces seven greatest practices you need to use to take C # logging to the following degree.

Q: What Frames Do You Use?

A: System.Diagnostics.TraceSource built-in into .NET 2.0.

It offers highly effective, versatile and highly effective logging for purposes. Nevertheless, many builders aren’t conversant in its capabilities and don’t use them to the fullest.

Extra capabilities in some areas helpful or generally current however poorly documented. Nevertheless, this doesn’t imply that the complete logging framework (which is meant to be extensible) ought to be deserted and utterly changed with some common options (NLog, log4net, Widespread.Logging and even EntLib Logging).

Relatively than altering the way in which you add logging directions to your software and reinventing the wheel, you have solely developed the System.Diagnostics framework within the few locations you want it.

It appears to me that different frameworks, even EntLib, are simply affected by Not Invented Right here Syndrome, and I feel they wasted their time inventing the fundamentals that already work nice in System.Diagnostics (like the right way to write a protocol) as an alternative of filling within the few current gaps. Briefly, do not use them – they aren’t wanted.

Options You Might Not Know About:

  • Utilizing TraceEvent overloads that take a format string and arguments can enhance efficiency as a result of parameters are saved as separate references till Filter.ShouldTrace () succeeds. This implies there are not any pricey calls v ToString () for parameter values ​​till the system affirmation message is definitely logged.
  • With Hint.CorrelationManager, you possibly can affiliate protocol directions with the identical logical operation (see beneath).
  • VisualBasic.Logging.FileLogTraceListener is appropriate for writing to log recordsdata and helps file rotation. Though it is within the VisualBasic namespace, it will possibly simply as simply be utilized in a C # venture (or every other language venture) by merely together with the DLL.
  • When utilizing EventLogTraceListener and calling TraceEvent with a number of arguments and an empty string or empty string, the arguments are handed on to EventLog.WriteEntry () when utilizing localized message sources.
  • The Service Hint Viewer (from WCF) is beneficial for viewing graphs of activity-related log recordsdata (even if you’re not utilizing WCF). It may well actually assist with tough multi-thread / exercise issues.
  • Keep away from overloading by eradicating all listeners (or eradicating defaults). In any other case, Default laneeats every thing into the hint system (and incurs all that ToString () overhead).
  • Areas you would possibly wish to develop (if wanted):

    • Database Hint Listener
    • Full colour console hint listener
  • MSMQ / E-mail / WMI Hint Listener (optionally available)
  • Implement FileSystemWatcher to name Hint.Refresh for dynamic configuration adjustments.
  • Different suggestions:

    Use structured occasion IDs and keep an inventory of hyperlinks (for instance, doc them in a bulleted listing).

    It is rather helpful to have distinctive occasion IDs for every (important) occasion in your system as a way to correlate and discover particular issues. It’s simple to return to the precise code that registers / makes use of occasion IDs and it may be simple to offer steering for widespread errors reminiscent of: Error 5178 means your database connection string is improper, and so on.

    Occasion identifiers will need to have a sure construction (much like the idea of code from The online utilized in electronic mail and HTTP), which lets you classify them with out realizing the precise codes.

    eg. The primary digit can describe the final class intimately: 1xxx can be utilized for “ begin ” operations, 2xxx for regular habits, 3xxx for exercise monitoring, 4xxx for warnings, 5xxx for errors, 8xxx for cease operations, 9xxx for critical errors and so on.

    The second digit could point out an space, for instance 21xx for database data (41xx for database warnings, 51xx for database errors), 22xx for calculation mode (42xx for calculation warning, and so on.), 23xx for one more module, and so on.

    Assigned structured occasion IDs let you use them in filters.

    Use Exception Throwing Strategies

    A category often throws the identical exception somewhere else in its implementation. Use helper strategies that throw and throw an exception to keep away from pointless code. For instance:

    c# error logging best practice

      FileReader reference class{Personal:    String ^ fileName;Publicity:    FileReader (String ^ Path)    {File identify = path;    }}    Array  ^ learn (int bytes)    {        array  ^ outcomes = FileUtils :: ReadFromFile (file identify, bytes);        if (outcomes == nullptr)        {            throw NewFileIOException ();        }}        Return outcomes;    }}    FileReaderException ^ NewFileIOException ()    {        String ^ description = "Description of My NewFileIOException";        return gcnew FileReaderException (description);    }}}; 
      FileReader Class{    personal string fileName;    public FileReader (string path)    {        File identify = path;    }}    public byte [] learn (complete bytes)    {        byte [] outcomes = FileUtils.ReadFromFile (file identify, bytes);        if (outcomes == null)        {            throw NewFileIOException ();        }}        Return outcomes;    }}    FileReaderException NewFileIOException ()    {        string description = "Description of My NewFileIOException";        returns a brand new FileReaderException (description);    }}}} 
      FileReader class    Personal filename as string    Public Sub New (path as string)        File identify = path    Finish of subscription    Studying public service (bytes as integers) as bytes ()        Darken the outcomes () as Byte = FileUtils.ReadFromFile (filename, bytes)        When the outcomes are nothing            Throw NewFileIOException ()        Tono, if        Return outcomes    Finish operate    NewFileIOException () operate reminiscent of FileReaderException        Dim Description As String = "My NewFileIOException Description"        Throw a brand new FileReaderException (Description)    Finish functionEnd after all 

    In some circumstances, it’s higher to make use of the exception constructor to throw an exception. An instance is a worldwide exception class reminiscent of ArgumentException .

    Restoration Standing If Strategies Fail Due To Exceptions

    Callers must make certain that there are not any unintended effects if an exception is thrown from a technique. For instance, when you’ve got a code that transfers cash by withdrawing from one account and depositing to a different account, and an exception happens throughout the deposit, you do not need the withdrawal to stay. performing.

      public void TransferFunds (account from, account to, decimal quantity){    de. Withdrawal (quantity);    // If the deposit failed, the withdrawal shouldn't stay legitimate.    Deposit quantity);}} 
      Public Sub TransferFunds (from As Account, [to] As Account, Quantity as Decimal)    from. withdrawal (quantity)    If the deposit will not be requestedate, the evaluation is not going to stay legitimate.    [in]. Deposit quantity)Finish of subscription 

    The above methodology doesn’t instantly throw any exceptions, it have to be written in order that the withdrawal is canceled if the deposit course of fails.

    One solution to cope with this example is to catch any exceptions thrown by the deposit transaction and reset the withdrawal.

      Personal Static Invalid TransferFunds (account from, account to, decimal quantity){    String ExtractionTrxID = from.Withdrawal (Quantity);    Attempt    {        Deposit quantity);    }}    Seize    {        from.RollbackTransaction (inferredTrxID);        throw it away;    }}}} 
      Personal Shared Extra TransferFunds (from account [to] as account, quantity in decimal)    Withdraw funds as a string = from. Withdrawal (quantity)    Attempt        [in]. Deposit quantity)    Seize        from.RollbackTransaction (RetractionTrxID)        Throw away    Finish attemptEnd of subscription 

    This instance exhibits the usage of throw to rethrow the unique exception, which may make issues simpler for callers.