python logging模块书写日志以及日志分割详解

yipeiwu_com6年前Python基础

本文范例是书写两个日志:错误日志(ERROR级别)和运行日志(DEBUG级别),其中运行日志每日凌晨进行分割

import logging,datetime,logging.handlers
from conf import settings
 
if __name__ == "__main__":
  #两个日志,错误日志和运行日志,输出文件路径及文件名
  error_log = settings.ERROR_LOG_FILE
  run_log = settings.RUN_LOG_FILE
 
  logger = logging.getLogger("mylog")
  logger.setLevel(logging.DEBUG)
 
  DATE_FORMAT = "%Y-%m-%d %H:%M:%S %p"
  LOG_FORMAT = "%(asctime)s------%(levelname)s[:%(lineno)d]-------%(message)s"
  #第一种普通写法
  #file_run_log = logging.FileHandler(run_log)
  #假如需要每日凌晨进行日志切割,注意导入模块时需要导入logging.handlers,否则报错
  #when参数可以设置S M H D,分别是秒、分、小时、天分割,也可以按周几分割,也可以凌晨分割
  file_run_log = rf_handler = logging.handlers.TimedRotatingFileHandler(run_log, when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
 
  file_error_log = logging.FileHandler(error_log)
 
  file_run_log.setLevel(level=logging.INFO)
  file_run_log.setFormatter(logging.Formatter(LOG_FORMAT))
  file_error_log.setLevel(level=logging.ERROR)
  file_error_log.setFormatter(logging.Formatter(LOG_FORMAT))
 
  logger.addHandler(file_run_log)
  logger.addHandler(file_error_log)
 
  logger.info("info test")
  logger.error("error test")
  logger.critical("critical test")
 
 
 
  #普通全局写法
  # logging.basicConfig(level=logging.DEBUG,filename=run_log,format=LOG_FORMAT,datefmt=DATE_FORMAT)
 
  # logging.info("this is a log")
  # logging.warning("this is warning")

settings.py:

ERROR_LOG_FILE = os.path.join(BASE_DIR,"log","error.log")
RUN_LOG_FILE = os.path.join(BASE_DIR,"log","run.log")

日志输出结果run.log:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现对象转换为xml的方法示例

本文实例讲述了Python实现对象转换为xml的方法。分享给大家供大家参考,具体如下: # -*- coding:UTF-8 -*- ''''' Created on 2010-4-...

python assert的用处示例详解

使用assert断言是学习python一个非常好的习惯,python assert 断言句语格式及用法很简单。在没完善一个程序之前,我们不知道程序在哪里会出错,与其让它在运行最崩溃,不如...

python将控制台输出保存至文件的方法

很多时候在Linux系统下运行python程序时,控制台会输出一些有用的信息。为了方便保存这些信息,有时需要对这些信息进行保存。这里介绍几种将控制台输出保存到文件中的方式: 1 重定向标...

用TensorFlow实现多类支持向量机的示例代码

用TensorFlow实现多类支持向量机的示例代码

本文将详细展示一个多类支持向量机分类器训练iris数据集来分类三种花。 SVM算法最初是为二值分类问题设计的,但是也可以通过一些策略使得其能进行多类分类。主要的两种策略是:一对多(one...

Windows平台Python连接sqlite3数据库的方法分析

本文实例讲述了Windows平台Python连接sqlite3数据库的方法。分享给大家供大家参考,具体如下: 之前没有接触过sqlite数据库,只是听到同事聊起这个。 有一次,手机端同事...