2018-06-27-python full stack development day23-logging, Configparser, Hashlib module

Source: Internet
Author: User

1.logging Module

The logging module is the log module used to record the state of the program's operation.

There are five levels:

    • Debug
    • Info
    • Warning
    • Error
    • Critical

 

Logging.debug ('Debug Message') #logging. info ('Info Message') logging.warning ('warn message') #表明发生了一些意外, or problems will occur in the near future (such as ' Disk full '). The software is still working properly. Logging.error ('error Message') #由于更严重的问题, the software is no longer capable of performing some functions. Logging.critical ('Critical Message') #严重错误 that the software cannot continue running.

Used to output the log content, it can be customized to the log content according to their own needs
WARNING:root:warn messageERROR:root:error messageCRITICAL:root:critical message# in the process of output, root is the user currently in use

1.1 Adjusting Display parameters

Parameter name Description filename Specifies the file name of the log output destination file, and the log confidence is not output to the console after you specify the setting item FileMode the open mode of the specified log file, which defaults to'a'. It is important to note that this option is valid when the filename is specified, format specifies the log format string, which specifies the field information that is included in the log output and the order in which they are made. The format fields defined by the logging module are listed below. Datefmt Specified date/Time format. It is important to note that the option to include the Time field% in format(Asctime) s is only valid level specifies the log levels of the logger stream, which specifies the log output target stream, such as Sys.stdout, Sys.stderr, and network stream. It should be explained that the stream and filename cannot be provided at the same time, otherwise the ValueError exception will be thrown style PythonThe newly added configuration item in 3.2. Specifies the style of the format string and the desired value is'%'、'{'And'$', the default is'%'handlers PythonThe newly added configuration item in 3.3. If this option is specified, it should be an iterative object that creates multiple handler that will be added to the root logger. It is important to note that the three configuration items, filename, stream, and handlers, can only have one presence, not 2 or 3 at the same time, or a ValueError exception will be thrown.

1.1 Level----Basicconfig

      

Logging.basicconfig (filename='logger.log', level=logging.info)# use the Basicconfig method to display the display content, if there is a filename, the log content is stored in the appropriate file, or output to the screen,  # levels are the lowest level of information, and if you want to filter out some harmless information, you can use info

1.2format

    

ImportLogginglogging.basicconfig ( level=logging. debug,format='% (asctime) s-% (levelname) s-% (message) s') Logging.debug ('Debug Message') Logging.info ('Info Message') logging.warning ('warn message') Logging.error ('error Message') logging.critical ('Critical Message')
2018-07-02 22:42:36,277-debug-DEBUG message2018-07-02 22:42:36,544-info-INFO message2018-07-02 22:42:36,544-warning-warn message2018-07-02 22:42:36,544-error-ERROR message2018-07-02 22:42:36,545-critical-critical message

Format is formatted as Time-levelname-message

Four modules of 1.3 logging

     

Component name    corresponding class name    function description Logger    Logger    provides an interface processor that the application can use all the time    Handler    sends Logger created log records to the appropriate destination output filter    Filter    provides a finer-grained control tool to determine which logging to output, and which logging format to discard    Formatter    determines the final output format of the log record

1.3.1 Print the log to the screen at the same time, and write the file

  

ImportLogginglogger=logging.getlogger ('Abc.txt') Logger.setlevel (logging. DEBUG)#Setting the log levelFh=logging. Filehandler ('Abc.txt')#output the log to a fileCh=logging. Streamhandler ()#Output to screenLogger.addhandler (FH)#Adding a method to the processorLogger.addhandler (CH) FM=logging. Formatter ('% (asctime) s-% (levelname) s-% (message) s')#setting the output formatFH.SETFORMATTER (FM)#Application Formatch.setformatter (FM) logger.debug ('Debug Message') Logger.info ('Info Message') logger.warning ('warning Message') Logger.error ('error Message') logger.critical ('Critical Message')
2018-07-03 00:05:53,601-debug-DEBUG message2018-07-03 00:05:53,601-info-INFO message2018-07-03 00:05:53,601-warning-WARNING message2018-07-03 00:05:53,601-error-ERROR message2018-07-03 00:05:53,601-critical-critical message

1.3.2 when there is a root and a child user

Root as the parent process, prints the information of the child user and prints the parent process root information at the same time

2.configparser Module

configuration file, which is stored as a dictionary

  

ImportConfigparserconfig= Configparser. Configparser ()#config={} #相当于定义一个空字典config["DEFAULT"] = {'Serveraliveinterval':' $',                     'Compression':'Yes',                     'CompressionLevel':'9'}#writing a dictionary type to a fileconfig['bitbucket.org'] ={}config['bitbucket.org']['User'] ='HG'config['topsecret.server.com'] ={}topsecret= config['topsecret.server.com']topsecret['Host Port'] ='50022'  #mutates the parsertopsecret['ForwardX11'] ='No'  #same hereWith Open ('Example.ini','W') as F:config.write (f)
= = 9 = = 50022= no

2.1 Querying the configuration file

2.1.1 View

        

Import configparserconfig=configparser. Configparser () config.read('example.ini')print('  bitbucket.org' in config)print(config['  bitbucket.org'['user'])

2.1.2 to traverse the key of a file

2.1.3 Increase

    

ImportConfigparserconfig=Configparser. Configparser () Config.read ('Example.ini')Print('bitbucket.org' inchconfig)Print(config['bitbucket.org']['User']) config.add_section ('Haibin') Config.set ('Haibin','K1','value') with open ('Example.ini','W') as F:config.write (f)

2.1.4 Delete

    

ImportConfigparserconfig=Configparser. Configparser () Config.read ('Example.ini')Print('bitbucket.org' inchconfig)Print(config['bitbucket.org']['User']) config.remove_section ('Haibin')#Delete entire blockConfig.remove_option ('bitbucket.org','User')#Delete the key value below the blockWith open ('Example.ini','W') as F:config.write (f)

3.hashlib Module

For encryption, all values can be encrypted, and a value of the same length is obtained

You can make a comparison of the files and then query whether the files are the same.

Usage

  

Import hashlibobj=hashlib.md5 () #以md5的方式进行hash #  to avoid being cracked, you can also add a checksum to the MD5 to reduce the chance of being cracked. #obj =hashlib.md5 (' SB ', encode= ' UTF8 ') obj.update ('brown') encode ('  Utf-8') #使用update方法, start the hash, the first parameter is the value of the hash, the second is the encoding mode print( Obj.hexdigest ()) #这个是对所更新的值进行输出---6ff47afa5dc7daa42cc705a03fca8a9b

   

2018-06-27-python full stack development day23-logging, Configparser, Hashlib module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.