Change language

Login to Python

| | |

Logging — it is a means of tracking the events that occur when you launch any software. Logging is essential for developing, debugging, and running software. If you don’t have a log entry and your program crashes, you have very little chance of finding the root cause of the problem. And if you find a reason, it will take a long time. When logging, you can leave a trail of breadcrumbs so that if something goes wrong, we can determine the cause of the problem. 
There are a number of situations, for example, if you are expecting an integer, you got a floating point number and you can use the cloud API, the service is not available for service, and much more. These issues are out of control and difficult to identify.

Why isn’t printing a good option?

Some Developers use the concept of operator printing to check that the operators are executed correctly or some kind of error occurs. But printing is not a good idea. This might solve your problems for simple scripts, but for complex scripts, printing will fail.

Python has a built-in registration module that allows you to write status messages to a file or any other output streams ... The file can contain information about which part of the code is being executed and what problems it encountered.

Log message levels

Yes two built-in log message levels.

  • Debugging: they are used to provide detailed information that is usually only of interest when diagnosing problems.
  • Information: they are used to confirm that everything is working as expected
  • Warning: they are used to indicate that something unexpected has happened, or to indicating a problem in the near future.
  • Error: this indicates that a larger problem caused the software to be unable to perform any function
  • Critical: This indicates a severe error indicating that the program itself cannot continue to run

If necessary Most developers can create more levels, but there are enough of them to solve any possible situation. Each embedded layer has a numeric value assigned to it.

The logging module contains several functions. It has several constants, classes and methods. Elements with all uppercase letters are constant, elements with a capital letter — these are classes, and elements starting with lowercase letters — these are methods. 
There are several logger objects offered by the module itself.

  • Logger.info (msg): this logger will write a message with the INFO level.
  • Logger.warning (msg): this logger will write a message with the WARNING level.
  • Logger.error (msg): this log will write a message with an ERROR level.
  • Logger.critical (msg): this log will log a message with a CRITICAL level.
  • Logger.log (lvl, msg): this log logs a message with an integer lvl level .
  • Logger.exception (msg): this will log a message with an ERROR level on this logger.
  • Logger.setLevel (lvl): this function sets the threshold of this logger to lvl. This means that all messages below this level will be ignored.
  • Logger.addFilter (filter): this adds a specific filter filter to this logger.
  • Logger.removeFilter (filter): removes a specific filter filter for this logger.
  • Logger.filter (record): this method applies a logger filter to the provided record and returns True if the record is to be processed. Otherwise, it will return False.
  • Logger.addHandler (hdlr): this adds a specific hdlr handler to this logger.
  • Logger.removeHandler ( hdlr): removes a specific hdlr handler for this logger.
  • Logger.hasHandlers (): checks if any handler is configured in the logger or not.

Basics

The basics of using the logger to write events to a file are very simple. 
To do this, simply import the module from the library.

  1. Create and configure a logger. It can have several parameters. But it is important to pass the name of the file to which you want to log events.
  2. The format of the logger can also be set here. By default, the file runs in append mode, but we can change it to write mode if needed.
  3. In addition, the log level can be set, which acts as a threshold for tracking based on numerical values ​​assigned to each level. 
    There are several attributes that can be passed as parameters.
  4. For a list of all of these parameters, see Python library . User can select the desired attribute according to the requirement.

    Then create the object and use different methods as shown in the example.

    # importing module

    import logging

      
    # Creating and configuring a logger

    logging.basicConfig (filename = "newfile.log" ,

    format = ’% ( asctime) s% (message) s’ ,

    filemode =  ’w’ )

      
    # Create an object

    logger = logging.getLogger ()

     
    # Setting the logger threshold in DEBUG
    logger.setLevel (logging.DEBUG)

     
    # Test messages

    logger.debug ( "Harmless debug Message" )

    logger.info ( "Just an information " )

    logger.warning ( "Its a Warning" )

    logger.error ( "Did you try t o divide by zero " )

    logger.critical ( " Internet is down " )

    The above code will generate a file with the specified name, and if we open the file, the file will contain the following data. 

    This article courtesy of Rishabh Bansal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically