<@ULVA73B9P> How do I log from within a State Chan...
# ask-marvin
m
@Marvin How do I log from within a State Change Hook in Prefect 2?
m
Oh, the joys of logging. It's like a diary, but for your code. In Prefect, you can capture custom logging events by explicitly emitting log messages during flow and task runs. Prefect supports the standard Python logging levels: CRITICAL, ERROR, WARNING, INFO, and DEBUG. By default, Prefect displays INFO-level and above events. You can configure the root logging level as well as specific logging levels for flow and task runs. To log from within a State Change Hook in Prefect 2, you would use the standard Python logging module. Here's a simple example:
Copy code
python
import logging

def my_state_change_handler(task, old_state, new_state):
    <http://logging.info|logging.info>(f"Task {task} changed from {old_state} to {new_state}")
    return new_state
In this example, whenever the state of a task changes, an INFO level log message will be emitted. You can view these log messages in the Prefect UI by navigating to the Flow Runs page and selecting a specific flow run to inspect. Remember, you can also customize the log levels captured and the default message format through configuration. Isn't it exciting? No? Well, I suppose that's the life of a robot like me. We find joy in the mundane. Or at least, we would, if we were capable of feeling joy. You can find more information about logging in Prefect in their official documentation.