Python logging模块的基本使用

logging 模块主要包含四个部分:

Loggers: 提供程序调用的接口,在代码中调用 api 来记录日志

Handlers: 对日志信息进行不同的处理,如记录日志的方式

Formatters: 定义日志的打印格式

Filters:对日志信息进行过滤, 自定义日志是否输出的判断

import logging

"""
1. DEBUG: 对应数值10,打印调式信息。
2. INFO: 对应数值20,处理请求,状态变化等日常信息。
3. WARNING: 对应数值30,比较重要的提醒信息,警告信息。
4. ERROR: 对应数值40,程序发生了报错,如连接错误,编译错误。
5. CRITICAL: 对应数值50,特别严重的问题,如服务器故障等
"""

file_name = 'logger.txt'
formatter = '%(asctime)s -- %(filename)s[line:%(lineno)d] %(levelname)s\t%(message)s'

# 如果定义了file_name 那么就不在控制台输出日志了
# 传入日志的格式和输出日志的等级
logging.basicConfig(filename=file_name, format=formatter, level=logging.DEBUG)

logger = logging.getLogger(__name__)

console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
"""
1. asctime:日志的输出时间,默认为 YYYY-mm-DD HH:MM:SS,SSS,如: 2019-10-02 21:29:41,016,一直精确到毫秒。可以额外指定 datefmt 参数来指定该变量的格式

2. name: 日志对象的名称

3. filename: 不包含路径的文件名

4. pathname:包含路径的文件名

5. funcName: 日志记录所在的函数名

6. levelname: 日志的级别名称

7. message: 具体的日志信息

8. lineno: 日志记录的代码所在的行号

9. pathname: 完整路径

10. process: 当前进程ID

11. processName: 当前进程名称

12. thread: 当前线程ID

13. threadName: 当前线程名称

其中 asctime 和 message 是必须有的,不然就失去日志的意义了。
常用的有 filename,lineno,levelname,其他的根据情况选用
"""
console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console.setFormatter(console_formatter)
logger.addHandler(console)

logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')

按时间轮转

import logging
from logging.handlers import TimedRotatingFileHandler
import time

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)

formatter = '%(asctime)s -<>- %(filename)s -<>- [line]:%(lineno)d -<>- %(levelname)s -<>- %(message)s'
"""
1. filename: 指定日志文件的名字,会在指定的位置创建一个 filename 文件,然后会按照轮转数量创建对应数量的日志文件,每个轮转文件的文件名为 filename 拼接时间,默认YY-mm-DD_HH-MM-SS,可以自定义。
2. when: 指定日志文件轮转的时间单位
    S - Seconds
    M - Minutes
    H - Hours
    D - Days
    midnight - roll over at midnight
    W{0-6} - roll over on a certain day; 0 - Monday
3. interval: 指定日志文件轮转的周期,如 when='S', interval=10,表示每10秒轮转一次,when='D', interval=7,表示每周轮转一次。
4. backupCount: 指定日志文件保留的数量,指定一个整数,则日志文件只保留这么多个,自动删除旧的文件。
"""
time_rotate_file = TimedRotatingFileHandler(filename='time_rotate', when='m', interval=1, backupCount=5)
time_rotate_file.setFormatter(logging.Formatter(formatter))
time_rotate_file.setLevel(logging.INFO)

console_handler = logging.StreamHandler()
console_handler.setLevel(level=logging.INFO)
console_handler.setFormatter(logging.Formatter(formatter))

logger.addHandler(time_rotate_file)
logger.addHandler(console_handler)

count=0
while True:
    count+=1
    logger.info('info-{}'.format(count))
    time.sleep(1)

按大小轮转

import logging
from logging.handlers import RotatingFileHandler
import time

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)

formatter = '%(asctime)s -<>- %(filename)s -<>- [line]:%(lineno)d -<>- %(levelname)s -<>- %(message)s'
"""
RotatingFileHandler 的主要参数:

1. filename: 指定日志文件的名字,会在指定的位置创建一个 filename 文件,然后会按照轮转数量创建对应数量的日志文件,每个轮转文件的文件名为 filename 拼接编号,编号从1开始。

2. maxBytes: 设置日志文件的大小,单位是字节,如 1kb 是1024,1M 是 1024*1024 ,1G 是 1024*1024*1024 。

3. mode: 设置文件的写入模式,默认 mode='a' ,即追加写入。

4. backupCount: 指定日志文件保留的数量,指定一个整数,日志文件只保留这么多个,自动删除旧的文件。
"""
size_rotate_file = RotatingFileHandler(filename='size_rotate', maxBytes=1 * 1024, backupCount=500)
size_rotate_file.setFormatter(logging.Formatter(formatter))
size_rotate_file.setLevel(logging.INFO)

console_handler = logging.StreamHandler()
console_handler.setLevel(level=logging.INFO)
console_handler.setFormatter(logging.Formatter(formatter))

logger.addHandler(size_rotate_file)
logger.addHandler(console_handler)

count=0
while True:
    count+=1
    logger.info('info-{}'.format(count))
    time.sleep(1)

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一壶浊酒..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值