日志书写方式

简易版

import logging
logging.basicConfig(
    # level=logging.DEBUG,
    level=30,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    filename=r'test.log',
)
logging.debug('调试模式')
logging.info('正常模式')
logging.warning('警告模式')
logging.error('错误信息')
logging.critical('严重错误信息')

标准版

import logging
#创建一个logging对象
logger = logging.getLogger()

#创建一个文件对象
fh = logging.FileHandler('标准版.log', encoding='utf-8')

#创建一个显示对象
sh = logging.StreamHandler()

#配置显示格式
formatter1 = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
formatter2 = logging.Formatter('%(asctime)s %(message)s')
fh.setFormatter(formatter1)
sh.setFormatter(formatter2)

logger.addHandler(fh)
logger.addHandler(sh)

#总开关
logger.setLevel(10)

fh.setLevel(10)
sh.setLevel(40)

logging.debug('调试模式')
logging.info('正常模式')
logging.warning('警告模式')
logging.error('错误信息')
logging.critical('严重错误信息')

旗舰版

import os
import logging.config
#定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
#结束

logfile_name = 'login.log' #文件名
logfile_path_staff = os.path.join(os.path.dirname(__name__), 'staff.log')
logfile_path_boss = os.path.join(os.path.dirname(__name__), 'boss.log')

#log配置字典
#LOGGING_DIC第一层的所有的键不能改变

LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,#固定写法
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
        'id_simple': {
            'format': id_simple_format
        }
    },
    'fileters': {},
    'handlers': {
        #打印到终端日志
        'sh': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'id_simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'fh': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path_staff,  # 日志文件
            'maxBytes': 5000,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8', #日志文件的编码,再也不用担心中文log乱码了
        },
        'boss':{
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path_staff,  # 日志文件
            'maxBytes': 5000,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8', #日志文件的编码,再也不用担心中文log乱码了
        },
    },
     'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['sh', 'fh', 'boss'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}


def md_logger():
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger()  # 生成一个log实例
    return logger
    # logger.debug('It works!')  # 记录该文件的运行状态

dic = {'username': 'Lz'}


def login():
    md_logger().info(f"{dic['username']}登陆成功")

login()

猜你喜欢

转载自www.cnblogs.com/dalaolz/p/11116438.html