日志模块 - 第三方模块

目录

什么是日志?

基本使用

logging的详细使用

配置成字典格式:当成配置文件使用

日志终极版

第三方模块(重点)

如何优化下载?


日志就是记录你的代码在运行过程中产生的变化
# 日志的级别
'''根据日志级别的不同,选择性的记录'''

logging.debug('debug message') # 10
logging.info('info message') # 20
logging.warning('warning message') # 30
logging.error('error message') # 40
logging.critical('critical message') # 50

基本使用

# 基本使用
# 产生日志的
file_handler = logging.FileHandler(filename='x1.log', mode='a', encoding='utf-8',)

"""
2023-03-13 12:06:48 PM - root - ERROR -05 logging模块基本使用:  你好
"""
# 指定日志的格式
logging.basicConfig(
    format='%(lineno)d - %(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s - %(pathname)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    handlers=[file_handler,],
    level=logging.ERROR
)

logging.error('你好')  # 10

logging的详细使用

# 日志的组成部分:
1. logger对象 # 负责产生日志
2. Filter对象 # 过滤的 (忽略)
3. Handler对象 # 负责日志产生的位置
4. Formatter对象 # 负责产生的格式

# 1.logger对象:负责产生日志
logger = logging.getLogger()
# 2.filter对象:负责过滤日志(直接忽略)
# 3.handler对象:负责日志产生的位置
hd1 = logging.FileHandler('a1.log', encoding='utf8')  # 产生到文件的
hd2 = logging.FileHandler('a2.log', encoding='utf8')  # 产生到文件的
hd3 = logging.StreamHandler()  # 产生在终端的
# 4.formatter对象:负责日志的格式
fm1 = logging.Formatter(
    fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)
fm2 = logging.Formatter(
    fmt='%(asctime)s - %(name)s %(message)s',
    datefmt='%Y-%m-%d',
)
# 5.绑定handler对象
logger.addHandler(hd1)
logger.addHandler(hd2)
logger.addHandler(hd3)
# 6.绑定formatter对象
hd1.setFormatter(fm1)
hd2.setFormatter(fm2)
hd3.setFormatter(fm1)
# 7.设置日志等级
logger.setLevel(10)
# 8.记录日志
logger.debug('')

配置成字典格式:当成配置文件使用

import logging
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'

# 日志文件
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
log_path = os.path.join(BASE_DIR, 'log')

if not os.path.exists(log_path):
    os.mkdir(log_path)

logfile_path = os.path.join(log_path, 'a3.log')  # D:\python25\day22\log\a3.log
# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},  # 过滤日志
    'handlers': {
        # 打印到终端的日志
        'console': {
            'level': 'ERROR',
            '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配置  空字符串作为键 能够兼容所有的日志
        'xxx': {
            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },  # 当键不存在的情况下 (key设为空字符串)默认都会使用该k:v配置
    },
}

# 使用配置字典
logging.config.dictConfig(LOGGING_DIC)  # 自动加载字典中的配置
logger1 = logging.getLogger('xxx')
logger1.debug('')

配置好日志之后,把配置字典封装成函数 ,存放在lib文件夹的py文件中,需导入三个模块

  1. import  logging #日志模块
  2. import logging.config # 日志所需的文件模块
  3. from conf import stetings #日志

 

 

日志终极版

import logging

# 一:日志配置
logging.basicConfig(
    # 1、日志输出位置:1、终端 2、文件
    # filename='access.log', # 不指定,默认打印到终端

    # 2、日志格式
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',

    # 3、时间格式
    datefmt='%Y-%m-%d %H:%M:%S %p',

    # 4、日志级别
    # critical => 50
    # error => 40
    # warning => 30
    # info => 20
    # debug => 10
    level=30,
)

# 二:输出日志
logging.debug('调试debug')
logging.info('消息info')
logging.warning('警告warn')
logging.error('错误error')
logging.critical('严重critical')

'''
# 注意下面的root是默认的日志名字
WARNING:root:警告warn
ERROR:root:错误error
CRITICAL:root:严重critical
'''

第三方模块(重点)

在内置模块不能满足我们的开发需求时,就要借助于第三方模块来实现一些更复杂的需求

""" 第三方模块需要网络下载"""

 pip安装模块默认是国外下载的;所以下载可能会慢,有可能下载不成功

如何优化下载?

换源(换国内的源)

"""
清华源:
https://pypi.tuna.tsinghua.edu.cn/simple

阿里云源:
http://mirrors.aliyun.com/pypi/simple/

中科大源: 
https://pypi.mirrors.ustc.edu.cn/simple/

豆瓣源:
http://pypi.douban.com/simple/
"""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值