python 之 软件开发目录规范 、logging模块

6.4 软件开发目录规范

软件(例如:ATM)目录应该包含:

文件名存放备注
bin start.py,用于起动程序  
core src.py,程序核心功能代码  
conf settings.py, 程序配置信息  
db db.txt 数据库信息  
lib common.py ,存放常用功能  
log access.log ,存放记录  

start.py :

import sys,os                                   #应该把项目的根目录添加到环境变量中
BASE_DIR=os.path.dirname(os.path.dirname(__file__)#os.path.dirname(__file__) 获取当前文件上一级路径名
sys.path.append(BASE_DIR)                       #拿到ATM所在的文件夹
from core import src
​
src.run()

sys.path.append(r'D:\code\SH_fullstack_s1\day15\ATM') 添加的是绝对路径,不支持移植到别的硬件上运行

src.py :

from conf import settings
from lib import common
​
logger1=common.get_logger('atm')
​
def login():
    print('登录....')
    with open(settings.DB_PATH,encoding='utf-8') as f:
        for line in f:
            print(line)
​
def register():
    print('注册....')
​
def shop():
    print('购物....')
​
def pay():
    print('支付...')
​
def transter():
    print('转账...')
    common.logger('xxxx给他爹xx转账10000')
    logger1.debug('xxxx给他爹xx转账10000')
    logger1.error('xxxx给他爹xx转账10000,转账失败')
​
def run():
    while True:
        print("""
        1 登录
        2 注册
        3 购物
        4 支付
        5 转账
        """)
​
        choice=input('>>: ').strip()
        if choice == '1':
            login()
        elif choice == '2':
            register()
        elif choice == '3':
            shop()
        elif choice == '4':
            pay()
        elif choice == '5':
            transter()
        else:
            print('输入错误指令')
src.py

settings.py:

DB_PATH=r'D:\code\SH_fullstack_s1\day15\ATM\db\db.txt' #自定义设置的文件路径
LOG_PATH=r'D:\code\SH_fullstack_s1\day15\ATM\log\access.log'
LOGGING_DIC = {.....}               #log配置字典

common.py :

from conf import settings
​
def logger(msg):
    with open(settings.LOG_PATH,'a',encoding='utf-8') as f:
        f.write('%s\n' %msg)
​
        
import logging.config
import logging
from conf import settings
​
def get_logger(name): #name='atm'
    logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置
    l1=logging.getLogger(name)
    return l1
View Code

6.5 logging 模块

import logging
logging.basicConfig(      #为logging模板指定全局配置,针对所有logger有效,控制打印到文件中
filename='access.log',          # /stream=sys.stdout 打印在屏幕上,但和filename只能存在其一
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=40
)
logging.debug('debug...') # 10
logging.info('info....') #20
logging.warning('.....') #30
logging.error('......') # 40
logging.critical('.....') #50
View Code

6.51 logging模块的四类对象

logger:负责产生日志

logger1=logging.getLogger('xxx')
filter:过滤日志(不常用)

handler:控制日志打印到文件or终端

fh1=logging.FileHandler(filename='a1.log',encoding='utf-8')
fh2=logging.FileHandler(filename='a2.log',encoding='utf-8')
sh=logging.StreamHandler()
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 - %(message)s',)
View Code

logger ---->多个file handler <----多个formatter

绑定关系:

1.为logger1对象绑定handler:

logger1.addHandler(fh1)
logger1.addHandler(fh2)
logger1.addHandler(sh)
2.为handler对象绑定日志格式

fh1.setFormatter(formatter1)
fh2.setFormatter(formatter1)
sh.setFormatter(formatter2)
设定日志级别: 两层关卡,必须都通过,日志才能正常记录

logger1.setLevel(10)
fh1.setLevel(10)
fh2.setLevel(10)
sh.setLevel(10)
​
#调用logger1对象下的方法,产生日志,然后交给不同的handler,控制日志记录到不同的地方
logger1.debug('调试信息')   #调用logger1,产生日志
View Code

日志的继承

import logging
logger1=logging.getLogger('xxx')
logger2=logging.getLogger('xxx.son')
logger3=logging.getLogger('xxx.son.grandson')
​
sh=logging.StreamHandler()
​
formatter2=logging.Formatter(fmt='%(asctime)s - %(message)s',)
​
sh.setFormatter(formatter2)
​
logger1.addHandler(sh)
logger2.addHandler(sh)
logger3.addHandler(sh)
​
logger1.setLevel(10)
logger2.setLevel(10)
logger3.setLevel(10)
sh.setLevel(10)
​
logger1.debug('测试。。。。')
logger2.debug('测试。。。。')
logger3.debug('测试。。。。')
View Code
posted @ 2019-06-19 22:01  small_white-  阅读(570)  评论(0编辑  收藏  举报