Skip to content

Commit 631f874

Browse files
SCANPY-135 Add log messages through the code
1 parent 7dadf89 commit 631f874

12 files changed

Lines changed: 62 additions & 18 deletions

src/pysonar_scanner/__main__.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,20 @@
3838

3939
def scan():
4040
app_logging.setup()
41-
41+
app_logging.get_logger().info("Starting Pysonar, the Sonar scanner CLI for Python")
4242
config = ConfigurationLoader.load()
4343
set_logging_options(config)
44-
44+
app_logging.get_logger().debug(f"Loaded configuration: {config}")
45+
4546
api = build_api(config)
4647
check_version(api)
4748
update_config_with_api_urls(config, api.base_urls)
48-
49+
app_logging.get_logger().debug(f"Configuration after update from API URL: {config}")
50+
4951
cache_manager = cache.get_cache(config)
5052
scanner = create_scanner_engine(api, cache_manager, config)
5153

54+
app_logging.get_logger().info("Starting the analysis...")
5255
return scanner.run(config)
5356

5457

@@ -62,10 +65,13 @@ def build_api(config: dict[str, any]) -> SonarQubeApi:
6265
return SonarQubeApi(base_urls, token)
6366

6467

65-
def check_version(api):
68+
def check_version(api: SonarQubeApi):
69+
app_logging.get_logger().info("Checking SonarQube version...")
6670
if api.is_sonar_qube_cloud():
71+
app_logging.get_logger().info("Analysis will be run on SonarQube Cloud")
6772
return
6873
version = api.get_analysis_version()
74+
app_logging.get_logger().info("Analysis will be run on SonarQube version %s", version)
6975
if not version.does_support_bootstrapping():
7076
raise SQTooOldException(
7177
f"Only SonarQube versions >= {MIN_SUPPORTED_SQ_VERSION} are supported, but got {version}"
@@ -81,8 +87,10 @@ def update_config_with_api_urls(config, base_urls: BaseUrls):
8187

8288

8389
def create_scanner_engine(api, cache_manager, config):
90+
app_logging.get_logger().info("Creating the scanner engine...")
8491
jre_path = create_jre(api, cache_manager, config)
8592
config[SONAR_SCANNER_JAVA_EXE_PATH] = str(jre_path.path)
93+
app_logging.get_logger().debug(f"JRE path: {jre_path.path}")
8694
scanner_engine_path = ScannerEngineProvisioner(api, cache_manager).provision()
8795
scanner = ScannerEngine(jre_path, scanner_engine_path)
8896
return scanner

src/pysonar_scanner/api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import requests
2525
import requests.auth
2626

27+
from pysonar_scanner import app_logging
2728
from pysonar_scanner.configuration.properties import (
2829
SONAR_HOST_URL,
2930
SONAR_SCANNER_SONARCLOUD_URL,
@@ -220,7 +221,7 @@ def download_analysis_engine(self, handle: typing.BinaryIO) -> None:
220221
This method can raise a SonarQubeApiException if the server doesn't respond successfully.
221222
Alternative, if the file IO fails, an IOError or OSError can be raised.
222223
"""
223-
224+
app_logging.get_logger().info("Download the analysis engine...")
224225
try:
225226
res = requests.get(
226227
f"{self.base_urls.api_base_url}/analysis/engine",

src/pysonar_scanner/app_logging.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,6 @@ def setup() -> None:
2626

2727
def configure_logging_level(verbose: bool) -> None:
2828
logging.getLogger().setLevel(logging.DEBUG if verbose else logging.INFO)
29+
30+
def get_logger() -> logging.Logger:
31+
return logging.getLogger()

src/pysonar_scanner/configuration/cli.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#
2020
import argparse
2121

22+
from pysonar_scanner import app_logging
2223
from pysonar_scanner.configuration import properties
2324
from pysonar_scanner.exceptions import UnexpectedCliArgument
2425

src/pysonar_scanner/configuration/configuration_loader.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#
2020
from pathlib import Path
2121

22+
from pysonar_scanner import app_logging
2223
from pysonar_scanner.configuration.cli import CliConfigurationLoader
2324
from pysonar_scanner.configuration.pyproject_toml import TomlConfigurationLoader
2425
from pysonar_scanner.configuration.properties import SONAR_TOKEN, SONAR_PROJECT_BASE_DIR, Key
@@ -35,6 +36,8 @@ def get_static_default_properties() -> dict[Key, any]:
3536
class ConfigurationLoader:
3637
@staticmethod
3738
def load() -> dict[Key, any]:
39+
app_logging.get_logger().info("Loading configuration properties...")
40+
3841
# each property loader is required to return NO default values.
3942
# E.g. if no property has been set, an empty dict must be returned.
4043
# Default values should be set through the get_static_default_properties() method

src/pysonar_scanner/configuration/environment_variables.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import json
2222
from typing import Dict
2323

24+
from pysonar_scanner import app_logging
2425
from pysonar_scanner.configuration.properties import Key, PROPERTIES
2526

2627

@@ -48,10 +49,12 @@ def load_json_env_variables():
4849
json_params = os.environ["SONAR_SCANNER_JSON_PARAMS"]
4950
json_properties = json.loads(json_params)
5051
properties.update(json_properties)
51-
except json.JSONDecodeError:
52-
# If JSON is invalid, continue with regular environment variables
53-
# SCANPY-135 should log the error
54-
pass
52+
except json.JSONDecodeError as e:
53+
app_logging.get_logger().warning(
54+
"The JSON in SONAR_SCANNER_JSON_PARAMS environment variable is invalid. The other environment variables will still be loaded.",
55+
e
56+
)
57+
5558
return properties
5659

5760

src/pysonar_scanner/configuration/pyproject_toml.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from pathlib import Path
2121
from typing import Dict
2222
import os
23+
from pysonar_scanner import app_logging
2324
import tomli
2425

2526
from pysonar_scanner.configuration import properties
@@ -49,9 +50,8 @@ def load(base_dir: Path) -> TomlProperties:
4950
# Look for general project configuration
5051
project_properties = TomlConfigurationLoader.__read_project_properties(toml_dict)
5152
return TomlProperties(sonar_properties, project_properties)
52-
except Exception:
53-
# If there's any error parsing the TOML file, return empty TomlProperties
54-
# SCANPY-135: We should log the pyproject.toml parsing error
53+
except Exception as e:
54+
app_logging.get_logger().warning("There was an error reading the pyproject.toml file. No properties from the TOML file were extracted.", e)
5555
return TomlProperties({}, {})
5656

5757
@staticmethod

src/pysonar_scanner/scannerengine.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from threading import Thread
2626
from typing import IO, Callable, Optional
2727

28+
from pysonar_scanner import app_logging
2829
from pysonar_scanner.api import SonarQubeApi
2930
from pysonar_scanner.cache import Cache, CacheFile
3031
from pysonar_scanner.exceptions import ChecksumException
@@ -122,9 +123,11 @@ def provision(self) -> pathlib.Path:
122123
raise ChecksumException("Failed to download and verify scanner engine")
123124

124125
def __download_and_verify(self) -> Optional[CacheFile]:
126+
app_logging.get_logger().info("Get the analysis engine info ...")
125127
engine_info = self.api.get_analysis_engine()
126128
cache_file = self.cache.get_file(engine_info.filename, engine_info.sha256)
127129
if not cache_file.is_valid():
130+
app_logging.get_logger().info("Cached analysis engine is not valid.")
128131
self.__download_scanner_engine(cache_file)
129132
return cache_file if cache_file.is_valid() else None
130133

@@ -140,7 +143,9 @@ def __init__(self, jre_path: JREResolvedPath, scanner_engine_path: pathlib.Path)
140143

141144
def run(self, config: dict[str, any]):
142145
cmd = self.__build_command(self.jre_path, self.scanner_engine_path)
146+
app_logging.get_logger().debug(f"Command: {cmd}")
143147
properties_str = self.__config_to_json(config)
148+
app_logging.get_logger().debug(f"Properties: {properties_str}")
144149
return CmdExecutor(cmd, properties_str).execute()
145150

146151
def __build_command(self, jre_path: JREResolvedPath, scanner_engine_path: pathlib.Path) -> list[str]:

tests/test_environment_variables.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
from json import JSONDecodeError
2021
import unittest
21-
from unittest.mock import patch
22+
from unittest.mock import MagicMock, patch
2223

2324
from pysonar_scanner.configuration import environment_variables
2425
from pysonar_scanner.configuration.properties import (
@@ -105,13 +106,22 @@ def test_environment_variables_from_json_params(self):
105106
self.assertEqual(len(properties), 2)
106107
self.assertDictEqual(properties, expected_properties)
107108

108-
def test_invalid_json_params(self):
109+
@patch("pysonar_scanner.configuration.environment_variables.app_logging.get_logger")
110+
def test_invalid_json_params(self, mock_get_logger):
111+
mock_logger = MagicMock()
112+
mock_get_logger.return_value = mock_logger
113+
109114
env = {"SONAR_SCANNER_JSON_PARAMS": '{"sonar.token": "json-token"'}
110115
with patch.dict("os.environ", env, clear=True):
111116
properties = environment_variables.load()
112117
self.assertEqual(len(properties), 0)
113118
self.assertDictEqual(properties, {})
114119

120+
mock_logger.warning.assert_called_once_with(
121+
"The JSON in SONAR_SCANNER_JSON_PARAMS environment variable is invalid. The other environment variables will still be loaded.",
122+
unittest.mock.ANY
123+
)
124+
115125
def test_environment_variables_priority_over_json_params(self):
116126
env = {
117127
"SONAR_TOKEN": "regular-token", # This should take priority

tests/unit/test_configuration_cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@
158158
class TestCliConfigurationLoader(unittest.TestCase):
159159
def setUp(self):
160160
self.maxDiff = None
161-
161+
162162
@patch("sys.argv", ["myscript.py", "--token", "myToken", "--sonar-project-key", "myProjectKey"])
163163
def test_minimal_cli_args(self):
164164
configuration = CliConfigurationLoader.load()

0 commit comments

Comments
 (0)