python 输出日志到文件,删除过期文件

参考:python logging模块按日期打印日志,并删除过期的日志

官方:15.7. logging --- Logging facility for Python --- Python 2.7.18 documentation

一 简单日志打印:

import logging

python 复制代码
logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename='/home/URL/client/test_log.log',
                        filemode='a')

logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数:

filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。

filemode:文件打开方式,在指定了filename时使用这个参数,默认值为"a"还可指定为"w"。

format:指定handler使用的日志显示格式。

datefmt:指定日期时间格式。

level:设置rootlogger; 默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET)

stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:

%(name)s Logger的名字

%(levelno)s 数字形式的日志级别

%(levelname)s 文本形式的日志级别

%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有

%(filename)s 调用日志输出函数的模块的文件名

%(module)s 调用日志输出函数的模块名

%(funcName)s 调用日志输出函数的函数名

%(lineno)d 调用日志输出函数的语句所在的代码行

%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示

%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数

%(asctime)s 字符串形式的当前时间。默认格式是 "2003-07-08 16:49:45,896"。逗号后面的是毫秒

%(thread)d 线程ID。可能没有

%(threadName)s 线程名。可能没有

%(process)d 进程ID。可能没有

%(message)s用户输出的消息

二,只输出到文件不在ternimal打印

python 复制代码
import logging
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler

def log_init():
    log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
    formatter = logging.Formatter(log_fmt)
    log_file_handler = TimedRotatingFileHandler(filename=LOG_PATH+"thread_", when="D", interval=1, backupCount=7)
    log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
    log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
    log_file_handler.setFormatter(formatter)
    log_file_handler.setLevel(logging.DEBUG)
    log = logging.getLogger()
    log.addHandler(log_file_handler)
   '''
   程序运行
   '''
   #removeHandler 要放在程序运用打印日志的后面
    log.removeHandler(log_file_handler)()

结果是每天生成一个日志文件,保留最近7天的日志文件。

when:是一个字符串,用于描述滚动周期的基本单位,字符串的值及意义如下:

"S": Seconds

"M": Minutes

"H": Hours

"D": Days

"W": Week day (0=Monday)

"midnight": Roll over at midnight

interval: 滚动周期,单位有when指定,比如:when='D',interval=1,表示每天产生一个日志文件;

backupCount: 表示日志文件的保留个数;

删除日志文件设置:

log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"

log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")

suffix和extMatch的格式要相对应,Year-4位,m-2位 以此类推

三、既输出到文件,又打印到terminal

python 复制代码
def initLogging(logFilename):
   
    logging.basicConfig(
                    level    = logging.DEBUG,
                    format   = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s',
                    datefmt  = '%a, %d %b %Y %H:%M:%S',
                    filename = logFilename,
                    filemode = 'w');
  
    console = logging.StreamHandler();
    console.setLevel(logging.INFO);
    formatter = logging.Formatter('LINE %(lineno)-4d : %(levelname)-8s %(message)s');
    console.setFormatter(formatter);
    logging.getLogger('').addHandler(console);

通过logging.StreamHandler()函数来打印到terminal

相关推荐
xqqxqxxq7 分钟前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python
GISer_Jing14 分钟前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
最晚的py18 分钟前
Python抓取ZLibrary元数据
爬虫·python
咖啡续命又一天19 分钟前
Trae CN IDE 中 Python 开发的具体流程和配置总结
开发语言·ide·python·ai编程
明远湖之鱼42 分钟前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长1 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs1 小时前
Nginx核心架构设计
运维·前端·nginx
IT·小灰灰2 小时前
告别“翻墙“烦恼:DMXAPI让Gemini-3-pro-thinking调用快如闪电
网络·人工智能·python·深度学习·云计算
雪球工程师团队2 小时前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程