Logging

    Logging serves two purposes:

    • Audit logging records events for business analysis. A user’stransactions can be extracted and combined with other user details forreports or to optimize a business goal.

    The only time that print is a better option than logging is whenthe goal is to display a help statement for a command line application.Other reasons why logging is better than print:

    • The log record, which is created with every logging event, containsreadily available diagnostic information such as the file name, full path,function, and line number of the logging event.
    • Events logged in included modules are automatically accessible via the rootlogger to your application’s logging stream, unless you filter them out.
    • Logging can be selectively silenced by using the method or disabled by setting the attribute to True.

    Notes for configuring logging for a library are in the. Because the user, not the library, shoulddictate what happens when a logging event occurs, one admonition bearsrepeating:

    It is strongly advised that you do not add any handlers other thanNullHandler to your library’s loggers.

    Best practice when instantiating loggers in a library is to only create themusing the name global variable: the logging module creates ahierarchy of loggers using dot notation, so using ensuresno name collisions.

    Here is an example of best practice from the – placethis in your init.py:

    There are at least three ways to configure a logger:

    • Using an INI-formatted file:
      • Pro: possible to update configuration while running using thefunction logging.config.listen() to listen on a socket.
    • Using a dictionary or a JSON-formatted file:
      • Pro: in addition to updating while running, it is possible to loadfrom a file using the module, in the standard library sincePython 2.6.
      • Con: less control than when configuring a logger in code.
    • Using code:
      • Pro: complete control over the configuration.
      • Con: modifications require a change to source code.

    Let us say the file is named .More details for the file format are in the logging configurationsection of the .

    Then use logging.config.fileConfig() in the code: