Package, introducing absolute relative import log module

1. The use of the package

创建一个包,也会发生三件事:
1.将该包内__init__py文件加载到内存
2.创建一个以包命名的名称空间
3.通过包名称.的方式引用__init__的所有的名字
1.1 executable file and import the package in the packet using the import function
sys.path 会主动加载执行文件的当前目录
(以下执行文件与包在同一工作目录下)
引用包里的py文件的变量:
1.在执行文件写入import 包
2.包里的__init__里面写from 包 import py文件
3.执行文件 包.py文件.变量
引用包里的包1的py文件的变量:
1.在执行文件写入import 包
2.在包的__init__写上from 包 import 包2(包2的__init__里面所有变量都能引用)
3.在包2的__init__写上from 包.包1 import py文件
4.执行文件 包.包1.py文件.变量
# 无论从哪里引用模块,最开始的模块或者包名一定是内存、内置函数,sys.path中能找到的
1.2 performs the function from import file by introducing the package and an inner package
# 这种方式不用设置__init__文件
from a.b.c import d
c的.的前面一定是包,import 的后面一定是名字,并且不能再有点

2. The absolute imports relative imports

# 由于模块增加了很多功能,所以这个文件就要划整一个包,无论对模块有任何操作,对于使用者来说不应该改变,极少的改变对其的调用方式
import nb
nb.f1()
nb.f2()
nb.f3()
nb.f4()
nb.f5()
nb.f6()
# 将原包名改成了大写的NB
import NB as nb
nb.f1()
nb.f2()
nb.f3()
nb.f4()
nb.f5()
nb.f6()
nb.f7()
# 还应再将包里的__init__种的nb进行修改
=>from .m1 import f1,f2
  from .m2 import f3,f4
  from .m3 import f5,f6
  from .m4 import f7
. .. ... => 相对导入

3. log module

1.low版日志
import logging
logging.basicConfig(level=logging.DEBUG,)
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

def func():
    print('in func')
    logging.debug('正常执行')
func()

logging.basicConfig(
    level=30,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    filename=r'test.log')
logging.debug('调试模式')  # 10
logging.info('正常模式')  # 20
logging.warning('警告信息')  # 30
logging.error('错误信息')  # 40
logging.critical('严重错误信息')  # 50
# low版的日志缺点: 文件与屏幕输入只能选择一个.
2.标配版
import logging
logger = logging.getLogger()
fh = logging.FileHandler('标配版.log',encoding='utf-8')
sh = logging.StreamHandler()
formatter1=logging.Formatter('%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')
formatter2=logging.Formatter('%(asctime)s %(filename)s')
fh.setFormatter(formatter1)
sh.setFormatter(formatter2)
logger.addHandler(fh)
logger.addHandler(sh)
logger.setLevel(10)
fh.setLevel(10)
sh.setLevel(40)
logging.debug('调试模式')
logging.info('正常模式')
logging.warning('警告模式')
logging.error('错误信息 ')
logging.critical('严重错误信息')
3.旗舰版
import os
import logging.config
# 定义三种日志输出格式
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目录
logfile_name = 'all2.log'  # log文件名
# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)
# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)
# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},
    'handlers': {
        #打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024*1024*5,  # 日志大小 5M
            'backupCount': 5,      #轮流的个数
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}


def load_my_logging_cfg():
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger(__name__)  # 生成一个log实例  __name__对应的是[task_id:%(name)s]
    logger.info('It works!')  # 记录该文件的运行状态

if __name__ == '__main__':
    load_my_logging_cfg()

Guess you like

Origin www.cnblogs.com/wxl1025/p/11139587.html