日志
以flask举例
# mytest.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "hello world"
def run():
app.run("0.0.0.0", 12345)
if __name__ == "__main__":
run()
三种配置方式
# logging.conf
[loggers]
keys = root,gunicorn.error,gunicorn.access
[handlers]
keys=console,logfile
[formatters]
keys=json
[logger_root]
level=INFO
handlers=console,logfile
[logger_gunicorn.error]
level = INFO
handlers = logfile
propagate = 1
qualname = gunicorn.error
[logger_gunicorn.access]
level = INFO
handlers = logfile
propagate = 0
qualname = gunicorn.access
[handler_console]
class=logging.StreamHandler
formatter=json
args=(sys.stdout, )
[handler_logfile]
class=logging.handlers.TimedRotatingFileHandler
formatter=json
args=('logs.log', 'midnight', )
[formatter_json]
format=%(message)s
class=pythonjsonlogger.jsonlogger.JsonFormatter
# gunicorn.conf
import logging
from logging.handlers import TimedRotatingFileHandler
import os, sys
import multiprocessing
from gunicorn.glogging import Logger
filepath = "/data/zgx/test/test/flaskTest/list_embedding/log/"
th_acc = TimedRotatingFileHandler(when="S", backupCount=7, filename=filepath + "access.log")
th_err = TimedRotatingFileHandler(when="S", backupCount=7, filename=filepath + "error.log")
th_acc.setFormatter(logging.Formatter("[%(asctime)s] %(levelname)s | %(message)s"))
th_err.setFormatter(logging.Formatter("[%(asctime)s] %(levelname)s | %(message)s"))
# gunicorn源码中不支持按日切分日志
class SplitLogger(Logger):
def __init__(self, cfg):
super(SplitLogger, self).__init__(cfg)
self.access_log.addHandler(th_acc)
self.error_log.addHandler(th_err)
# Server Socket
bind = ["0.0.0.0:1316"]
backlog = 512
chdir = "/data/prod/project/list_embedding/service_py"
timeout = 100
# Worker Processes
worker_class = "gevent"
workers = multiprocessing.cpu_count() * 2 + 1
# Logging
loglevel = "info"
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
accesslog = "/data/prod/project/list_embedding/service_py/gunicorn_access.log"
error_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
errorlog = "/data/prod/project/list_embedding/service_py/gunicorn_error.log"
logger_class = SplitLogger
# 第一种
gunicorn mytest:app --log-conf=logging.conf
# 第二种
gunicorn mytest:app -c gunicorn.conf
# 第三种
gunicorn mytest:app --access-logfile '/xxx/access.log'
# 具体配置可以详见官网
# https://docs.gunicorn.org/en/latest/settings.html#logger-class