User Tools

Site Tools


Writing /var/lib/dokuwiki/data/meta/tutorials/python_development_standards.meta failed
tutorials:python_development_standards

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tutorials:python_development_standards [2019/06/17 04:09] – [Tools] Explain logging levels dgarciatutorials:python_development_standards [2022/09/20 00:08] (current) – external edit 127.0.0.1
Line 47: Line 47:
 ==== Logging ==== ==== Logging ====
  
-Logging is a very important part of every software project, because it is the best way to deliver valuable information to our users. Logs are used to report errors, warnings, or just general information of how the program is executing. Good logs help us to discover why the program fails some times, they help us diagnose problems with our programs and help us plan strategies for improvement. It is crucial to maintain good and healthy logging practices so that you can increase the maintainability of your code.+Logging is a very important part of every software project, because it is the best way to deliver valuable information to our users. Logs are used to report errors, warnings, or just general information of how the program is executing. Good logs help us to discover why the program fails some times, they help us diagnose problems with our programs and help us plan strategies for improvement. It is crucial to maintain good and healthy logging practices so that you can increase the maintainability of your code.
  
-Python developers, knowing that logs are so important, have developed a module just for this: the [[https://docs.python.org/3.7/library/logging.html|Logging]] module. There are 5 default levels of logging, ordered from most important to less important are: ''CRITICAL'', ''Error'', ''Warning'', ''Info'', ''Debug''.+Python developers, knowing that logs are so important, have developed a module just for this: the [[https://docs.python.org/3.7/library/logging.html|Logging]] module. It is very important that we use this tool and **Not plain prints**. Also, take into consideration that logging helpers are going to be removed from ''arcospyu'' very soon. There are 5 default levels of logging, ordered from most important to less important are: ''CRITICAL'', ''Error'', ''Warning'', ''Info'', ''Debug''.
  
 === Logging levels === === Logging levels ===
Line 67: Line 67:
 === Loggers === === Loggers ===
  
 +In Python, the [[https://docs.python.org/3.7/library/logging.html#logging.Logger|logger]] is the object in charge of handling your logs. This are the objects that you as a programmer will use to create the logs. In order to get a logger you just have to call the module level function [[https://docs.python.org/3.7/library/logging.html#logging.getLogger|getLogger()]]. This function will return a logger object that you can use. Loggers have the ''setLevel'' method. This method sets the level of your logger as explained above. Then you have the ''debug'', ''info'', ''warning'', ''error'', and ''critical'' methods which create a message of their respective level. Note that if you set the ''Warning'' level, and create a ''Debug'' message, it won't be shown to the user. That is exactly the idea of defining these levels.
  
 +The following is an example,
  
 +<code python>
 +# myapp.py
 +import logging
 +import math
 +
 +def main():
 +    # Instead of printing the message send it to a file named 'filename'
 +    # Set the INFO level
 +    logging.basicConfig(filename="myapp.log", level=logging.INFO)
 +    
 +    # log some info
 +    logging.info("Started")
 +    total = 0
 +    for number in range(-2, 100):
 +        logging.debug(number)
 +        try:
 +            math.sqrt(number)
 +        except ValueError:
 +            # report that there was an error, but we handled it.
 +            logging.warning("Recovering from a negative sqrt")
 +            number = 0
 +       
 +        total += number
 +       
 +    if total < 0:
 +        # If after adding possive numbers you got a negative, then there is something really wrong
 +        logging.error("Negative sum of positive numbers")
 +        raise ValueError
 +    
 +    # If everything went OK, report it
 +    logging.info('Finished')
 +
 +if __name__ == '__main__':
 +    main()
 +</code>
 +
 +
 +=== Colors ===
 +
 +It is also possible to add colors to your logs. For that we need to deal with a [[https://docs.python.org/3.7/library/logging.html#handler-objects| Handler]] which is the object in charge of sending your logs to the apropiate destination. The default is to send them to the standard output, but you can also send them to a log file as we did in the example above. 
 +
 +If you want to add colors to your logs you will need a package named `colorlog`. You can install it from PyPi with:
 +
 +<code bash>
 +pip install colorlog
 +</code>
 +
 +If you do not want to use ''pip'', there are also [[https://packages.debian.org/jessie/python-colorlog| Debian]], [[https://launchpad.net/python-colorlog| Ubuntu]], and [[https://aur.archlinux.org/packages/python-colorlog/| AUR]] packages. For example for Debian, you can install with:
 +
 +<code bash>
 +sudo apt install python-colorlog python3-colorlog
 +</code>
 +
 +Here you have an example of how to use `colorlog`:
 +
 +<code python>
 +import colorlog
 +
 +# create the format object with colors.
 +formatter = colorlog.ColoredFormatter(
 + "%(asctime)s%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
 + datefmt=None,
 + reset=True,
 + log_colors={
 + 'DEBUG':    'cyan',
 + 'INFO':     'green',
 + 'WARNING':  'yellow',
 + 'ERROR':    'red',
 + 'CRITICAL': 'red,bg_white',
 + },
 + secondary_log_colors={},
 + style='%'
 +)
 +
 +# Create the handler
 +handler = colorlog.StreamHandler()
 +# Add the formatter we created earlier
 +handler.setFormatter(formatter)
 +
 +# Get a logger called "example". (It is created if it doesn't exist)
 +logger = colorlog.getLogger("example")
 +# Add the colored formatter to the logger we just created
 +logger.addHandler(handler)
 +
 +logger.error("This is an error")
 +logger.warning("This is a warning")
 +logger.info("This is an info (that you will not see)")
 +logger.debug("This a debug (that you will not see)")
 +</code>
 ===== Project Layout ===== ===== Project Layout =====
 The recommended project layout for a python projected named <code>ptoject_name</code> is as follows: The recommended project layout for a python projected named <code>ptoject_name</code> is as follows:
tutorials/python_development_standards.1560744556.txt.gz · Last modified: 2022/09/20 00:08 (external edit)