Python 第十九章 包+日志

# 1.包
    # import 包.包.包
    # from 包.包.包 import 模块
    # 路径:
    #     绝对:从最外层的包开始导入
    #     相对:从当前(.)开始导入或者父级(..)导入
    # 使用相对路径的时候必须在包的外层且同级

    # from 包 import *
    # 需要在__init__.py做操作

    # python2: import 文件夹(没有__init__.py)报错
    # python3: import 文件夹(没有__init__.py)不报错

    # 包:自己一定要多练练

# 2.日志:
#     记住怎么使用就好了

#     自己定义日志开始
#     import logging
#     logger = logging.getLogger()
#     # 创建一个logger
#     fh = logging.FileHandler('test.log',mode="a",encoding='utf-8')   # 文件
#     ch = logging.StreamHandler()   # 屏幕
#     formatter = logging.Formatter('%(asctime)s - %(name)s - %(filename)s - [line:%(lineno)d] -  %(levelname)s - %(message)s')
#     # 将屏幕和文件都是用以上格式
#     logger.setLevel(logging.DEBUG)
#     # 设置记录级别
#     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 -- 日志

# import logging
# logging.debug('我是调试')
# logging.info('我是信息')
# logging.warning('我是警告')
# logging.error('我是错误')
# logging.critical('我是危险')

# 默认是从warning开始记录

# import logging
# logging.basicConfig(level=logging.DEBUG,
#                     format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s',
#                     datefmt='%Y-%m-%d %H:%M:%S',
#                     filename='test.log',
#                     filemode='w')

# dic = {"key":123}
# logging.debug(dic)

# num = 100
# logging.info(f"用户当前余额:{num - 50}")

# try:
#     num = int(input("请输入数字:"))
# except Exception as e:
#     logging.warning("int将字符串转换报错了")
# print("12334")

# logging.error('我是错误')
# logging.critical('我是危险')



import logging
logger = logging.getLogger()
# 创建一个logger
fh = logging.FileHandler('test.log',mode="a",encoding='utf-8')   # 文件
ch = logging.StreamHandler()   # 屏幕
formatter = logging.Formatter('%(asctime)s - %(name)s - %(filename)s - [line:%(lineno)d] -  %(levelname)s - %(message)s')
# 将屏幕和文件都是用以上格式
logger.setLevel(logging.DEBUG)
# 设置记录级别
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')


posted @ 2019-08-05 23:24  张珊33  阅读(131)  评论(0编辑  收藏  举报