Skip to main content

Python Python中的日志模块

Published 1 min readMarkdown
Python Python中的日志模块

Python中的日志模块

日志的作用

  • 日记
  • 程序行为
  • 重要信息记录

日志的等级

  • debug
  • info
  • warning
  • error
  • critical

logging模块的使用

  • logging.basicConfig
参数名作用举例
level日志输出等级level = logging.DEBUG
format日志输出格式
filename存储位置filename = 'd://back.log'
filemode输入模式filemode = "w"
format具体格式
格式符含义
%(levelname)s日志级别名称
%(pathname)s执行程序的路径
%(filename)s执行程序名
%(lineno)d日志的当前行号
%(asctime)s打印日志的时间
%(message)s日志信息
  • format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
  • (常用的格式)

代码

# coding:utf-8

import logging
import os


def init_log(path):
    if os.path.exists(path):
        mode = 'a'
    else:
        mode = 'w'
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s',
        filename=path,
        filemode=mode
    )
    return logging


current_path = os.getcwd()
path = os.path.join(current_path, 'back.log')
log = init_log(path)
# log = init_log()

log.info('这是第一个记录的日志信息')
log.warning('这是一个警告')
log.error('这是一个重大的错误信息')
log.debug('这是一个debug')

3 views

No comments yet. Be the first to comment.

More from this blog