python模块#4

一. 日志模块logging

        什么是日志:logging是Python标准库中的一个模块,用于记录日志信息。通过logging模块,我们可以在程序运行时输出各种级别的日志,包括调试信息、错误信息、警告信息等,方便程序的调试和维护。同时,我们还可以将日志信息保存到文件或者发送到其他地方,以便于后续的查阅和分析。

1. 导入logging模块

import logging

2. 设置日志的输出级别

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

'''在python中默认的日志级别设置为WARNING级别'''

我们设置了日志输出级别为INFO级别,所以只有INFO级别及以上的日志信息会被输出。然后,我们分别输出了不同级别的日志信息,logging会将它们输出到标准输出设备(console)。

除了上述例子中的基本用法外,logging模块还提供了一些高级用法,比如设置日志输出格式、将日志信息输出到文件、通过SMTP发送日志信息等,可以根据具体需求进行配置。

1. 日志基本使用
'''日志格式'''

format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s'

import logging

'''日志格式为'''
file_handler = logging.FileHandler(filename='x1.log', mode='a', encoding='UTF-8')###自动创建日志x1.log
"""指定日志存储的格式:"""
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s - %(lineno)d行 - %(created)f :  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p', # 2023-09-25 10:23:31 AM
    handlers=[file_handler,],
    level=logging.DEBUG
)

format参数中可能用到的格式化串:


%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息

2. 日志的详细使用

        在日志中logging库提供了多个组件:Logger、Handler、Filter、Formatter

 1.logger对象:负责产生日志

2. filter对象:负责过滤日志

3..handler对象:负责日志产生的位置

hd1 = logging.FileHandler('a1.log',encoding='utf8')  # 产生到文件的
hd2 = logging.FileHandler('a2.log',encoding='utf8')  # 产生到文件的
hd3 = logging.StreamHandler()  # 产生在终端的

日志的格式: 

fm1 = logging.Formatter(
    fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
)
fm2 = logging.Formatter(
    fmt='%(asctime)s - %(name)s %(message)s',
    datefmt='%Y-%m-%d',
)

.绑定handler对象
logger.addHandler(hd1)
logger.addHandler(hd2)
logger.addHandler(hd3)


        绑定formatter对象
hd1.setFormatter(fm1)
hd2.setFormatter(fm2)
hd3.setFormatter(fm1)
        7.设置日志等级
logger.setLevel(30)


         8.记录日志
logger.warning('生成日志')

3.日志配置成字典使用
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'

test_format = '%(asctime)s] %(message)s'
other_format = '[%(levelname)s][%(asctime)s]] %(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')
# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },

        'other': {
            'format': other_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 * 100,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
        'other': {
             'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'other'
        },

    },
    'loggers': {
        # logging.getLogger(__name__)拿到的logger配置  空字符串作为键 能够兼容所有的日志
        '': {
            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },  # 当键不存在的情况下 (key设为空字符串)默认都会使用该k:v配置
        'default': {
            'handlers': ['default', ],
            'level': 'DEBUG',
            'propagate': False,
        },

        'console': {
            'handlers': ['console', 'default'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'other': {
            'handlers': ['other'],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}


'''日志配置成字典'''


def common(xxx):
    logging.config.dictConfig(LOGGING_DIC)  # 自动加载字典中的配置
    # logger1 = logging.getLogger('default')
    logger1 = logging.getLogger(xxx)
    # logger1.debug(xxx)
    return logger1

logger = common('default')
logger.debug('xxx')
logger.info('xxx')
logger.warning('xxx')

二. 第三方模块的下载与安装

1. 下载与安装

        Python 第三方模块可以通过 pip 工具下载。pip 是 Python 下载和安装第三方模块的标准工具。下面是使用 pip 安装模块的步骤:

  1. 打开命令行终端 win+r,输入cmd
  2. 输入 pip install 模块名,例如 pip install numpy
  3. 回车后,pip 将会自动从 PyPI(Python Package Index)下载并安装该模块
  4. 输入pip list 可以查看已经安装了哪些模块

2. 换源

        当我们下载时,会因为是国外网站导致下载速度慢,为了加快下载的速度,我们把默认的官网源修改成我们国内的源,那么该如何换源,目前我们国内的一些源有:

        1. 豆瓣:http://pypi.douban.com/simple/

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

        3.华为云:https://repo.huaweicloud.com/repository/pypi/simple

        4.清华大学:https://pypi.tuna.tsinghua.edu.cn/simple

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

换源方法:

临时换源:

        pip install django # 默认使用的是python官方的
    pip3.8 install numpy -i http://mirrors.aliyun.com/pypi/simple/ 

永久换源:

        

-1 在文件地址栏输入:%APPDATA% 回车,快速进入 C:\Users\电脑用户\AppData\Roaming 文件夹中
-2 新建 pip 文件夹并
-3 在文件夹中新建 pip.ini 配置文件
-4 配置文件写入:
如果想换源就直接把源的路径换了就可以了
    '''
    [global]
    index-url = https://mirrors.aliyun.com/pypi/simple
    [install]
    use-mirrors =true
    mirrors =https://mirrors.aliyun.com/pypi/simple
    trusted-host =mirrors.aliyun.com
    '''

        以后再命令行中,下载模块,就会走国内源了

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值