python 日志 logging 模块,输出日志到文件与屏幕上

# encoding=utf-8
import os
import time
import logging


def get_log(filepath):
    logger = logging.getLogger()
    formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
    #  %(filename)s[line:%(lineno)d]
    logger.setLevel(logging.INFO)
    fh = logging.FileHandler(filepath, mode='a', encoding='utf-8')
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    logger.addHandler(fh)
    logger.addHandler(ch)
    return logger


if __name__ == '__main__':
    current_path = os.path.dirname(os.path.realpath(__file__))
    logpath = os.path.join(current_path, 'log/xx_%s.log' % time.strftime('%y%m%d%H%M'))
    logging = get_log(logpath)
    logging.setLevel('DEBUG')  # INFO DEBUG

在工具方法中打印日志,不需要多次配置,直接获取即可使用(一次配置多处可以使用)

_logger = logging.getLogger(__name__)

设置一个基础日志

log_format = '%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s:%(message)s'
logging.basicConfig(filename='test.log', format=log_format, filemode='a', level=logging.DEBUG)

指定文件编码,需要改用 handlers 参数传入

logging.basicConfig(handlers=[logging.FileHandler(filename="./log_records.txt", encoding='utf-8', mode='a+')], level=logging.DEBUG)

错误记录

  • 磁盘空间不足导致
Traceback (most recent call last):
  File "C:\Python38\lib\logging\__init__.py", line 1085, in emit
    self.flush()
  File "C:\Python38\lib\logging\__init__.py", line 1065, in flush
    self.stream.flush()
OSError: [Errno 28] No space left on device
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值