简体   繁体   中英

Passing logger as an argument to functions and get the function name in log file

I am using logging package to create a log file for my application. In the main function, I created the logger, handler, and formatter and set the logging level as below:

try:
    os.remove('xxx.log')
except WindowsError:
    pass
LOG_FILENAME = 'xxx.log'
logger = logging.getLogger(__name__)
logger.setLevel(20)
ch = logging.FileHandler(LOG_FILENAME)
ch.setLevel(20)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

logger.info("info message")

then, I call different functions that I want to have the logger as well. So I pass logger as an argument to that function and then use the logger.info to have the info log in that function. The problem is that I need the name of the function to be listed in the log file so I coded as below:

test(a, b, c, d, e, f, g, logger)
def test test(a, b, c, d, e, f, g, logger):
    logger = logging.getLogger(__name__)
    logger.info("test ....")

What is wrong here? How can fix the issue? Any suggestion to improve my coding is also appreciated.

The formatter needs to be changed to below:

logging.Formatter("%(asctime)s - %(module)s - %(levelname)s - %(message)s")

So instead %(name)s, the %(module)s needs to be implemented based on the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM