Flask-如何存储日志并添加其他信息 [英] Flask - How to store logs and add additional information

查看:96
本文介绍了Flask-如何存储日志并添加其他信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将"werkzeug"输出存储在一个文件中(或创建一个类似的日志文件),并向日志的每一行添加其他数据. (例如,如果用户名在会话中已知,则为该用户名的值)

I would like to store "werkzeug" output in a file (or create a similar log file) and add additional data to each line of log. (For example a value for the username if the value is known in the session)

如何进行?如果用户名在会话中未知,我希望用户为未知".

How to proceed ? I would like the user to be "unknown" if the username is not known in the session.

是否可以在执行app.run()之前定义所有内容? (因为尝试在app.run之前使用会话对象时确实遇到了在请求上下文之外工作"错误)

Is it possible to define everything before doing app.run() ? (Because I did ran into 'working outside of request context' errors when trying to use the session object before app.run)

class UserIDFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.
    """
    from flask import session
    def filter(self, record):
        username = session.get('username','unknown')
        record.user_id = username
        return True


logFormatStr = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(filename='output.log',format = logFormatStr, level=logging.DEBUG)
app.run(debug=True)

我对app.run的问题是了解程序如何能够访问存储在会话中的用户值. (我认为也许我必须在定义日志记录之前启动"app.run".)

My question about app.run was understanding how the program will be able to get access to the user value stored in the session. (I thought maybe I have to fire up "app.run" before defining the logging.)

对我来说,最好的答案是一个Hello World示例,其中用户名存储在会话中,并带有添加了该信息的日志文件(类似于werkzeug).

The best answer for me would be a Hello World example with the username stored in the session and with a log file (similar to werkzeug) with that information added.

推荐答案

您的问题中有几个问题.

There are several questions in your question.

对于第一个,您可以在此处查看文档:记录登录到文件.

for the first one, you can check the documentation here: Logging and Logging to a File.

对于第二个,您可以使用session.get('someone', 'unknown'),如果某人"不在会话中,则返回未知",否则它仅返回值.

for the second one, you can use session.get('someone', 'unknown'), return 'unknown' if 'someone' is not in the session, else it just returns the value.

最后一个. app.run()用于启动开发服务器,define everything before doing app.run()是什么意思.而且只有错误可能不是很有帮助,显示一些代码并粘贴完整的错误日志.

for the last one. app.run() is used to fire up a development server, what do you mean by define everything before doing app.run(). And only the error may not very helpful, show some code and paste the full error log.

有关如何登录flask的基本示例:

A basic example for how to log in flask:

from flask import Flask, session

import logging
from logging import Formatter, FileHandler


app = Flask(__name__)


@app.route('/')
def index():
    user_name = session.get('Hello, world', 'unknown')
    app.logger.debug('Say somethind here'.format(
        user_name, extra={'username': user_name}))
    return 'Hello, {0}.'.format(user_name)


if __name__ == '__main__':
    file_handler = FileHandler('app.log')
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s %(username)s: %(message)s'))
    app.logger.addHandler(file_handler)
    app.run(debug=True)

,当您运行该应用程序时,您会在同一目录中找到一个app.log文件,内容为:

and when you run the app, you'll find a app.log file in the same directory, the content is:

2016-01-07 20:19:09,636 DEBUG unknown: say something here

这篇关于Flask-如何存储日志并添加其他信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆