python logging模塊的使用總結(jié)
日志級(jí)別
- CRITICAL 50
- ERROR 40
- WARNING 30
- INFO 20
- DEBUG 10
logging.basicConfig()函數(shù)中的具體參數(shù)含義
- filename:指定的文件名創(chuàng)建FiledHandler,這樣日志會(huì)被存儲(chǔ)在指定的文件中;
- filemode:文件打開方式,在指定了filename時(shí)使用這個(gè)參數(shù),默認(rèn)值為“w”還可指定為“a”;
- format:指定handler使用的日志顯示格式;
- datefmt:指定日期時(shí)間格式。,格式參考strftime時(shí)間格式化(下文)
- level:設(shè)置rootlogger的日志級(jí)別
- stream:用指定的stream創(chuàng)建StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者文件,默認(rèn)為sys.stderr。若同時(shí)列出了filename和stream兩個(gè)參數(shù),則stream參數(shù)會(huì)被忽略。
format參數(shù)用到的格式化信息
| 參數(shù) | 描述 |
|---|---|
| %(name)s | Logger的名字 |
| %(levelno)s | 數(shù)字形式的日志級(jí)別 |
| %(levelname)s | 文本形式的日志級(jí)別 |
| %(pathname)s | 調(diào)用日志輸出函數(shù)的模塊的完整路徑名,可能沒有 |
| %(filename)s | 調(diào)用日志輸出函數(shù)的模塊的文件名 |
| %(module)s | 調(diào)用日志輸出函數(shù)的模塊名 |
| %(funcName)s | 調(diào)用日志輸出函數(shù)的函數(shù)名 |
| %(lineno)d | 調(diào)用日志輸出函數(shù)的語句所在的代碼行 |
| %(created)f | 當(dāng)前時(shí)間,用UNIX標(biāo)準(zhǔn)的表示時(shí)間的浮 點(diǎn)數(shù)表示 |
| %(relativeCreated)d | 輸出日志信息時(shí)的,自Logger創(chuàng)建以 來的毫秒數(shù) |
| %(asctime)s | 字符串形式的當(dāng)前時(shí)間。默認(rèn)格式是 “2003-07-08 16:49:45,896”。逗號(hào)后面的是毫秒 |
| %(thread)d | 線程ID??赡軟]有 |
| %(threadName)s | 線程名??赡軟]有 |
| %(process)d | 進(jìn)程ID??赡軟]有 |
| %(message)s | 用戶輸出的消息 |
使用logging打印日志到標(biāo)準(zhǔn)輸出
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
使用logging.baseConfig()將日志輸入到文件
import os
logging.basicConfig(
filename=os.path.join(os.getcwd(),'all.log'),
level=logging.DEBUG,
format='%(asctime)s %(filename)s : %(levelname)s %(message)s', # 定義輸出log的格式
filemode='a',
datefmt='%Y-%m-%d %A %H:%M:%S',
)
logging.debug('this is a message')
自定義Logger
設(shè)置按照日志文件大小自動(dòng)分割日志寫入文件
import logging
from logging import handlers
class Logger(object):
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
}
def __init__(self, filename, level='info', when='D', backCount=3,
fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
self.logger = logging.getLogger(filename)
format_str = logging.Formatter(fmt) # 設(shè)置日志格式
self.logger.setLevel(self.level_relations.get(level)) # 設(shè)置日志級(jí)別
# 向控制臺(tái)輸出日志
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(format_str)
self.logger.addHandler(stream_handler)
# 日志按文件大小寫入文件
# 1MB = 1024 * 1024 bytes
# 這里設(shè)置文件的大小為500MB
rotating_file_handler = handlers.RotatingFileHandler(
filename=filename, mode='a', maxBytes=1024 * 1024 * 500, backupCount=5, encoding='utf-8')
rotating_file_handler.setFormatter(format_str)
self.logger.addHandler(rotating_file_handler)
log = Logger('all.log', level='info')
log.logger.info('[測(cè)試log] hello, world')
按照間隔日期自動(dòng)生成日志文件
import logging
from logging import handlers
class Logger(object):
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
}
def __init__(self, filename, level='info', when='D', backCount=3,
fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
self.logger = logging.getLogger(filename)
format_str = logging.Formatter(fmt) # 設(shè)置日志格式
self.logger.setLevel(self.level_relations.get(level)) # 設(shè)置日志級(jí)別
# 往文件里寫入
# 指定間隔時(shí)間自動(dòng)生成文件的處理器
timed_rotating_file_handler = handlers.TimedRotatingFileHandler(
filename=filename, when=when, backupCount=backCount, encoding='utf-8')
# 實(shí)例化TimedRotatingFileHandler
# interval是時(shí)間間隔,backupCount是備份文件的個(gè)數(shù),如果超過這個(gè)個(gè)數(shù),就會(huì)自動(dòng)刪除,when是間隔的時(shí)間單位,單位有以下幾種:
# S 秒
# M 分
# H 小時(shí)、
# D 天、
# W 每星期(interval==0時(shí)代表星期一)
# midnight 每天凌晨
timed_rotating_file_handler.setFormatter(format_str) # 設(shè)置文件里寫入的格式
self.logger.addHandler(timed_rotating_file_handler)
# 往屏幕上輸出
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(format_str)
self.logger.addHandler(stream_handler)
log = Logger('all.log', level='info')
log.logger.info('[測(cè)試log] hello, world')
logging 模塊在Flask中的使用
我在使用Flask的過程中看了很多Flask關(guān)于logging的文檔,但使用起來不是很順手,于是自己就根據(jù)Flask的官方文檔寫了如下的log模塊,以便集成到Flask中使用。
restful api 項(xiàng)目目錄:
. ├── apps_api │ ├── common │ ├── models │ └── resources ├── logs ├── migrations │ └── versions ├── static ├── templates ├── test └── utils └── app.py └── config.py └── exts.py └── log.py └── manage.py └── run.py └── README.md └── requirements.txt
log.py 文件
# -*- coding: utf-8 -*-
import logging
from flask.logging import default_handler
import os
from logging.handlers import RotatingFileHandler
from logging import StreamHandler
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_PATH = os.path.join(BASE_DIR, 'logs')
LOG_PATH_ERROR = os.path.join(LOG_PATH, 'error.log')
LOG_PATH_INFO = os.path.join(LOG_PATH, 'info.log')
LOG_PATH_ALL = os.path.join(LOG_PATH, 'all.log')
# 日志文件最大 100MB
LOG_FILE_MAX_BYTES = 100 * 1024 * 1024
# 輪轉(zhuǎn)數(shù)量是 10 個(gè)
LOG_FILE_BACKUP_COUNT = 10
class Logger(object):
def init_app(self, app):
# 移除默認(rèn)的handler
app.logger.removeHandler(default_handler)
formatter = logging.Formatter(
'%(asctime)s [%(thread)d:%(threadName)s] [%(filename)s:%(module)s:%(funcName)s] '
'[%(levelname)s]: %(message)s'
)
# 將日志輸出到文件
# 1 MB = 1024 * 1024 bytes
# 此處設(shè)置日志文件大小為500MB,超過500MB自動(dòng)開始寫入新的日志文件,歷史文件歸檔
file_handler = RotatingFileHandler(
filename=LOG_PATH_ALL,
mode='a',
maxBytes=LOG_FILE_MAX_BYTES,
backupCount=LOG_FILE_BACKUP_COUNT,
encoding='utf-8'
)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
stream_handler = StreamHandler()
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging.INFO)
for logger in (
# 這里自己還可以添加更多的日志模塊,具體請(qǐng)參閱Flask官方文檔
app.logger,
logging.getLogger('sqlalchemy'),
logging.getLogger('werkzeug')
):
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
在exts.py擴(kuò)展文件中添加log模塊
# encoding: utf-8 from log import Logger logger = Logger()
在app.py 文件中引入logger模塊,這個(gè)文件是create_app的工廠模塊。
# encoding: utf-8
from flask import Flask
from config import CONFIG
from exts import logger
def create_app():
app = Flask(__name__)
# 加載配置
app.config.from_object(CONFIG)
# 初始化logger
logger.init_app(app)
return app
運(yùn)行run.py
# -*- coding: utf-8 -*- from app import create_app app = create_app() if __name__ == '__main__': app.run()
$ python run.py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on 2019-07-08 08:15:50,396 [140735687508864:MainThread] [_internal.py:_internal:_log] [INFO]: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 2019-07-08 08:15:50,397 [140735687508864:MainThread] [_internal.py:_internal:_log] [INFO]: * Restarting with stat 2019-07-08 08:15:50,748 [140735687508864:MainThread] [_internal.py:_internal:_log] [WARNING]: * Debugger is active! 2019-07-08 08:15:50,755 [140735687508864:MainThread] [_internal.py:_internal:_log] [INFO]: * Debugger PIN: 234-828-739
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
跟老齊學(xué)Python之?dāng)?shù)據(jù)類型總結(jié)
前面已經(jīng)洋洋灑灑地介紹了不少數(shù)據(jù)類型。不能再不顧一切地向前沖了,應(yīng)當(dāng)總結(jié)一下。這樣讓看官能夠從總體上對(duì)這些數(shù)據(jù)類型有所了解,如果能夠有一覽眾山小的感覺,就太好了。2014-09-09
關(guān)于scipy.optimize函數(shù)使用及說明
這篇文章主要介紹了關(guān)于scipy.optimize函數(shù)使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
python實(shí)現(xiàn)爬取百度圖片的方法示例
這篇文章主要介紹了python實(shí)現(xiàn)爬取百度圖片的方法,涉及Python基于requests、urllib等模塊的百度圖片抓取相關(guān)操作技巧,需要的朋友可以參考下2019-07-07
python使用numpy按一定格式讀取bin文件的實(shí)現(xiàn)
這篇文章主要介紹了python使用numpy按一定格式讀取bin文件的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05

