Python日志器使用方法

import logging
from logging import handlers


# 全局搜索Formatter

def basic_log():
    """使用默认日志器 root"""
    # 缺点,不能同时进行文件输出和控制台输出
    format = "%(name)s %(levelname)s %(pathname)s %(lineno)d %(message)s"

    # 对默认日志器进行配置
    logging.basicConfig(level='DEBUG', format=format, filename='test.log')
    # 可以通过数字或字符串取
    # logging.basicConfig(level=logging.DEBUG)

    # 使用默认日志器
    logging.error("this is a error message")
    logging.info("this is a info message")
    logging.warning("this is a warning message")
    logging.debug("this is a debug message")


def custum_log():
    """自定义日志器"""

    # 创建/获取日志器
    mylogger = logging.getLogger('mytest')
    mylogger.setLevel('DEBUG')

    # 创建输出处理器(流处理器)
    console_handler = logging.StreamHandler()

    # 给输出处理器设置格式
    console_formatter = logging.Formatter("[%(asctime)s] %(name)s %(levelname)s %(pathname)s %(lineno)d %(message)s")
    console_handler.setFormatter(console_formatter)

    # 创建文件输出处理器
    # handlers.RotatingFileHandler转存文件处理器 当我们文件达到指定大小时,会生成新的文件继续保存日志
    # 当文件写到100m时会自动生成新日志文件,如果达到10个会复写之前的
    file_handler = handlers.RotatingFileHandler(filename='mylogger.log', maxBytes=100 * 1024 * 1024,backupCount=10 )

    # 给输出处理器设置格式
    file_formatter = logging.Formatter("[%(asctime)s] %(name)s %(levelname)s %(pathname)s %(lineno)d %(message)s")
    file_handler.setFormatter(file_formatter)

    # 日志器添加处理器
    mylogger.addHandler(console_handler)
    mylogger.addHandler(file_handler)

    # 使用自定义日志器
    mylogger.error("this is a error message")
    mylogger.info("this is a info message")
    mylogger.warning("this is a warning message")
    mylogger.debug("this is a debug message")


if __name__ == '__main__':
    # basic_log()

    custum_log()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值