Ask Your Question
2

How can I prevent the need to pass the logger reference between functions in Python?

asked 2023-06-04 21:18:21 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-04 21:44:03 +0000

huitzilopochtli gravatar image

One way to prevent the need to pass the logger reference between functions is to use a global logger instance.

In Python, you can create a global logger instance using the logging module. Here's an example:

import logging

# create a global logger instance
logger = logging.getLogger(__name__)

def func1():
    logger.debug("func1 called")

def func2():
    logger.debug("func2 called")

# call functions
func1()
func2()

In this example, we create a global logger instance using logging.getLogger(__name__). This logger can then be used in any function within the module without needing to explicitly pass it as a parameter.

You can also configure the global logger instance with handlers and formatters as needed. For example:

import logging

# create a global logger instance
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# create file handler
fh = logging.FileHandler("mylog.log")
fh.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# add handler to logger
logger.addHandler(fh)

def func1():
    logger.debug("func1 called")

def func2():
    logger.debug("func2 called")

# call functions
func1()
func2()

In this example, we configure the global logger instance to log messages at the DEBUG level and write them to a file. We also specify a formatter for the log messages. The func1 and func2 functions can then use the global logger instance without needing to pass it as a parameter.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-04 21:18:21 +0000

Seen: 8 times

Last updated: Jun 04 '23