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处理excel绘制雷达图

本文实例为大家分享了python处理excel绘制雷达图的具体代码,供大家参考,具体内容如下 python处理excel制成雷达图,利用工具plotly在线生成,事先要安装好xlrd组件...

python中时间转换datetime和pd.to_datetime详析

python中时间转换datetime和pd.to_datetime详析

前言 我们在python对数据进行操作时,经常会选取某一时间段的数据进行分析。这里为大家介绍两个我经常用到的用来选取某一时间段数据的函数:datetime( )和pd.to_dateti...

Python 字符串转换为整形和浮点类型的方法

Python2.6 之前:字符串转换为整形和浮点型 >>>import string >>>string.atoi('34.1') 34 &...

Python中dict和set的用法讲解

Python中dict和set的用法讲解

dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 举个例子,假设要...

python配置文件写入过程详解

python配置文件有.conf,.ini,.txt等多种 python集成的 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件 我的配置文件如下 [M...