Python使用logging模塊創(chuàng)建和處理.log文件的多種方法
在 Python 中創(chuàng)建和處理 .log 文件,推薦使用內(nèi)置的 logging 模塊。以下是完整的實(shí)現(xiàn)方案:
基礎(chǔ)版:創(chuàng)建單個(gè)日志文件
import logging
# 基本配置
logging.basicConfig(
filename='application.log', # 日志文件名
level=logging.DEBUG, # 記錄級(jí)別(DEBUG及以上都會(huì)記錄)
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# 使用日志
logging.debug('這是一條調(diào)試信息')
logging.info('程序正常啟動(dòng)')
logging.warning('磁盤(pán)空間不足50%')
logging.error('數(shù)據(jù)庫(kù)連接失敗')
進(jìn)階版:日志分時(shí)分割 (按日期)
from logging.handlers import TimedRotatingFileHandler
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# 創(chuàng)建按天分割的日志處理器
handler = TimedRotatingFileHandler(
'daily_log.log',
when='midnight', # 每天午夜分割
interval=1,
backupCount=7 # 保留最近7天的日志
)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# 使用日志
logger.info("這條日志會(huì)按天自動(dòng)分割")
專(zhuān)業(yè)版:多類(lèi)型日志處理器組合
import logging
from logging.handlers import RotatingFileHandler
# 創(chuàng)建不同處理器
debug_handler = RotatingFileHandler(
'debug.log',
maxBytes=1024*1024, # 1MB
backupCount=3
)
debug_handler.setLevel(logging.DEBUG)
error_handler = RotatingFileHandler(
'errors.log',
maxBytes=1024*1024,
backupCount=1
)
error_handler.setLevel(logging.ERROR)
# 創(chuàng)建帶顏色的控制臺(tái)輸出
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# 創(chuàng)建格式器
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
debug_handler.setFormatter(formatter)
error_handler.setFormatter(formatter)
console.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
# 配置根日志器
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
root_logger.addHandler(debug_handler)
root_logger.addHandler(error_handler)
root_logger.addHandler(console)
# 測(cè)試日志
logging.debug("開(kāi)發(fā)調(diào)試信息")
logging.info("用戶(hù)登錄成功")
logging.warning("接口響應(yīng)時(shí)間過(guò)長(zhǎng)")
logging.error("支付服務(wù)連接超時(shí)")
關(guān)鍵功能說(shuō)明
| 功能 | 實(shí)現(xiàn)方式 |
|---|---|
| 文件創(chuàng)建 | logging.basicConfig(filename='...') |
| 日志級(jí)別 | DEBUG < INFO < WARNING < ERROR < CRITICAL |
| 大小切割 | RotatingFileHandler |
| 日期切割 | TimedRotatingFileHandler |
| 格式定制 | logging.Formatter() 支持日期、進(jìn)程信息等 |
| 多輸出目標(biāo) | 添加多個(gè)處理器到日志器 |
高級(jí)功能
結(jié)構(gòu)化日志 (適合JSON格式)
import json
from logging import Formatter
class JsonFormatter(Formatter):
def format(self, record):
log_record = {
'time': self.formatTime(record),
'level': record.levelname,
'message': record.getMessage(),
'module': record.module
}
return json.dumps(log_record)
formatter = JsonFormatter()
日志過(guò)濾
class NoDebugFilter(logging.Filter):
def filter(self, record):
return record.levelno < logging.DEBUG
debug_handler.addFilter(NoDebugFilter())
日志管理最佳實(shí)踐
目錄結(jié)構(gòu)
project/ ├── logs/ │ ├── debug.log │ ├── info.log │ └── errors.log └── main.py
推薦配置
import os
from pathlib import Path
# 創(chuàng)建日志目錄
log_dir = Path('logs')
log_dir.mkdir(exist_ok=True)
# 主日志配置
logging.basicConfig(
level=logging.INFO,
handlers=[
RotatingFileHandler(log_dir/'app.log', maxBytes=10*1024*1024, backupCount=5),
logging.StreamHandler()
],
format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
)
環(huán)境區(qū)分
if os.getenv('FLASK_ENV') == 'development':
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.WARNING)
使用這些方法,您可以創(chuàng)建專(zhuān)業(yè)級(jí)的日志系統(tǒng),滿足從簡(jiǎn)單記錄到企業(yè)級(jí)應(yīng)用的各種需求。
以上就是Python使用logging模塊創(chuàng)建和處理.log文件的多種方法的詳細(xì)內(nèi)容,更多關(guān)于Python logging創(chuàng)建和處理.log文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解Python中的分支和循環(huán)結(jié)構(gòu)
這篇文章主要介紹了Python中的分支和循環(huán)結(jié)構(gòu),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02
基于python解線性矩陣方程(numpy中的matrix類(lèi))
這篇文章主要介紹了基于python解線性矩陣方程(numpy中的matrix類(lèi)),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
python實(shí)現(xiàn)ID3決策樹(shù)算法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)ID3決策樹(shù)算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
非常全面的Python常見(jiàn)基礎(chǔ)面試題及答案
Python是目前編程領(lǐng)域最受歡迎的語(yǔ)言,Python可用于許多領(lǐng)域,Web應(yīng)用程序開(kāi)發(fā),自動(dòng)化,數(shù)學(xué)建模,大數(shù)據(jù)應(yīng)用程序等等,這篇文章主要給大家介紹了關(guān)于Python常見(jiàn)基礎(chǔ)面試題及答案的相關(guān)資料,需要的朋友可以參考下2021-09-09
python實(shí)現(xiàn)請(qǐng)求數(shù)據(jù)包簽名
這篇文章主要介紹了python實(shí)現(xiàn)請(qǐng)求數(shù)據(jù)包簽名,主要以python怎么快速對(duì)請(qǐng)求體做一次簽名為主題,塑造實(shí)現(xiàn)請(qǐng)求數(shù)據(jù)包簽名過(guò)程,具有一定得參考價(jià)值,需要的小伙伴可以參考一下2022-02-02
分享十個(gè)Python提高工作效率的自動(dòng)化腳本
在這個(gè)自動(dòng)化時(shí)代,我們有很多重復(fù)無(wú)聊的工作要做。 想想這些你不再需要一次又一次地做的無(wú)聊的事情,讓它自動(dòng)化,讓你的生活更輕松。本文分享了10個(gè)Python自動(dòng)化腳本,希望對(duì)大家有所幫助2022-10-10

