I would like to log user actions whenever user logs in/out and adds, edits, deletes objects in my site models in flask. Which is the best way to do this? Also I would like to show the old data and the new modified data, which happens using wtfforms. I am using flask and Flask-SQLAlchemy. I want something similar to what Django framework offers in the 'History' hlink for the associated objects.
Flask-login also requires you to define a “user_loader” function which, given a user ID, returns the associated user object. The @login_manager. user_loader piece tells Flask-login how to load users given an id. I put this function in the file with all my routes defined, as that's where it's used.
To start with logging in Flask, first import the logging module from Python. This logger module comes out of the box from the Python installation and does not need configuration. The Python logging module logs events based on pre-defined levels. The recorded log events are known as log records.
At the same time, you can use Flask-login API to do some configurations in case that you want to use its functionality. When you want to check whether the user has logged in manually rather than use the Flask-login API, then check the value of session['logged_in'] .
Using the Default Logging System for Flask Python Logging has a default Logger – BasicConfig which we can use to log our messages. The logs are stored in files with . log extension. If you wish to display logs in the console itself, then remove the filename attribute.
Use Signals. Take a look at this
http://flask.pocoo.org/docs/signals/
Using signals, you can keep track of any actions such as adds/edits etc. as needed. All you have to do is
from blinker import Namespace
my_signals = Namespace()
def add_user():
# add user code here
user_added = my_signals.signal('user-added')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With