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.
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
Asked: 2023-06-04 21:18:21 +0000
Seen: 8 times
Last updated: Jun 04 '23
How can popen() be used to direct streaming data to TAR?
In Python, can a string be utilized to retrieve a dataframe that has the same name as the string?
What is the method for merging field value and text into a singular line for display?
What is the method for programmatic access to a time series?