首先放置gunicorn的官方文檔地址:http://docs.gunicorn.org/en/latest/settings.html#accesslog
Gunicorn“綠色獨角獸”是一個被廣泛使用的高性能的Python WSGI UNIX HTTP服務器,移植自Ruby的獨角獸(Unicorn )項目,使用pre-fork worker模式,具有使用非常簡單,輕量級的資源消耗,以及高性能等特點。
安裝gunicorn
$ sudo apt-get update
$ sudo apt-get install gunicorn
運行gunicorn:
$ gunicorn [OPTIONS] 模塊名:變量名
模塊名是python文件名,可以是完整的路徑+python文件名;變量名是python文件中可調用的WSGI(Web Server Gateway ).
示例:
# filename:test.py
def app(environ, start_response):
"""Simplest possible application object"""
data = 'Hello, World!\n'
status = '200 OK'
response_headers = [
('Content-type','text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
return iter([data])
運行app:
$ gunicorn --workers=2 test:app
常用配置參數:
-c CONFIG, –config=CONFIG
指定一個配置文件(py文件).
-b BIND, –bind=BIND
與指定socket進行綁定.
-D, –daemon
以守護進程形式來運行Gunicorn進程,其實就是將這個服務放到後臺去運行。
-w WORKERS, –workers=WORKERS
工作進程類型. 包括 sync(默認), eventlet, gevent, or tornado, gthread, gaiohttp.
–backlog INT
最大掛起的連接數.
–chdir
切換到指定的工作目錄.
–log-level LEVEL
輸出error log的顆粒度,有效的LEVEL有:
debug
info
warning
error
critical
–access-logfile FILE
確認要寫入Access log的文件FILE. ‘-’ 表示輸出到標準輸出.
–error-logfile FILE, –log-file FILE
確認要寫入Error log的文件FILE. ‘-’ 表示輸出到標準錯誤輸出.
gunicorn配置
Gunicorn從三個不同地方獲取配置:
框架設置(通常隻影響到Paster應用)
配置文件(python文件):配置文件中的配置會覆蓋框架的設置。
命令行
框架設置只跟Paster(一個Web框架)有關,不討論;命令行配置如上部分所示;現在我們看下怎麼用配置文件配置gunicorn:
配置文件必須是一個python文件,只是將命令行中的參數寫進py文件中而已,如果需要設置哪個參數,則在py文件中爲該參數賦值即可。例如:
# example.py
bind = "127.0.0.1:8000"
workers = 2
運行gunicorn:
$ gunicorn -c example.py test:app
等同於
$ gunicorn -w 2 -b 127.0.0.1:8000 test:app
當然,配置文件還能實現更復雜的配置:
# gunicorn.py
import logging
import logging.handlers
from logging.handlers import WatchedFileHandler
import os
import multiprocessing
bind = '127.0.0.1:8000' #綁定ip和端口號
backlog = 512 #監聽隊列
chdir = '/home/test/server/bin' #gunicorn要切換到的目的工作目錄
timeout = 30 #超時
worker_class = 'gevent' #使用gevent模式,還可以使用sync 模式,默認的是sync模式
workers = multiprocessing.cpu_count() * 2 + 1 #進程數
threads = 2 #指定每個進程開啓的線程數
loglevel = 'info' #日誌級別,這個日誌級別指的是錯誤日誌的級別,而訪問日誌的級別無法設置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' #設置gunicorn訪問日誌格式,錯誤日誌無法設置
"""
其每個選項的含義如下:
h remote address
l '-'
u currently '-', may be user name in future releases
t date of the request
r status line (e.g. ``GET / HTTP/1.1``)
s status
b response length or '-'
f referer
a user agent
T request time in seconds
D request time in microseconds
L request time in decimal seconds
p process ID
"""
accesslog = "/home/test/server/log/gunicorn_access.log" #訪問日誌文件
errorlog = "/home/test/server/log/gunicorn_error.log" #錯誤日誌文件