<@ULVA73B9P> I have functions that are shared for ...
# ask-marvin
j
@Marvin I have functions that are shared for prefect tasks & non-prefect codes. How do I make the function to use default logger from python's built in module and to prefect's task logger based on the context it's running?
m
Based on the findings, the core idea is to switch logging contexts dynamically based on whether your code is running as a Prefect task or not. Here's a structured approach to achieve this: 1. Use standard Python logging by default. 2. Switch to Prefect's logger if running within a Prefect task. Here's a sample Python implementation to help guide you:
Copy code
python
import logging
from prefect import task, flow, get_run_logger
from prefect.context import TaskRunContext

# Configure default logger
default_logger = logging.getLogger(__name__)
logging.basicConfig(level=<http://logging.INFO|logging.INFO>)


def get_logger():
    # Check if running within a Prefect task
    if TaskRunContext.get():
        return get_run_logger()
    return default_logger


# Sample task and flow using the shared logger function
@task
def sample_task():
    logger = get_logger()
    <http://logger.info|logger.info>("This is a log from within a Prefect Task")


@flow
def sample_flow():
    logger = get_logger()
    <http://logger.info|logger.info>("This is a log from within a Prefect Flow")
    sample_task()

# Test logging outside Prefect context
if __name__ == "__main__":
    logger = get_logger()
    <http://logger.info|logger.info>("This is a log from outside Prefect context")
    sample_flow()
### Summary: - Use
TaskRunContext.get()
to detect if the code is running within a Prefect task. - Switch to Prefect's logger (
get_run_logger()
) when within a task or flow. - Default to the standard Python logger otherwise. ### References: - Prefect Logging Guide: Prefect Docs - Logging - Example issue discussing logger context: GitHub Issue #9322 This approach ensures that your shared functions use the appropriate logger based on the execution context.