{"record":{"id":"eaeb6cb87457e5b1","repo":"Lightning-AI/pytorch-lightning","slug":"you-are-trying-to-self-log-but-it-is-not-manag","errorCode":null,"errorMessage":"You are trying to `self.log()` but it is not managed by the `Trainer` control flow","messagePattern":"You are trying to `self\\.log\\(\\)` but it is not managed by the `Trainer` control flow","errorType":"exception","errorClass":"MisconfigurationException","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/core/module.py","lineNumber":471,"sourceCode":"                \"You are trying to `self.log()` but the `self.trainer` reference is not registered on the model yet.\"\n                \" This is most likely because the model hasn't been passed to the `Trainer`\"\n            )\n            return\n        if trainer.barebones:\n            rank_zero_warn(\n                \"You are trying to `self.log()` but `Trainer(barebones=True)` is configured.\"\n                \" Logging can impact raw speed so it is disabled under this setting.\"\n            )\n            return\n        results = trainer._results\n        if results is None:\n            raise MisconfigurationException(\n                \"You are trying to `self.log()` but the loop's result collection is not registered\"\n                \" yet. This is most likely because you are trying to log in a `predict` hook,\"\n                \" but it doesn't support logging\"\n            )\n        if self._current_fx_name is None:\n            raise MisconfigurationException(\n                \"You are trying to `self.log()` but it is not managed by the `Trainer` control flow\"\n            )\n\n        on_step, on_epoch = _FxValidator.check_logging_and_get_default_levels(\n            self._current_fx_name, on_step=on_step, on_epoch=on_epoch\n        )\n\n        # make sure user doesn't introduce logic for multi-dataloaders\n        if add_dataloader_idx and \"/dataloader_idx_\" in name:\n            raise MisconfigurationException(\n                f\"You called `self.log` with the key `{name}`\"\n                \" but it should not contain information about `dataloader_idx` when `add_dataloader_idx=True`\"\n            )\n\n        value = apply_to_collection(value, (Tensor, numbers.Number), self.__to_tensor, name)\n\n        if trainer._logger_connector.should_reset_tensors(self._current_fx_name):\n            # if we started a new epoch (running its first batch) the hook name has changed","sourceCodeStart":453,"sourceCodeEnd":489,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/core/module.py#L453-L489","documentation":"self.log relies on _current_fx_name, an internal marker the Trainer sets before invoking each hook, to decide default on_step/on_epoch behavior. If self.log is called outside that managed control flow (no hook context), the _FxValidator cannot validate the call and MisconfigurationException is raised.","triggerScenarios":"Calling self.log in code not invoked by the Trainer: in __init__, in helper functions called manually, in dataloader methods, or before trainer.fit has started the loop.","commonSituations":"User calls model.log('loss', loss) while debugging outside training; logs from a DataLoader worker function or from on_before_backward called manually; logs in setup before results registration in some paths.","solutions":["Move the self.log call inside a proper hook (training_step, validation_step, on_train_batch_end, etc.)","For logging outside the loop, use trainer.logger or an external logger directly","Pass explicit on_step/on_epoch only when already inside a supported hook (the fx name must still be set)"],"exampleFix":"# before\nmodel = MyModel()\nmodel.log('loss', 0.5)  # outside Trainer control flow\n\n# after\nclass MyModel(L.LightningModule):\n    def training_step(self, batch, batch_idx):\n        loss = ...\n        self.log('loss', loss)  # inside managed hook\n        return loss","handlingStrategy":"validation","validationCode":"if self._current_fx_name is None:\n    # outside a Trainer-managed hook; use an external logger\n    trainer.logger.log_metrics({name: float(value)})\nelse:\n    self.log(name, value)","typeGuard":"def inside_trainer_hook(module) -> bool:\n    return getattr(module, '_current_fx_name', None) is not None","tryCatchPattern":"try:\n    self.log(name, value)\nexcept MisconfigurationException as e:\n    if 'not managed by the `Trainer` control flow' in str(e):\n        self.logger and self.logger.log_metrics({name: float(value)})\n    else:\n        raise","preventionTips":["Keep all self.log calls inside standard hooks","Use an explicit logger for anything outside the training loop"],"tags":["pytorch-lightning","self-log","control-flow","logging","misconfiguration"],"backgroundTag":"logging-outside-training-loop","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}