hashlib模块:
>>> import hashlib #引入模块
>>> m = hashlib.md5() #md5算法加密
>>> m.update('hello world'.encode('utf8'))
>>> m.hexdigest() #返回加密后的密文,十六进制
'5eb63bbbe01eeed093cb22bb8f5acdc3'
>>> d = hashlib.sha256() #sha256加密方式
>>> d.update('hello world'.encode('utf-8'))
>>> d.hexdigest()
'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
logging 模块:
import logging
logging.basicConfig(
level= logging.DEBUG, #log level设置
format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', #输出格式
datefmt = '%a,%d %b %Y %H:%M:%S', #时间格式
filename = 'test.log', #输出到文件的文件名
filemode='a' #文件操作模式
) #log格式配置
#log格式 Mon,28 May 2018 17:22:42 teststudy.py[line:357] DEBUG debug- info
logging.debug('debug- info')
logging.info('info- info')
logging.warning('warning -info')
logging.error('error-info')
logging.critical('critical- info')
format参数中可能用到的格式话串:
%(name)s logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块完整路径,可能无
%(filename)s 调用日志 输出函数的模块文件名
%(module)s 调用日志输出函数模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在代码行
%(created)f 当前时间,用UNIX标准时间的浮点数表示
%(relativeCreated)d 输出日志信息时的自logger创建以来的毫秒数
%(asctime)s 字符串形式的当前时间,默认格式是'2003-08-08 16:49:45.896'
%(thread)d 线程ID,可能没有
%(threadName)s 线程名,可能没有
%(process)d 进程ID,可能没有
%(message)s 用户输出信息
getLogger()获取log:
import logging
#创建logger对象
logger= logging.getLogger()
#创建一个FileHandler,将log写入到文件
f_log = logging.FileHandler('test.log')
#创建StreamHandler输出log到console控制台
c_log = logging.StreamHandler()
#log输出格式设置
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(message)s')
#设置log格式给f_log 和c_log
f_log.setFormatter(formatter)
c_log.setFormatter(formatter)
#addHandler方法添加输出log的方式
logger.addHandler(f_log)
logger.addHandler(c_log)
#设置log输出级别,如果不进行设置,默认log level为:WARNING
logger.setLevel("DEBUG") #等价于 logger.setLevel(logging.DEBUG)
#打印log
logger.debug('debug info')
logger.info('info info')
logger.warning('warning info')
logger.error('error info')
logger.critical('critical info')