Azure 上的 Flask 应用程序在应用程序后停止收集日志。 30分钟

问题描述 投票:0回答:1

我构建了一个托管在 Azure 应用服务上的 Flask 应用。该应用程序运行良好,我正在使用日志记录捕获日志。问题是我可以按预期在 kudu: /home/LogFiles 上找到日志文件。但不知怎的,在某些时候条目并没有被收集。我知道该应用程序正在运行。有什么想法吗 ?代码:

   log_file = f'{path}{formatted_datetime}-xxx_logging-log.log'
    file_handler = logging.FileHandler(log_file)
    
    file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(file_formatter)
    logger = logging.getLogger()
    logger.addHandler(file_handler)
    logging.info('*** Logging Started')
python-3.x azure-web-app-service flask-sqlalchemy azure-appservice
1个回答
0
投票

在您的代码中,您添加了一个处理程序,但尚未显式设置日志记录级别。默认情况下,它设置为“警告”,这意味着可能无法捕获信息消息(例如“日志记录已开始”消息)。

  • 下面是我的重现,我对记录器名称、路径处理进行了调整,并引入了用于日志轮换的
    RotatingFileHandler
    。根据您的要求调整
    maxBytes
    backupCount
    参数。

这是代码:config.py_file

import os
import logging
from logging.handlers import RotatingFileHandler
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

LOGS_DIR = 'logs'
os.makedirs(LOGS_DIR, exist_ok=True)

formatted_datetime = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
LOG_FILE = os.path.join(LOGS_DIR, f'{formatted_datetime}-app.log')

# Set up the logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Create a rotating file handler
file_handler = RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5)

# Set the formatter
file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(file_formatter)

# Add the handler to the logger
logger.addHandler(file_handler)

# Flask-SQLAlchemy configuration
SQLALCHEMY_DATABASE_URI = 'your_database_uri_here'
SQLALCHEMY_TRACK_MODIFICATIONS = False

# Create a SQLAlchemy instance
db = SQLAlchemy()

在这里我能够按预期获取每个时间点的日志条目。

enter image description here

然后我将其部署到我的应用程序服务中。

enter image description here

  • 我能够按预期获取 kudu: /home/Logs 中的日志条目。 enter image description here

enter image description here

这里,即使在 30 分钟后也会收集日志。

© www.soinside.com 2019 - 2024. All rights reserved.