1 logging 日志模块
1.1 函数式简单配置
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。
灵活配置日志级别,日志格式,输出位置:
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w')
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
配置参数:

logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有: filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。 filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。 format:指定handler使用的日志显示格式。 datefmt:指定日期时间格式。 level:设置rootlogger(后边会讲解具体概念)的日志级别 stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。 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-07-08 16:49:45,896”。逗号后面的是毫秒 %(thread)d 线程ID。可能没有 %(threadName)s 线程名。可能没有 %(process)d 进程ID。可能没有 %(message)s用户输出的消息
2.2 logger对象配置
import logging
logger = logging.getLogger()
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log')
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh) #logger对象可以添加多个fh和ch对象
logger.addHandler(ch)
logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')
logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,可以通过:logger.setLevel(logging.Debug)设置级别。
#日志模块
#配置方式 1.config 2.logger
#config
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(lineno)s] %(message)s %(module)s",
datefmt="%Y-%m-%d %X",
filename="logger.log",
filemode="w",
)
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")
#logger
# def logger():
# logger=logging.getLogger()
#
# fh=logging.FileHandler("logger2.log")
# sh=logging.StreamHandler()
#
# Fm=logging.Formatter("%(asctime)s")
# logger.setLevel(logging.DEBUG)
#
# logger.addHandler(fh)
# logger.addHandler(sh)
#
# return logger
#
# logger=logger()
#
# logger.debug("debug message")
# logger.info("info message")
# logger.warning("warning message")
# logger.error("error message")
# logger.critical("critical message")
2 json /pickle序列化
#序列化:把一个数据类型的数据转化成一个json字符串类型的数据 dumps
#反序列化:把一个josn字符串类型的数据转化成数据类型 loads
import json
d={"name":"egon","age":16}
# #dumps方式
# s=json.dumps(d)
# with open("new","w") as f:
# f.write(s)
# with open("new",) as f:
# date=f.read()
# s1=json.loads(date) #date是读取文件的内容
#dump 方式
# with open("new","w") as f:
# json.dump(d,f) #多了一个文件句柄的参数,不需要在做写的操作
with open("new","r") as f:
date=json.load(f) #不需要在做读的操作
print(date)
之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就不管用了,所以eval的重点还是通常用来执行一个字符串表达式,并返回表达式的值。
|
1
2
3
4
|
import jsonx="[null,true,false,1]"print(eval(x))print(json.loads(x)) |
什么是序列化?
我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
json
如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。
JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:

|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#----------------------------序列化import jsondic={'name':'alvin','age':23,'sex':'male'}print(type(dic))#<class 'dict'>j=json.dumps(dic)print(type(j))#<class 'str'>f=open('序列化对象','w')f.write(j) #-------------------等价于json.dump(dic,f)f.close()#-----------------------------反序列化<br>import jsonf=open('序列化对象')data=json.loads(f.read())# 等价于data=json.load(f) |
注意点
pickle
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
##----------------------------序列化import pickledic={'name':'alvin','age':23,'sex':'male'}print(type(dic))#<class 'dict'>j=pickle.dumps(dic)print(type(j))#<class 'bytes'>f=open('序列化对象_pickle','wb')#注意是w是写入str,wb是写入bytes,j是'bytes'f.write(j) #-------------------等价于pickle.dump(dic,f)f.close()#-------------------------反序列化import picklef=open('序列化对象_pickle' |
