1

I have a flask application, which calls 2 functions from 2 different files. I've setup logging to 2 different files. However, the logging always seems to append to one file (whatever end point is hit first)

Here is the structure of the files -

  • app.py
from file1 import fun1
from file2 import fun2
 
@app.route("/end_point1")
def data_1:
    return fun1()
     
@app.route("/end_point2")
def data_2:
    return fun2()
  • file1.py
import logging

def fun1:
    logging.basicConfig(filename = "file1.log")
    logging.info("Logging function 1 details to to file1")
    return foo
  • file2.py
def fun2:
    logging.basicConfig(filename = "file2.log")
    logging.info("Logging function 2 details to to file2")
    return bar

This logs fine (separately) when I run the individual python files - file1.py / file2.py But the logs append to just one file when I run the API.

What am I doing wrong with the logging? How can I fix it?

Shine
  • 83
  • 10

1 Answers1

0

Add this to logger_setup.py

import logging
from pathlib import Path
formatter = logging.Formatter('%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s')


def setup_logger( name, log_file, level=logging.DEBUG): 

    my_file = Path(log_file)
    # print("check the if condition for the file")
    # print(my_file.is_file())

    if my_file.is_file():
        #print(logging.getLogger(name).hasHandlers())
        # if logging.getLogger(name).hasHandlers():
        if len(logging.getLogger(name).handlers)>0:
            return logging.getLogger(name)
        else:
            handler = logging.FileHandler(log_file, mode='a')        
            handler.setFormatter(formatter)
            logger = logging.getLogger(name)
            logger.setLevel(level)
            logger.addHandler(handler)
            logger.propagate = False
            return logger
    else:
        handler = logging.FileHandler(log_file, mode='a')        
        handler.setFormatter(formatter)

        logger = logging.getLogger(name)
        logger.setLevel(level)
        logger.addHandler(handler)
        logger.propagate = False
        return logger

Inside the file1 and 2 you can use something like this

import logging
import logger_setup

def fun1():
    log_location = 'logs'
    logger = logger_setup.setup_logger(__name__,log_location+__name__+'.log')
    logger.info("Logging function 1 details to to file1")
    return "1"
Deependra
  • 21
  • 7