python--logging日志
Posted 点影
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python--logging日志相关的知识,希望对你有一定的参考价值。
日志记录器级别:严重、错误、警告、信息、调试
logger模块用于记录log信息,使用前请导包import logger。
例一、
1、超级简单版logger.py:
def log_message(msg): with open("test.log",\'a+\') as log_file: log_file.write("{0}\\n".format(msg))
2、新建一个main_script.py文件引入logger.py日志记录器
import logger for i in range(4): logger.log_message("log message {}".format(i))
3、运行后生成日志,没有日志级别的日志不是好日志,日志信息如下:
log message 0 log message 1 log message 2 log message 3
4、logger.py文件修改
def critical(msg): with open("test.log",\'a+\') as log_file: log_file.write("[CRITICAL]{0}\\n".format(msg)) def error(msg): with open("test.log",\'a+\') as log_file: log_file.write("[ERROR]{0}\\n".format(msg)) def warn(msg): with open("test.log",\'a+\') as log_file: log_file.write("[WARN]{0}\\n".format(msg)) def info(msg): with open("test.log",\'a+\') as log_file: log_file.write("[INFO]{0}\\n".format(msg)) def debug(msg): with open("test.log",\'a+\') as log_file: log_file.write("[DEBUG]{0}\\n".format(msg))
5、新建一个py文件,test_error_log.py
import logger try: a = 1/0 except: logger.error("something went wront")
6、运行test_error_log.py程序后查看log日志,
[ERROR]something went wron
7、logging第三方模块pip安装后可以这样用
import logging # 引入logging模块 import os.path import time # 第一步,创建一个logger logger = logging.getLogger() logger.setLevel(logging.INFO) # Log等级总开关 # 第二步,创建一个handler,用于写入日志文件 rq = time.strftime(\'%Y%m%d%H%M\', time.localtime(time.time())) log_path = os.path.dirname(os.getcwd()) + \'/Logs/\' log_name = log_path + rq + \'.log\' logfile = log_name fh = logging.FileHandler(logfile, mode=\'w\') fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关 # 第三步,定义handler的输出格式 formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s") fh.setFormatter(formatter) # 第四步,将logger添加到handler里面 logger.addHandler(fh) # 日志 logger.debug(\'this is a logger debug message\') logger.info(\'this is a logger info message\') logger.warning(\'this is a logger warning message\') logger.error(\'this is a logger error message\') logger.critical(\'this is a logger critical message\')
以上是关于python--logging日志的主要内容,如果未能解决你的问题,请参考以下文章