亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python logging模塊的使用總結(jié)

 更新時間:2019年07月09日 08:25:32   作者:DeaconOne  
這篇文章主要介紹了python logging模塊使用總結(jié)以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。,需要的朋友可以參考下

日志級別

  • CRITICAL 50
  • ERROR 40
  • WARNING 30
  • INFO 20
  • DEBUG 10

logging.basicConfig()函數(shù)中的具體參數(shù)含義

  • filename:指定的文件名創(chuàng)建FiledHandler,這樣日志會被存儲在指定的文件中;
  • filemode:文件打開方式,在指定了filename時使用這個參數(shù),默認(rèn)值為“w”還可指定為“a”;
  • format:指定handler使用的日志顯示格式;
  • datefmt:指定日期時間格式。,格式參考strftime時間格式化(下文)
  • level:設(shè)置rootlogger的日志級別
  • stream:用指定的stream創(chuàng)建StreamHandler??梢灾付ㄝ敵龅絪ys.stderr,sys.stdout或者文件,默認(rèn)為sys.stderr。若同時列出了filename和stream兩個參數(shù),則stream參數(shù)會被忽略。

format參數(shù)用到的格式化信息

參數(shù) 描述
%(name)s Logger的名字
%(levelno)s 數(shù)字形式的日志級別
%(levelname)s 文本形式的日志級別
%(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)前時間,用UNIX標(biāo)準(zhǔn)的表示時間的浮 點(diǎn)數(shù)表示
%(relativeCreated)d 輸出日志信息時的,自Logger創(chuàng)建以 來的毫秒數(shù)
%(asctime)s 字符串形式的當(dāng)前時間。默認(rèn)格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒
%(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è)置按照日志文件大小自動分割日志寫入文件

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è)置日志級別

    # 向控制臺輸出日志
    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('[測試log] hello, world')

按照間隔日期自動生成日志文件

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è)置日志級別

    # 往文件里寫入
    # 指定間隔時間自動生成文件的處理器
    timed_rotating_file_handler = handlers.TimedRotatingFileHandler(
      filename=filename, when=when, backupCount=backCount, encoding='utf-8')

    # 實例化TimedRotatingFileHandler
    # interval是時間間隔,backupCount是備份文件的個數(shù),如果超過這個個數(shù),就會自動刪除,when是間隔的時間單位,單位有以下幾種:
    # S 秒
    # M 分
    # H 小時、
    # D 天、
    # W 每星期(interval==0時代表星期一)
    # 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('[測試log] hello, world')

logging 模塊在Flask中的使用
我在使用Flask的過程中看了很多Flask關(guān)于logging的文檔,但使用起來不是很順手,于是自己就根據(jù)Flask的官方文檔寫了如下的log模塊,以便集成到Flask中使用。

restful api 項目目錄:

.
├── 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 個
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自動開始寫入新的日志文件,歷史文件歸檔
    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 (
        # 這里自己還可以添加更多的日志模塊,具體請參閱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模塊,這個文件是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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python對文檔中元素刪除,替換操作

    python對文檔中元素刪除,替換操作

    這篇文章主要介紹了python對文檔中元素刪除,替換操作,pthon更換文檔中某元素、python改變或者刪除txt文檔中某一列元素,下文具體代碼實現(xiàn)需要的小伙伴可以參考一下
    2022-04-04
  • python和C語言混合編程實例

    python和C語言混合編程實例

    這篇文章主要介紹了python和C語言混合編程實例,文中開發(fā)了一個tcp端口ping程序來介紹混合編程,需要的朋友可以參考下
    2014-06-06
  • Python 正則表達(dá)式大全(推薦)

    Python 正則表達(dá)式大全(推薦)

    正則表達(dá)式是對字符串操作的一種邏輯公式,正則表達(dá)式是一種文本模式,該模式描述在搜索文本時要匹配的一個或多個字符串。本文重點(diǎn)給大家介紹Python 正則表達(dá)式大全,感興趣的朋友一起看看吧
    2021-11-11
  • PYcharm 激活方法(推薦)

    PYcharm 激活方法(推薦)

    這篇文章主要介紹了PYcharm 激活方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • 跟老齊學(xué)Python之?dāng)?shù)據(jù)類型總結(jié)

    跟老齊學(xué)Python之?dāng)?shù)據(jù)類型總結(jié)

    前面已經(jīng)洋洋灑灑地介紹了不少數(shù)據(jù)類型。不能再不顧一切地向前沖了,應(yīng)當(dāng)總結(jié)一下。這樣讓看官能夠從總體上對這些數(shù)據(jù)類型有所了解,如果能夠有一覽眾山小的感覺,就太好了。
    2014-09-09
  • python讀取csv文件示例(python操作csv)

    python讀取csv文件示例(python操作csv)

    這篇文章主要介紹了python讀取csv文件示例,這個示例簡單說明了一下python操作csv的方法,需要的朋友可以參考下
    2014-03-03
  • 關(guān)于scipy.optimize函數(shù)使用及說明

    關(guān)于scipy.optimize函數(shù)使用及說明

    這篇文章主要介紹了關(guān)于scipy.optimize函數(shù)使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • python實現(xiàn)爬取百度圖片的方法示例

    python實現(xiàn)爬取百度圖片的方法示例

    這篇文章主要介紹了python實現(xiàn)爬取百度圖片的方法,涉及Python基于requests、urllib等模塊的百度圖片抓取相關(guān)操作技巧,需要的朋友可以參考下
    2019-07-07
  • python使用numpy按一定格式讀取bin文件的實現(xiàn)

    python使用numpy按一定格式讀取bin文件的實現(xiàn)

    這篇文章主要介紹了python使用numpy按一定格式讀取bin文件的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Flask框架編寫文件下載接口過程講解

    Flask框架編寫文件下載接口過程講解

    這篇文章主要介紹了Flask框架編寫文件下載接口的過程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-01-01

最新評論