8,python 日志和异常

2021/10/24 17:13:26

本文主要是介绍8,python 日志和异常,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

python 日志模块
[root@centos7 ~]# cat a.py 
#! /usr/bin/python3

#filename:日志文件名
#format: 时间-名称-级别-模块:错误信息
#datefmt:时间格式


import logging  # 引入logging模块
logging.basicConfig(filename='acc1.log',
		format='%(asctime)s - %(name)s: %(levelname)s - %(module)s:  %(message)s',
		datefmt='%F-%m-%d %H:%M:%S',
		level=0 # 当前配置表示0以上的分数会写入文件	
		)

logging.debug('This is a debug message.') # debug的level 10
logging.info('This is an info message.')  # info的level 20
logging.warning('This is a warning message.') # warning的level 30
logging.error('This is an error message.')   # error的level 40
logging.critical('This is a critical message.') # critical的level 50
logging.log(2,"我是自定义")
[root@centos7 ~]# 

 

日志分文件记录

[root@centos7 ~]# cat b.py 
#! /usr/bin/python3

#如果系统中需要把日志文件分开,比如一个大系统,有2个系统,A系统,B系统需要分开记录日志,那怎么办呢?
#basicConfig 是搞不定的,我们需要借助文件助手(FileHandler),来帮我们完成日志的分开记录

import logging

# 创建一个操作日志的对象logger (依赖FileHandler)
file_handler = logging.FileHandler('l1.log','a',encoding='utf-8')  #类似  f = open() a:追加
file_handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s: %(levelname)s - %(module)s:  %(message)s'))

logger1 =logging.Logger('财务系统',level=40) #创建日志对象
logger1.addHandler(file_handler) #给日志对象设置文件信息


# 再创建一个操作日志的对象logger(依赖FileHandler)
file_handler2 = logging.FileHandler('l2.log','a',encoding='utf-8')
file_handler2.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s: %(levelname)s - %(module)s:  %(message)s'))

logger2 =logging.Logger('会计系统',level=logging.ERROR)
logger2.addHandler(file_handler2)

#项目1:财务系统出错了
logger1.error('财务系统炸了,程序员出来工作了')
#项目2:会计系统出错了
logger2.error('会计系统炸了,程序员出来工作了')
[root@centos7 ~]# 

 

异常处理

[root@centos7 ~]# cat c.py 
#! /usr/bin/python3

import traceback

try:
	print(1/0)
except:
	print('出错了')
	print(traceback.format_exc()) #错误信息就能看到了	
[root@centos7 ~]# 

 

日志记录异常

[root@centos7 ~]# cat d.py 
#! /usr/bin/python3
import logging
import traceback
#准备好记录日志的logging
logging.basicConfig(filename='acc2.log',
		format='%(asctime)s - %(name)s: %(levelname)s - %(module)s:  %(message)s',
		datefmt='%F-%m-%d %H:%M:%S',
		level=0 # 当前配置表示0以上的分数会写入文件	
		)

try:
	print(1/0)
except:
	print('出错了')
	logging.error(traceback.format_exc())
[root@centos7 ~]# 

  

 



这篇关于8,python 日志和异常的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程