how to log ip addresses in flask

Certainly! Here's an example of how to log IP addresses in Flask:

  1. Import Flask Modules: Start by importing the necessary modules in your Flask application.
from flask import Flask, request
  1. Create Flask App: Initialize your Flask application.
app = Flask(__name__)
  1. Define Logging Function: Create a function to log IP addresses. This function can be configured to log IP addresses whenever a request is made to your Flask app.
def log_ip():
    ip_address = request.remote_addr
    # Replace 'log_file.txt' with the path to your log file
    with open('log_file.txt', 'a') as file:
        file.write(f"IP Address: {ip_address}\n")
  1. Register Logging Function: Register this function to run before each request.
def before_request():

This setup will log the IP address of every request made to your Flask application in the specified log file. Adjust the file path and logging format as needed for your specific use case.