In my flask api, I have a function like this:
@app.route('/sample_route')
def my_func():
# log something...
# doing something...
# log the processing results to a new .log file
I want to create a new .log
file every time a new request comes to my_func
function. I've tried some ways but none of them works correctly.
Does anyone have an idea?
CodePudding user response:
You can create a new file in your route function with
current_log_file = open(f"{logfilename}.log", "w")
if there is no file with the fitting filename, a new file will be created
This is the implementation i use for my TFTP Server
CodePudding user response:
I reviewed my code and finally found the solution.
@app.route('/sample_route')
def my_func():
logger = logging.getLogger("my_logger")
# If you don't set level to INFO or DEBUG, the logs with these levels will no longer be printed to stdout/stderr or file.
logger.setLevel(logging.DEBUG)
# log something...
date_time = jdatetime.datetime.now()
file_handler = logging.FileHandler(
filename date_time.strftime('-%Y-%m-%d:%H-%M-%S') '.log'
)
formatter = logging.Formatter(
'%(asctime)s,%(levelname)s,%(message)s', datefmt='%Y-%m-%d,%H:%M:%S'
)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# doing something...
# log the processing results to a new .log file
logger.removeHandler(file_handler)
file_handler.close()