How can I add logs to my flow?

Prefect 2.0

Orion provides the get_run_logger function that returns a logging.Logger object. Retrieve the logger within the flow or task function and use it there.

Here is how you can use it in your tasks, flows, and subflows:

from prefect import task, get_run_logger

@task
def marvins_favorite_task():
    logger = get_run_logger()
    logger.info("Hello from the Marvin's favorite task!")
An example flow with various log levels
from prefect import flow, task, get_run_logger

@task
def foo():
    logger = get_run_logger()
    logger.info("Hello from the 'foo' task")

@task
def bar():
    logger = get_run_logger()
    logger.warning("Oh no, this is a bad task!")
    raise ValueError("Test")

@flow
def child_flow():
    bar()

@flow
def flow_with_logging():
    logger = get_run_logger()
    logger.info("Hello from the parent flow!")

    foo_future = foo()
    child_flow()

    logger.warning("Goodbye from the parent flow!")
    return foo_future

if __name__ == "__main__":
    flow_with_logging()

Prefect 1.0

To add custom logs within your tasks, you need to access the logger object from the Prefect context. Logging outside of tasks is generally not supported. Here is how it works:

import prefect

@task
def my_task():
    logger = prefect.context.get("logger")
    logger.info("An info message.")
    logger.warning("A warning message.")