python - 简化 Flask 中的日志记录

标签 python logging flask

我目前将其作为我的 Flask 应用程序的基本记录器。虽然我看到有一个 Flask.logger object .如何使用 native Flask 记录器?还是我在下面做的很好?

对于不同的日志记录状态,我也有点困惑,例如记录到信息还是记录到错误?

LOG_FILENAME = 'app_access_logs.log'

info_log = logging.getLogger('app_info_log')
info_log.setLevel(logging.INFO)

handler = logging.handlers.RotatingFileHandler(
    LOG_FILENAME,
    maxBytes=1024 * 1024 * 100,
    backupCount=20
    )

info_log.addHandler(handler)

...

@app.before_request
def pre_request_logging():
    #Logging statement
    if 'text/html' in request.headers['Accept']:
        info_log.info('\t'.join([
            datetime.datetime.today().ctime(),
            request.remote_addr,
            request.method,
            request.url,
            request.data,
            ', '.join([': '.join(x) for x in request.headers])])
        )

最佳答案

可能你想要的描述如下。

LOG_FILENAME = 'app_access_logs.log'

app.logger.setLevel(logging.INFO) # use the native logger of flask

handler = logging.handlers.RotatingFileHandler(
    LOG_FILENAME,
    maxBytes=1024 * 1024 * 100,
    backupCount=20
    )

app.logger.addHandler(handler)

...

@app.before_request
def pre_request_logging():
    #Logging statement
    if 'text/html' in request.headers['Accept']:
        app.logger.info('\t'.join([
            datetime.datetime.today().ctime(),
            request.remote_addr,
            request.method,
            request.url,
            request.data,
            ', '.join([': '.join(x) for x in request.headers])])
        )

关于python - 简化 Flask 中的日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12964547/

相关文章:

python - 将 Cookie 添加到 ZSI 帖子

python - 使用带有子进程、管道、Popen 的 python 从 hdfs 读取/写入文件给出错误

java - Tomcat 服务器中的 Log4j FileAppender 问题

logging - 如何避免创建 `npm-debug.log`

python - PythonAnywhere 上 Flask 的日志记录格式

python - 将数据发送到服务器flask html

python - 为什么 Python 选择使用 None 而不是 null?

python - matplotlib 轴上的不同精度

r - 将 R 包记录器与 data.frames 结合使用

authentication - 使用 Spring Security 进行 flask 用户身份验证