网站首页 > 技术文章 正文
Python项目中记录日志及异常捕获
推荐使用 loguru,pip install loguru
Loguru是一个旨在以Python带来令人愉悦的日志记录的库。Loguru的主要概念是只有一个 logger。没有 Handler, 没有 Formatter, 没有Filter只有一个add函数。循环、保留、压缩、异常捕获、结构化日志、解析器、异步、线程安全、多线程安全...好处多多。
loguru旨在通过添加一系列有用的功能来解决标准记录器的注意事项,从而减少 Python 日志记录的痛苦。
详细可参考:https://loguru.readthedocs.io/en/stable/api/logger.html
loguru基础功能测试
运行后,test.log不断增大,当达到设置的上限大小后,比如1 MB,则会按照其规则进行打包,例如:test.2022-09-07_02-48-34_016556.log.tar.gz
main.py
from loguru import logger
if __name__ == '__main__':
log_path_file = "./test.log"
logger.add(log_path_file,
# Automatically rotate too big file
# for example:"10 MB"、"0.5 GB"、"1 month 2 weeks"、"4 days"、"10h"、"18:00"...
rotation="1 MB",
# Cleanup after some time
# for example: "10 days"、"1 week, 3 days"、"2 months"、"1 minutes"...
retention="1 minutes",
encoding="utf-8",
# Asynchronous, Thread-safe, Multiprocess-safe
enqueue=True,
# Save some loved space
# for example: "gz", "bz2", "xz", "lzma", "tar", "tar.gz", "tar.bz2", "tar.xz", "zip".
compression="tar.gz")
# 日志滚动测试
while 1:
logger.debug("This's a log message")
logger.info("你好世界")
logger.error("hello world")
flask基础loguru实现日志记录及异常捕获
main.py
from flask import Flask, jsonify, request, g
from flask_cors import *
import os, traceback, time
from loguru import logger
log_path = f"../logs"
if not os.path.exists(log_path):
os.makedirs(log_path)
t = time.strftime("%Y_%m_%d")
log_path_file = f"{log_path}/interface_log_{t}.log"
def setup_logging():
logger.add(log_path_file,
rotation="10 MB",
retention="90 days",
encoding="utf-8",
enqueue=True,
level='INFO',
compression="tar.gz")
setup_logging()
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app, supports_cordentials=True)
@app.before_request
def before_request_middle_req():
try:
g.start_time = time.time()
url_method = request.method.upper()
url_str = request.url
if 'OPTIONS' == url_method:
return None
logger.info(f'(starting:)server receive,url={url_str},method={url_method}')
except Exception as e:
logger.error(f'请求异常:{e.__dict__},traceback={traceback.format_exc()}')
resultObj = {'code': 900, 'message': 'request error'}
return jsonify(resultObj)
@app.after_request
def after_request_middle_req(response):
url_str = request.url
url_method = request.method.upper()
if 'OPTIONS' == url_method:
return response
if "start_time" not in g:
return response
request_duration = round((time.time() - g.start_time) * 1000, 2)
logger.info(f"(statistics:)"
f"method={url_method}"
f" path={request.path} status={response.status_code}"
f" duration={request_duration}ms")
return response
@app.route('/test', methods=['POST', 'GET'])
def test():
try:
resultObj = {'code': 0, 'message': 'success'}
return jsonify(resultObj)
except Exception as e:
logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
resultObj = {'code': 1000, 'message': 'Service running exception'}
return jsonify(resultObj)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=False)
- 上一篇: [编程基础] Python日志记录库logging总结
- 下一篇: 这样处理Python日志,优雅!
猜你喜欢
- 2025-01-21 [819]ScalersTalk成长会Python小组第10周学习训练日志
- 2025-01-21 使用Python操作Jenkins(创建,构建,获取Job日志和报告)
- 2025-01-21 「python小脚本」监听日志文件异常数据发送告警短信
- 2025-01-21 告别千篇一律,Python打印彩色日志的方法!
- 2025-01-21 用Python写一个MacOS的系统通知
- 2025-01-21 Python 自制日志装饰器
- 2025-01-21 Python如何在日志中隐藏明文密码
- 2025-01-21 Kubernetes日志采集ELK|收集Python项目日志并展示
- 2025-01-21 Python接口自动化核心模块 - 数据库操作和日志
- 2025-01-21 python模块之 loguru 日志模块
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)