Skip to content

Commit 2e81cf3

Browse files
authored
Better logging (#262)
* Progress bars * Remove print statement * add log progress to git_pull * Add logging utility * Implement logging in modules * add to __init__ * Align on `datasets` logging
1 parent 1ec86b3 commit 2e81cf3

File tree

8 files changed

+171
-14
lines changed

8 files changed

+171
-14
lines changed

src/huggingface_hub/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@
3535
from .inference_api import InferenceApi
3636
from .repository import Repository
3737
from .snapshot_download import snapshot_download
38+
from .utils import logging

src/huggingface_hub/commands/lfs.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
"""
1818

1919
import json
20-
import logging
2120
import os
2221
import subprocess
2322
import sys
@@ -29,8 +28,10 @@
2928
from huggingface_hub.commands import BaseHuggingfaceCLICommand
3029
from huggingface_hub.lfs import LFS_MULTIPART_UPLOAD_COMMAND
3130

31+
from ..utils import logging
3232

33-
logger = logging.getLogger(__name__)
33+
34+
logger = logging.get_logger(__name__)
3435

3536

3637
class LfsCommands(BaseHuggingfaceCLICommand):

src/huggingface_hub/file_download.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import fnmatch
33
import io
44
import json
5-
import logging
65
import os
76
import sys
87
import tempfile
@@ -28,9 +27,10 @@
2827
REPO_TYPES_URL_PREFIXES,
2928
)
3029
from .hf_api import HfFolder
30+
from .utils import logging
3131

3232

33-
logger = logging.getLogger(__name__)
33+
logger = logging.get_logger(__name__)
3434

3535
_PY_VERSION: str = sys.version.split()[0].rstrip("+")
3636

src/huggingface_hub/hub_mixin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import json
2-
import logging
32
import os
43
from pathlib import Path
54
from typing import Dict, Optional, Union
@@ -10,13 +9,14 @@
109
from .file_download import hf_hub_download, is_torch_available
1110
from .hf_api import HfApi, HfFolder
1211
from .repository import Repository
12+
from .utils import logging
1313

1414

1515
if is_torch_available():
1616
import torch
1717

1818

19-
logger = logging.getLogger(__name__)
19+
logger = logging.get_logger(__name__)
2020

2121

2222
class ModelHubMixin:

src/huggingface_hub/inference_api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
import logging
21
from typing import Dict, List, Optional, Union
32

43
import requests
54

65
from .hf_api import HfApi
6+
from .utils import logging
77

88

9-
logger = logging.getLogger(__name__)
9+
logger = logging.get_logger(__name__)
1010

1111

1212
ENDPOINT = "https://api-inference.huggingface.co"

src/huggingface_hub/repository.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import logging
21
import os
32
import re
43
import subprocess
@@ -15,9 +14,10 @@
1514

1615
from .hf_api import ENDPOINT, HfApi, HfFolder, repo_type_and_id_from_hf_id
1716
from .lfs import LFS_MULTIPART_UPLOAD_COMMAND
17+
from .utils import logging
1818

1919

20-
logger = logging.getLogger(__name__)
20+
logger = logging.get_logger(__name__)
2121

2222

2323
def is_git_repo(folder: Union[str, Path]) -> bool:
@@ -313,9 +313,6 @@ def __init__(
313313
if is_git_repo(self.local_dir):
314314
logger.debug("[Repository] is a valid git repo")
315315
else:
316-
logger.error(
317-
"If not specifying `clone_from`, you need to pass Repository a valid git clone."
318-
)
319316
raise ValueError(
320317
"If not specifying `clone_from`, you need to pass Repository a valid git clone."
321318
)
@@ -468,7 +465,7 @@ def clone_from(self, repo_url: str, use_auth_token: Union[bool, str, None] = Non
468465

469466
if in_repository:
470467
if is_local_clone(self.local_dir, repo_url):
471-
logger.debug(
468+
logger.warning(
472469
f"{self.local_dir} is already a clone of {clean_repo_url}. Make sure you pull the latest"
473470
"changes with `repo.git_pull()`."
474471
)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env python
2+
# coding=utf-8
3+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
# coding=utf-8
2+
# Copyright 2020 Optuna, Hugging Face
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
""" Logging utilities. """
16+
17+
import logging
18+
import os
19+
from logging import CRITICAL # NOQA
20+
from logging import DEBUG # NOQA
21+
from logging import ERROR # NOQA
22+
from logging import FATAL # NOQA
23+
from logging import INFO # NOQA
24+
from logging import NOTSET # NOQA
25+
from logging import WARN # NOQA
26+
from logging import WARNING # NOQA
27+
from typing import Optional
28+
29+
30+
log_levels = {
31+
"debug": logging.DEBUG,
32+
"info": logging.INFO,
33+
"warning": logging.WARNING,
34+
"error": logging.ERROR,
35+
"critical": logging.CRITICAL,
36+
}
37+
38+
_default_log_level = logging.WARNING
39+
40+
41+
def _get_library_name() -> str:
42+
return __name__.split(".")[0]
43+
44+
45+
def _get_library_root_logger() -> logging.Logger:
46+
47+
return logging.getLogger(_get_library_name())
48+
49+
50+
def _get_default_logging_level():
51+
"""
52+
If HUGGINGFACE_HUB_VERBOSITY env var is set to one of the valid choices return that as the new default level.
53+
If it is not - fall back to ``_default_log_level``
54+
"""
55+
env_level_str = os.getenv("HUGGINGFACE_HUB_VERBOSITY", None)
56+
if env_level_str:
57+
if env_level_str in log_levels:
58+
return log_levels[env_level_str]
59+
else:
60+
logging.getLogger().warning(
61+
f"Unknown option HUGGINGFACE_HUB_VERBOSITY={env_level_str}, "
62+
f"has to be one of: { ', '.join(log_levels.keys()) }"
63+
)
64+
return _default_log_level
65+
66+
67+
def _configure_library_root_logger() -> None:
68+
library_root_logger = _get_library_root_logger()
69+
library_root_logger.setLevel(logging.INFO)
70+
71+
72+
def _reset_library_root_logger() -> None:
73+
library_root_logger = _get_library_root_logger()
74+
library_root_logger.setLevel(logging.NOTSET)
75+
76+
77+
def get_logger(name: Optional[str] = None) -> logging.Logger:
78+
"""Return a logger with the specified name.
79+
This function is not supposed to be directly accessed by library users.
80+
"""
81+
82+
if name is None:
83+
name = _get_library_name()
84+
85+
return logging.getLogger(name)
86+
87+
88+
def get_verbosity() -> int:
89+
"""Return the current level for the HuggingFace Hub's root logger.
90+
Returns:
91+
Logging level, e.g., ``huggingface_hub.logging.DEBUG`` and ``huggingface_hub.logging.INFO``.
92+
.. note::
93+
HuggingFace Hub has following logging levels:
94+
- ``huggingface_hub.logging.CRITICAL``, ``huggingface_hub.logging.FATAL``
95+
- ``huggingface_hub.logging.ERROR``
96+
- ``huggingface_hub.logging.WARNING``, ``huggingface_hub.logging.WARN``
97+
- ``huggingface_hub.logging.INFO``
98+
- ``huggingface_hub.logging.DEBUG``
99+
"""
100+
return _get_library_root_logger().getEffectiveLevel()
101+
102+
103+
def set_verbosity(verbosity: int) -> None:
104+
"""Set the level for the HuggingFace Hub's root logger.
105+
Args:
106+
verbosity:
107+
Logging level, e.g., ``huggingface_hub.logging.DEBUG`` and ``huggingface_hub.logging.INFO``.
108+
"""
109+
_get_library_root_logger().setLevel(verbosity)
110+
111+
112+
def set_verbosity_info():
113+
return set_verbosity(INFO)
114+
115+
116+
def set_verbosity_warning():
117+
return set_verbosity(WARNING)
118+
119+
120+
def set_verbosity_debug():
121+
return set_verbosity(DEBUG)
122+
123+
124+
def set_verbosity_error():
125+
return set_verbosity(ERROR)
126+
127+
128+
def disable_propagation() -> None:
129+
"""Disable propagation of the library log outputs.
130+
Note that log propagation is disabled by default.
131+
"""
132+
_get_library_root_logger().propagate = False
133+
134+
135+
def enable_propagation() -> None:
136+
"""Enable propagation of the library log outputs.
137+
Please disable the HuggingFace Hub's default handler to prevent double logging if the root logger has
138+
been configured.
139+
"""
140+
_get_library_root_logger().propagate = True
141+
142+
143+
_configure_library_root_logger()

0 commit comments

Comments
 (0)