import logging

import trio


class Tracer(trio.abc.Instrument):
    def __init__(self, logger_name=None):
        super().__init__()
        if logger_name is not None:
            self.logger = logging.getLogger(logger_name)
        else:
            self.logger = logging.getLogger()

    def _print_with_task(self, msg, task):
        # repr(task) is perhaps more useful than task.name in general,
        # but in context of a tutorial the extra noise is unhelpful.
        self.logger.debug(f"{msg}: {task.name}")

    def task_spawned(self, task):
        self._print_with_task("### new task spawned", task)

    def task_scheduled(self, task):
        self._print_with_task("### task scheduled", task)

    def before_task_step(self, task):
        self._print_with_task(">>> about to run one step of task", task)

    def after_task_step(self, task):
        self._print_with_task("<<< task step finished", task)

    def task_exited(self, task):
        self._print_with_task("### task exited", task)
