python - 使用 Gunicorn 时如何记录到文件

标签 python logging flask gunicorn

我正在通过 Gunicorn 运行 Flask 应用程序。

在创建 Flask 应用程序之前,我使用以下方法设置日志记录:

def setup_file_logging():
    logging.config.dictConfig(yaml.load(open('logging.conf')))
    logfile    = logging.getLogger('file')
    logfile.debug("<<setup_file_logging")

使用logging.conf:

formatters:
  standard:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: standard
    stream: ext://sys.stdout
  file:
    class: logging.FileHandler
    level: DEBUG
    formatter: standard
    filename: errors.log
loggers:
  console:
    level: DEBUG
    handlers: [console]
    propagate: no
  file:
    level: DEBUG
    handlers: [file]
    propagate: no
root:
  level: DEBUG
  handlers: [console,file]

如果我运行该应用程序:

gunicorn manage:app

我只在日志文件中得到以下内容:

2017-10-21 05:33:38,913 - 文件 - 调试 - <

即没有写入其他日志记录事件,即使代码库中充满了日志记录调用,我使用以下方式获取记录器:

logger = logging.getLogger(__name__)

在gunicorn(python manage.py runserver)之外运行代码会生成一个丰富的日志文件,因此似乎gunicorn正在阻止将日志信息写入日志文件(我想在gunicorn错误之外使用我自己的日志文件日志)。

如何允许设置gunicorn以允许将应用程序中的所有日志记录事件记录到文件中>

最佳答案

我知道自从有人问这个问题以来已经有一段时间了,但是我也遇到了同样的问题。如果它对其他人有帮助,我的解决方案是修改设置功能,通过修改

logfile = logging.getLogger('file')

logger = logging.getLogger() 

这允许我通过调用在其他模块中使用记录器

logger = logging.getLogger(__name__)

并在整个应用程序中获取结构化记录器名称。

在这里找到了更多解释:https://www.youtube.com/watch?v=apLoTRE1B8c&t=478s

关于python - 使用 Gunicorn 时如何记录到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860447/

相关文章:

python - Flask 在导入 pandas(还有 numpy、matplotlib 等)后挂起

mysql - 跟踪数据库内所有用户流量的最有效方法是什么

scala - Akka (2.3.0) 无法使用 java.lang.ClassNotFoundException 加载 Slf4jEventHandler 类

debugging - Telegram - 计算消息

python - 没有名为 'discord.ext' 的模块; 'discord' 不是一个包

python - Flask-在2条不同的 route 使用相同的变量?

python - uwsgi_params 文件应该放在哪里,它的扩展名是什么?

python - rsync 跳过源上不存在的文件

python - 如何在python中找到两个numpy数组的最近点

python - tf.reduce_sum(lastconv,axis=2)/tf.reduce_sum(tf.cast(tf.greater(lastconv, 0), tf.float32), axis=2) 用于代替均值池?