What are the best practices for including logging using log4net?

后端 未结 9 993
夕颜
夕颜 2021-02-07 04:04

I have been told to add “logging” to my code using log4net, the problem is no one can travel in time and see what real world problems the logging will need to be used to solve.<

9条回答
  •  攒了一身酷
    2021-02-07 04:56

    One of the great things about log4net is that you can log events to different categories. The defaults are Debug, Info, Warning and Error. I like these to mean

    Debug - very verbose, contains lots of debugging information. For example, SQL queries.
    Info - useful information that's good to know.
    Warning - nothing fatal but an operator should be aware of the problem.
    Error - the application is now unstable, the log contains diagnostic information such as the exception message and stack trace.

    Use these in code, so e.g.

    _log.Info("Updating object.");

    would write an INFO level message to any listener that was interested.

    Then you can hook up listeners in configuration to do things with the log messages. Here's one that I'm using:

    
    
      
        
      
    
    
      
      
      
      
        
      
    
    
      
      
    
    
      
      
    
    
    

    This says: all ERROR messages to the console, all INFO messages from the logger Warehouse.Core to the given file.

    Because this wiring of categories to listeners is done in configuration, you can alter the logging after deployment. There's virtually no performance penalty to logging if nothing's listening.


    Regarding the costs versus benefits of logging there definitely is a sweet spot between too much logging (huge logs that nobody will use) and not enough (a single line that says "fail").

    My policy is to log at INFO what could fail: external dependencies (application startup, service calls, SQL connections), and at DEBUG the more complex bits of meaty code (diagnostic messages in business logic, individual SQL calls, some method invocations).

    Unusual situations where (for example) defaults are taken that aren't usually would go to WARN, and exceptions go to ERROR or FATAL.

    Also: bear in mind that WCF has a most excellent service trace viewer that allows you to "drill down" to individual packets and how they're processed by both ends of the stack. That, too, is available by configuration without code changes. Because of this I'll generally just do very abbreviated logging of WCF service calls and responses.

提交回复
热议问题