python记录日志logging

版本一:只能输出屏幕和文件二选一

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("调试信息")   #10
logging.info("正常信息")    #20
logging.warning("警告信息") #30
logging.error("错误信息")   #40
logging.critical("严重问题")#50

# def fun():
#     logging.debug("正常调试")
#     print("aaa")
#     logging.debug("正常调试")
#
# fun()

#用法:
try:
    i = input("请输入选项:")
    int(i)
except Exception as e:
    logging.error(e)

版本二:

import logging

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

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

#创建一个屏幕对象
sh = logging.StreamHandler()

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

fh.setFormatter(formatter)  #文件格式
sh.setFormatter(formatter)  #屏幕格式

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

#设置总开关
logger.setLevel(30)

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


logging.debug("调试信息")   #10
logging.info("正常信息")    #20
logging.warning("警告信息") #30
logging.error("错误信息")   #40
logging.critical("严重问题")#50

版本三:

import logging.config

#定义日志格式
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

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

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

#定义日志输出格式
logfile_name = 'log1.log'
logfile_path = r'C:\Users\lg\Desktop\study\Python\python对象\log1.log'

#log配置字典
#LOGGING_DIC第一层所有的键不能改变
LOGGING_DIC = {
    
    
    'version':1,  #版本号固定
    'disable_existing_loggers':False, #固定写法
    'formatters':{
    
    
        'standard':{
    
    
            'format':standard_format
        },
        'simple':{
    
    
            'simple':simple_format,
        },
    },
    'filters':{
    
    },
    'handlers':{
    
    
        #打印到终端的日志
        'sh':{
    
    
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  #打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志
        'fh':{
    
    
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',   # 保存到文件
            'formatter': 'standard',
            'filename':logfile_path,
            'maxBytes': 1024*1024*5,   #日志大小5M
            'backupCount': 5,
            'encoding': 'utf-8',  #日志文件编码
        },
    },
    'loggers':{
    
    
       #logging.getLogger()拿到的logger配置
        '':{
    
    
            'handlers':['sh','fh'], #这里把上面定义的两个handler都加上,即log数据又写入文件又打印到屏幕
            'level':'DEBUG',  #总开关
            'propagete': True,  #向上(更高level的logger)传递
        },
    },
}

def md_logger(a='购物车'):
    logging.config.dictConfig(LOGGING_DIC)  #导入上面定义的logging配置
    logger = logging.getLogger(a)
    return logger
    # logger.debug('it works!')

dic = {
    
    
    'username':'lg'
}

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


login()

猜你喜欢

转载自blog.csdn.net/qq_37369726/article/details/117323400