Python日志模块logging&JSON

日志模块的用法

json部分

先开一段测试代码:注意  str可以直接处理字典   eval可以直接将字符串转成字典的形式

dic={'key1':'value1','key2':'value2'}

data=str(dic)#字典直接转成字符串

print(type(data),data)

#
# with open('db.txt','w',encoding='utf-8') as f:
# f.write(str(dic))
# with open('db.txt','r',encoding='utf-8') as f:
data=f.read()
print(data,type(data))
dic2=eval(data)
print(dic2,type(dic2))

原先目录结构为:

Python日志模块logging&JSON

=======================================================logging begin===============================================================

settings.py

 """
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
"""
#注意跨平台性
#os.path.join 用来拼接绝对路径 如果有2个头 就是C D的话,会取第二个
import os,sys
BaseDir=os.path.join('C:\\','a','b','c','d.txt')
print(BaseDir)#C:\\a\b\c\d.txt #如果有2个头 就是C D的话,会取第二个
BaseDir2=os.path.join('C:\\','a','b','D:\\','d.txt')
print(BaseDir2) BaseDir3=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BaseDir3)
#拼出access.log的路径
LOG_PATH=os.path.join(BaseDir3,'log','access.log')
print(LOG_PATH)
DB_PATH=os.path.join(BaseDir3,'db','user')
print(DB_PATH)
LIB_PATH=os.path.join(BaseDir3,'lib','common.py')
print(LIB_PATH) # 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s' # log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
'id_simple' : {
'format' : id_simple_format
},
},
'filters': {},
'handlers': {
#打印到终端的日志
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': LOG_PATH, # 日志文件
'maxBytes': 1024*1024*5, # 日志大小 5M
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
}, },
'loggers': {
'': {
'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'DEBUG',
'propagate': False, # 向上(更高level的logger)传递
},
},
}

common.py

 """
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
"""
from conf import setting
import logging.config
# def log(msg):
# with open(setting.LOG_PATH,'a',encoding='utf-8') as f:
# f.write('%s\n'%msg) def logger_handle(log_name):
logging.config.dictConfig(setting.LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(log_name) # 生成一个log实例
return logger

start.py

 """
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
""" import os,sys
print(os.path.abspath(__file__)) #打印当前文件的绝对路径 BaseDir=os.path.dirname(os.path.abspath(__file__))#取到star的目录bin
#print(BaseDir)
BaseDir2=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #取到bin的目录ATM
#print(BaseDir2) #取到了ATM sys.path.append(BaseDir2) #添加到环境变量
from core import src
if __name__=='__main__':
src.run()

src.py

 """
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
"""
from lib import common
def transfure():
print('转账')
msg='陈凯给周琪转账中....'
logger = common.logger_handle('转账')
logger.info(msg) def pay():
print('支付') def shopping_cart():
print('购物车') def run():
msg=""" 1 转账
2 支付
3 购物车 """
while True:
print(msg)
user_choice=input('choice:>>').strip()
if not user_choice:continue
if user_choice=='':
transfure()
elif user_choice=='':
pay()
elif user_choice=='':
shopping_cart()

================================================logging end============================================================

下面内容与实际使用无关,只是做个了解

日志模块分析代码

 """
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
""" #日志级别对应不同的数字
#介绍
# import logging
# logging.basicConfig(
# # filename='access.log',
# #日志名 日志级别 日志模块 日志信息
# format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S %p',
# level=10
# )
# logging.debug('debug is 调试') #10
# logging.info('info is 正常信息') #20
# logging.warning('warning is 警告信息') #30
# logging.error('error is 错误信息') #40
# logging.critical('critical is ') #50
#日志级别设置为30 30以上的会打印 30以下的不会打印 默认的日志级别是30 #日志模块的详细用法
"""
1 logger 产生日志
2 filter 基本不用 忽略
3 handler 接收logger传过来的日志 进行日志格式化
,可以打印到终端,也可以打印到文件 4 formatter 日志格式 logger-->handeler(可以多个)-->formatter 5 为handler绑定日志格式 6 """
# 1 logger 产生日志 import logging logger1=logging.getLogger('访问日志') # 3 handler 接收logger传过来的日志 进行日志格式化 sh=logging.StreamHandler() #打印到终端
fh1=logging.FileHandler('s1.log',encoding='utf-8')
fh2=logging.FileHandler('s2.log',encoding='utf-8') #4 formatter 日志格式
formatter1=logging.Formatter( fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p', ) formatter2=logging.Formatter( fmt='%(asctime)s = %(name)s = %(levelname)s =%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p', ) formatter3=logging.Formatter( fmt='%(asctime)s | %(name)s | %(levelname)s |%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p', ) # 5 为handler绑定格式 绑定handler与formatter的关系 sh.setFormatter(formatter1)
fh1.setFormatter(formatter2)
fh2.setFormatter(formatter3) #6 为logger绑定handler
logger1.addHandler(sh)
logger1.addHandler(fh1)
logger1.addHandler(fh2)
#7 设置日志级别 logger1可以设置级别 handler也可以设置级别
#logger对象的日志级别应该<=handler对象的日志级别
logger1.setLevel(10) #如果此处设置为50的话 则可以显示1条
sh.setLevel(10)
fh1.setLevel(10)
fh2.setLevel(10) #测试
logger1.debug('测试debug')
logger1.info('测试info')
logger1.warning('测试warning')
logger1.error('测试errror')
logger1.critical('测试critical')
上一篇:Angular4.x 安装|创建项目|目录结构|创建组件


下一篇:H5 EventSource 实现web页面推送功能demo