Flask - How to store logs and add additional information

喜夏-厌秋 提交于 2019-12-12 03:33:56

问题


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.

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)

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.)

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.


回答1:


There are several questions in your question.

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

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.

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.

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)

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


来源:https://stackoverflow.com/questions/34632730/flask-how-to-store-logs-and-add-additional-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!