Skip to content

Commit da4b5eb

Browse files
awaelchliBorda
authored andcommitted
fix duplicate console logging bug v2 (#6275)
Co-authored-by: chaton <[email protected]> Co-authored-by: Jirka Borovec <[email protected]> (cherry picked from commit bc577ca)
1 parent 7114c2d commit da4b5eb

32 files changed

+103
-44
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
180180
- Fixed error thrown when using valid distributed mode in multi node ([#6297](https://github.com/PyTorchLightning/pytorch-lightning/pull/6297)
181181

182182

183+
- Fixed duplicate logs appearing in console when using the python logging module ([#5509](https://github.com/PyTorchLightning/pytorch-lightning/pull/5509), [#6275](https://github.com/PyTorchLightning/pytorch-lightning/pull/6275))
184+
185+
183186
## [1.2.1] - 2021-02-23
184187

185188
### Fixed

docs/source/extensions/logging.rst

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -259,13 +259,19 @@ Configure console logging
259259
*************************
260260

261261
Lightning logs useful information about the training process and user warnings to the console.
262-
You can retrieve the Lightning logger and change it to your liking. For example, increase the logging level
263-
to see fewer messages like so:
262+
You can retrieve the Lightning logger and change it to your liking. For example, adjust the logging level
263+
or redirect output for certain modules to log files:
264264

265-
.. code-block:: python
265+
.. testcode::
266266

267267
import logging
268-
logging.getLogger("lightning").setLevel(logging.ERROR)
268+
269+
# configure logging at the root level of lightning
270+
logging.getLogger("pytorch_lightning").setLevel(logging.ERROR)
271+
272+
# configure logging on module level, redirect to file
273+
logger = logging.getLogger("pytorch_lightning.core")
274+
logger.addHandler(logging.FileHandler("core.log"))
269275

270276
Read more about custom Python logging `here <https://docs.python.org/3/library/logging.html>`_.
271277

pl_examples/domain_templates/computer_vision_fine_tuning.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
See: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
3939
"""
4040
import argparse
41+
import logging
4142
import os
4243
from pathlib import Path
4344
from typing import Union
@@ -54,11 +55,11 @@
5455

5556
import pytorch_lightning as pl
5657
from pl_examples import cli_lightning_logo
57-
from pytorch_lightning import _logger as log
5858
from pytorch_lightning import LightningDataModule
5959
from pytorch_lightning.callbacks.finetuning import BaseFinetuning
6060
from pytorch_lightning.utilities import rank_zero_info
6161

62+
log = logging.getLogger(__name__)
6263
DATA_URL = "https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip"
6364

6465
# --- Finetuning Callback ---

pytorch_lightning/__init__.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""Root package info."""
22

3-
import logging as python_logging
3+
import logging
44
import os
5+
import sys
56
import time
67

78
_this_year = time.strftime("%Y")
@@ -37,10 +38,14 @@
3738
- https://pytorch-lightning.readthedocs.io/en/latest
3839
- https://pytorch-lightning.readthedocs.io/en/stable
3940
"""
41+
_root_logger = logging.getLogger()
42+
_logger = logging.getLogger(__name__)
43+
_logger.setLevel(logging.INFO)
4044

41-
_logger = python_logging.getLogger("lightning")
42-
_logger.addHandler(python_logging.StreamHandler())
43-
_logger.setLevel(python_logging.INFO)
45+
# if root logger has handlers, propagate messages up and let root logger process them
46+
if not _root_logger.hasHandlers():
47+
_logger.addHandler(logging.StreamHandler())
48+
_logger.propagate = False
4449

4550
_PACKAGE_ROOT = os.path.dirname(__file__)
4651
_PROJECT_ROOT = os.path.dirname(_PACKAGE_ROOT)
@@ -53,9 +58,7 @@
5358
except NameError:
5459
__LIGHTNING_SETUP__: bool = False
5560

56-
if __LIGHTNING_SETUP__:
57-
import sys # pragma: no-cover
58-
61+
if __LIGHTNING_SETUP__: # pragma: no-cover
5962
sys.stdout.write(f'Partial import of `{__name__}` during the build process.\n') # pragma: no-cover
6063
# We are not importing the rest of the lightning during the build process, as it may not be compiled yet
6164
else:

pytorch_lightning/callbacks/finetuning.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
^^^^^^^^^^^^^^^^^^^^
1717
Freeze and unfreeze models for finetuning purposes
1818
"""
19+
import logging
1920
from typing import Callable, Generator, Iterable, List, Optional, Union
2021

2122
import torch
@@ -24,12 +25,13 @@
2425
from torch.nn.modules.container import Container, ModuleDict, ModuleList, Sequential
2526
from torch.optim.optimizer import Optimizer
2627

27-
from pytorch_lightning import _logger as log
2828
from pytorch_lightning.callbacks.base import Callback
2929
from pytorch_lightning.core.lightning import LightningModule
3030
from pytorch_lightning.utilities import rank_zero_warn
3131
from pytorch_lightning.utilities.exceptions import MisconfigurationException
3232

33+
log = logging.getLogger(__name__)
34+
3335

3436
def multiplicative(epoch):
3537
return 2

pytorch_lightning/callbacks/model_checkpoint.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
Automatically save model checkpoints during training.
1919
2020
"""
21-
21+
import logging
2222
import os
2323
import re
2424
from copy import deepcopy
@@ -29,13 +29,13 @@
2929
import torch
3030
import yaml
3131

32-
from pytorch_lightning import _logger as log
3332
from pytorch_lightning.callbacks.base import Callback
3433
from pytorch_lightning.utilities import rank_zero_info, rank_zero_only, rank_zero_warn
3534
from pytorch_lightning.utilities.cloud_io import get_filesystem
3635
from pytorch_lightning.utilities.exceptions import MisconfigurationException
3736
from pytorch_lightning.utilities.warnings import WarningCache
3837

38+
log = logging.getLogger(__name__)
3939
warning_cache = WarningCache()
4040

4141

pytorch_lightning/callbacks/pruning.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
^^^^^^^^^^^^
1717
"""
1818
import inspect
19+
import logging
1920
from copy import deepcopy
2021
from functools import partial
2122
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
@@ -24,12 +25,13 @@
2425
import torch.nn.utils.prune as pytorch_prune
2526
from torch import nn
2627

27-
from pytorch_lightning import _logger as log
2828
from pytorch_lightning.callbacks.base import Callback
2929
from pytorch_lightning.core.lightning import LightningModule
3030
from pytorch_lightning.utilities.distributed import rank_zero_debug, rank_zero_only
3131
from pytorch_lightning.utilities.exceptions import MisconfigurationException
3232

33+
log = logging.getLogger(__name__)
34+
3335
_PYTORCH_PRUNING_FUNCTIONS = {
3436
"ln_structured": pytorch_prune.ln_structured,
3537
"l1_unstructured": pytorch_prune.l1_unstructured,

pytorch_lightning/core/lightning.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import collections
1717
import copy
1818
import inspect
19+
import logging
1920
import os
2021
import re
2122
import tempfile
@@ -31,7 +32,6 @@
3132
from torch.nn import Module
3233
from torch.optim.optimizer import Optimizer
3334

34-
from pytorch_lightning import _logger as log
3535
from pytorch_lightning.core.grads import GradInformation
3636
from pytorch_lightning.core.hooks import CheckpointHooks, DataHooks, ModelHooks
3737
from pytorch_lightning.core.memory import ModelSummary
@@ -44,6 +44,8 @@
4444
from pytorch_lightning.utilities.exceptions import MisconfigurationException
4545
from pytorch_lightning.utilities.parsing import AttributeDict, collect_init_args, get_init_args
4646

47+
log = logging.getLogger(__name__)
48+
4749

4850
class LightningModule(
4951
ABC,

pytorch_lightning/core/saving.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import ast
1616
import csv
1717
import inspect
18+
import logging
1819
import os
1920
from argparse import Namespace
2021
from copy import deepcopy
@@ -25,13 +26,13 @@
2526
import torch
2627
import yaml
2728

28-
from pytorch_lightning import _logger as log
2929
from pytorch_lightning.utilities import _OMEGACONF_AVAILABLE, AttributeDict, rank_zero_warn
3030
from pytorch_lightning.utilities.apply_func import apply_to_collection
3131
from pytorch_lightning.utilities.cloud_io import get_filesystem
3232
from pytorch_lightning.utilities.cloud_io import load as pl_load
3333
from pytorch_lightning.utilities.parsing import parse_class_init_keys
3434

35+
log = logging.getLogger(__name__)
3536
PRIMITIVE_TYPES = (bool, int, float, str)
3637
ALLOWED_CONFIG_TYPES = (AttributeDict, MutableMapping, Namespace)
3738

pytorch_lightning/loggers/comet.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,20 @@
1616
------------
1717
"""
1818

19+
import logging
1920
import os
2021
from argparse import Namespace
2122
from typing import Any, Dict, Optional, Union
2223

2324
import torch
2425
from torch import is_tensor
2526

26-
from pytorch_lightning import _logger as log
2727
from pytorch_lightning.core.lightning import LightningModule
2828
from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment
2929
from pytorch_lightning.utilities import _module_available, rank_zero_only
3030
from pytorch_lightning.utilities.exceptions import MisconfigurationException
3131

32+
log = logging.getLogger(__name__)
3233
_COMET_AVAILABLE = _module_available("comet_ml")
3334

3435
if _COMET_AVAILABLE:

pytorch_lightning/loggers/csv_logs.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,19 @@
2020
"""
2121
import csv
2222
import io
23+
import logging
2324
import os
2425
from argparse import Namespace
2526
from typing import Any, Dict, Optional, Union
2627

2728
import torch
2829

29-
from pytorch_lightning import _logger as log
3030
from pytorch_lightning.core.saving import save_hparams_to_yaml
3131
from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment
3232
from pytorch_lightning.utilities.distributed import rank_zero_only, rank_zero_warn
3333

34+
log = logging.getLogger(__name__)
35+
3436

3537
class ExperimentWriter(object):
3638
r"""

pytorch_lightning/loggers/mlflow.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,17 @@
1515
MLflow Logger
1616
-------------
1717
"""
18+
import logging
1819
import re
1920
from argparse import Namespace
2021
from time import time
2122
from typing import Any, Dict, Optional, Union
2223

23-
from pytorch_lightning import _logger as log
2424
from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment
2525
from pytorch_lightning.utilities import _module_available, rank_zero_only, rank_zero_warn
2626

27+
log = logging.getLogger(__name__)
2728
LOCAL_FILE_URI_PREFIX = "file:"
28-
2929
_MLFLOW_AVAILABLE = _module_available("mlflow")
3030
try:
3131
import mlflow

pytorch_lightning/loggers/neptune.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,17 @@
1515
Neptune Logger
1616
--------------
1717
"""
18+
import logging
1819
from argparse import Namespace
1920
from typing import Any, Dict, Iterable, Optional, Union
2021

2122
import torch
2223
from torch import is_tensor
2324

24-
from pytorch_lightning import _logger as log
2525
from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment
2626
from pytorch_lightning.utilities import _module_available, rank_zero_only
2727

28+
log = logging.getLogger(__name__)
2829
_NEPTUNE_AVAILABLE = _module_available("neptune")
2930

3031
if _NEPTUNE_AVAILABLE:

pytorch_lightning/loggers/tensorboard.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
------------------
1717
"""
1818

19+
import logging
1920
import os
2021
from argparse import Namespace
2122
from typing import Any, Dict, Optional, Union
@@ -24,13 +25,14 @@
2425
from torch.utils.tensorboard import SummaryWriter
2526
from torch.utils.tensorboard.summary import hparams
2627

27-
from pytorch_lightning import _logger as log
2828
from pytorch_lightning.core.lightning import LightningModule
2929
from pytorch_lightning.core.saving import save_hparams_to_yaml
3030
from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment
3131
from pytorch_lightning.utilities import _OMEGACONF_AVAILABLE, rank_zero_only, rank_zero_warn
3232
from pytorch_lightning.utilities.cloud_io import get_filesystem
3333

34+
log = logging.getLogger(__name__)
35+
3436
if _OMEGACONF_AVAILABLE:
3537
from omegaconf import Container, OmegaConf
3638

pytorch_lightning/plugins/environments/slurm_environment.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,14 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import logging
1516
import os
1617
import re
1718

18-
from pytorch_lightning import _logger as log
1919
from pytorch_lightning.plugins.environments.cluster_environment import ClusterEnvironment
2020

21+
log = logging.getLogger(__name__)
22+
2123

2224
class SLURMEnvironment(ClusterEnvironment):
2325

pytorch_lightning/plugins/environments/torchelastic_environment.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,14 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import logging
1516
import os
1617

17-
from pytorch_lightning import _logger as log
1818
from pytorch_lightning.plugins.environments.cluster_environment import ClusterEnvironment
1919
from pytorch_lightning.utilities import rank_zero_warn
2020

21+
log = logging.getLogger(__name__)
22+
2123

2224
class TorchElasticEnvironment(ClusterEnvironment):
2325

pytorch_lightning/plugins/training_type/ddp.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
import logging
1415
import os
1516
import subprocess
1617
import sys
@@ -23,7 +24,6 @@
2324
from torch.nn.parallel.distributed import DistributedDataParallel
2425
from torch.optim import Optimizer
2526

26-
from pytorch_lightning import _logger as log
2727
from pytorch_lightning.distributed import LightningDistributed
2828
from pytorch_lightning.overrides import LightningDistributedModule
2929
from pytorch_lightning.overrides.distributed import prepare_for_backward
@@ -44,6 +44,9 @@
4444
from hydra.utils import get_original_cwd, to_absolute_path
4545

4646

47+
log = logging.getLogger(__name__)
48+
49+
4750
class DDPPlugin(ParallelPlugin):
4851
"""
4952
Plugin for multi-process single-device training on one or multiple nodes.

0 commit comments

Comments
 (0)