Skip to content

Commit ba2627e

Browse files
author
Will Usher
authored
Merge pull request #338 from willu47/issue-337
Remove top level verbosity cli argument. - `smif -vv list` or `smif -vv run <modelrun>` are no longer valid commands - `smif run <modelrun> -vv` verbosity flags are added to the sub-commands not the parent command
2 parents 13d0383 + c1ffc77 commit ba2627e

File tree

8 files changed

+95
-117
lines changed

8 files changed

+95
-117
lines changed

README.rst

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ and simulation model.
222222
To see all options and flags::
223223

224224
$ smif --help
225-
usage: smif [-h] [-V] [-v] {setup,list,run} ...
225+
usage: smif [-h] [-V] {setup,list,run} ...
226226

227227
Command line tools for smif
228228

@@ -236,8 +236,6 @@ To see all options and flags::
236236
optional arguments:
237237
-h, --help show this help message and exit
238238
-V, --version show the current version of smif
239-
-v, --verbose show messages: -v to see messages reporting on progress,
240-
-vv to see debug messages.
241239

242240
Citation
243241
========

docs/getting_started.rst

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Setup
1818
First, check smif has installed correctly by typing on the command line::
1919

2020
$ smif
21-
usage: smif [-h] [-V] [-v] {setup,list,app,run} ...
21+
usage: smif [-h] [-V] {setup,list,app,run} ...
2222

2323
Command line tools for smif
2424

@@ -32,8 +32,6 @@ First, check smif has installed correctly by typing on the command line::
3232
optional arguments:
3333
-h, --help show this help message and exit
3434
-V, --version show the current version of smif
35-
-v, --verbose show messages: -v to see messages reporting on
36-
progress, -vv to see debug messages.
3735

3836

3937
You can also check which version is installed::

src/smif/cli/__init__.py

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -65,43 +65,40 @@
6565
"""
6666
from __future__ import print_function
6767

68+
import logging
69+
import os
70+
import sys
71+
from argparse import ArgumentParser
72+
73+
import pkg_resources
74+
75+
import smif
76+
import smif.cli.log
77+
from smif.controller import (ModelRunScheduler, copy_project_folder,
78+
execute_model_run)
79+
from smif.data_layer import Store
80+
from smif.data_layer.file import (CSVDataStore, FileMetadataStore,
81+
ParquetDataStore, YamlConfigStore)
82+
from smif.http_api import create_app
83+
6884
try:
6985
import _thread
7086
except ImportError:
7187
import thread as _thread
7288

73-
import logging
74-
import logging.config
75-
import os
76-
import pkg_resources
7789

7890
try:
7991
import win32api
8092
USE_WIN32 = True
8193
except ImportError:
8294
USE_WIN32 = False
8395

84-
from argparse import ArgumentParser
85-
import sys
86-
87-
import smif
88-
import smif.cli.log
89-
90-
from smif.controller import copy_project_folder, execute_model_run, ModelRunScheduler
91-
from smif.http_api import create_app
92-
from smif.data_layer import Store
93-
from smif.data_layer.file import (CSVDataStore, FileMetadataStore, ParquetDataStore,
94-
YamlConfigStore)
95-
9696

9797
__author__ = "Will Usher, Tom Russell"
9898
__copyright__ = "Will Usher, Tom Russell"
9999
__license__ = "mit"
100100

101101

102-
LOGGER = logging.getLogger(__name__)
103-
104-
105102
def list_model_runs(args):
106103
"""List the model runs defined in the config
107104
"""
@@ -119,7 +116,8 @@ def run_model_runs(args):
119116
----------
120117
args
121118
"""
122-
LOGGER.profiling_start('run_model_runs', '{:s}, {:s}, {:s}'.format(
119+
logger = logging.getLogger(__name__)
120+
logger.profiling_start('run_model_runs', '{:s}, {:s}, {:s}'.format(
123121
args.modelrun, args.interface, args.directory))
124122
if args.batchfile:
125123
with open(args.modelrun, 'r') as f:
@@ -129,9 +127,9 @@ def run_model_runs(args):
129127

130128
store = _get_store(args)
131129
execute_model_run(model_run_ids, store, args.warm)
132-
LOGGER.profiling_stop('run_model_runs', '{:s}, {:s}, {:s}'.format(
130+
logger.profiling_stop('run_model_runs', '{:s}, {:s}, {:s}'.format(
133131
args.modelrun, args.interface, args.directory))
134-
LOGGER.summary()
132+
logger.summary()
135133

136134

137135
def _get_store(args):
@@ -221,10 +219,6 @@ def parse_arguments():
221219
action='version',
222220
version="smif " + smif.__version__,
223221
help='show the current version of smif')
224-
parser.add_argument('-v', '--verbose',
225-
action='count',
226-
help='show messages: -v to see messages reporting on progress, ' +
227-
'-vv to see debug messages.')
228222

229223
parent_parser = ArgumentParser(add_help=False)
230224
parent_parser.add_argument('-v', '--verbose',
@@ -334,6 +328,7 @@ def main(arguments=None):
334328
"""
335329
parser = parse_arguments()
336330
args = parser.parse_args(arguments)
331+
smif.cli.log.setup_logging(args.verbose)
337332

338333
def exception_handler(exception_type, exception, traceback, debug_hook=sys.excepthook):
339334
if args.verbose:

src/smif/cli/log.py

Lines changed: 43 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,6 @@
55
import sys
66
from collections import OrderedDict
77

8-
LOGGING_CONFIG = {
9-
'version': 1,
10-
'formatters': {
11-
'default': {
12-
'format': '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s'
13-
},
14-
'message': {
15-
'format': '\033[1;34m%(levelname)-8s\033[0m %(message)s'
16-
}
17-
},
18-
'handlers': {
19-
'file': {
20-
'class': 'logging.FileHandler',
21-
'level': 'DEBUG',
22-
'formatter': 'default',
23-
'filename': 'smif.log',
24-
'mode': 'a',
25-
'encoding': 'utf-8'
26-
},
27-
'stream': {
28-
'class': 'logging.StreamHandler',
29-
'formatter': 'message',
30-
'level': 'DEBUG'
31-
}
32-
},
33-
'root': {
34-
'handlers': ['file', 'stream'],
35-
'level': 'DEBUG'
36-
}
37-
}
38-
398

409
# Make profiling methods available through the logger
4110
def profiling_start(self, operation, key):
@@ -100,28 +69,50 @@ def summary(self, *args, **kws):
10069
self._log(logging.INFO, entry, args)
10170

10271

72+
def setup_logging(loglevel):
73+
config = {
74+
'version': 1,
75+
'formatters': {
76+
'default': {
77+
'format': '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s'
78+
},
79+
'message': {
80+
'format': '\033[1;34m%(levelname)-8s\033[0m %(message)s'
81+
}
82+
},
83+
'handlers': {
84+
'file': {
85+
'class': 'logging.FileHandler',
86+
'level': 'DEBUG',
87+
'formatter': 'default',
88+
'filename': 'smif.log',
89+
'mode': 'a',
90+
'encoding': 'utf-8'
91+
},
92+
'stream': {
93+
'class': 'logging.StreamHandler',
94+
'formatter': 'message',
95+
'level': 'DEBUG'
96+
}
97+
},
98+
'root': {
99+
'handlers': ['file', 'stream'],
100+
'level': 'DEBUG'
101+
}
102+
}
103+
104+
if loglevel is None:
105+
config['root']['level'] = logging.WARNING
106+
elif loglevel == 1:
107+
config['root']['level'] = logging.INFO
108+
else:
109+
config['root']['level'] = logging.DEBUG
110+
111+
logging.config.dictConfig(config)
112+
logging.debug('Debug logging enabled.')
113+
114+
103115
logging.Logger.profiling_start = profiling_start
104116
logging.Logger.profiling_stop = profiling_stop
105117
logging.Logger.summary = summary
106118
logging.Logger._profile = OrderedDict()
107-
108-
# Configure logging once, outside of any dependency on argparse
109-
VERBOSITY = None
110-
if '--verbose' in sys.argv:
111-
VERBOSITY = sys.argv.count('--verbose')
112-
else:
113-
for arg in sys.argv:
114-
if re.match(r'\A-v+\Z', arg):
115-
VERBOSITY = len(arg) - 1
116-
break
117-
118-
if VERBOSITY is None:
119-
LOGGING_CONFIG['root']['level'] = logging.WARNING
120-
elif VERBOSITY == 1:
121-
LOGGING_CONFIG['root']['level'] = logging.INFO
122-
else:
123-
LOGGING_CONFIG['root']['level'] = logging.DEBUG
124-
125-
logging.config.dictConfig(LOGGING_CONFIG)
126-
LOGGER = logging.getLogger(__name__)
127-
LOGGER.debug('Debug logging enabled.')

src/smif/controller/build.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88
from smif.exception import SmifDataNotFoundError
99
from smif.model import ScenarioModel, SosModel
1010

11-
LOGGER = logging.getLogger(__name__)
12-
1311

1412
def get_model_run_definition(store, modelrun):
1513
"""Builds the model run
@@ -31,26 +29,26 @@ def get_model_run_definition(store, modelrun):
3129
try:
3230
model_run_config = store.read_model_run(modelrun)
3331
except SmifDataNotFoundError:
34-
LOGGER.error("Model run %s not found. Run 'smif list' to see available model runs.",
32+
logging.error("Model run %s not found. Run 'smif list' to see available model runs.",
3533
modelrun)
3634
exit(-1)
3735

38-
LOGGER.info("Running %s", model_run_config['name'])
39-
LOGGER.debug("Model Run: %s", model_run_config)
36+
logging.info("Running %s", model_run_config['name'])
37+
logging.debug("Model Run: %s", model_run_config)
4038
sos_model_config = store.read_sos_model(model_run_config['sos_model'])
4139

4240
sector_models = get_sector_models(sos_model_config['sector_models'], store)
43-
LOGGER.debug("Sector models: %s", sector_models)
41+
logging.debug("Sector models: %s", sector_models)
4442

4543
scenario_models = get_scenario_models(model_run_config['scenarios'], store)
46-
LOGGER.debug("Scenario models: %s", [model.name for model in scenario_models])
44+
logging.debug("Scenario models: %s", [model.name for model in scenario_models])
4745

4846
sos_model = SosModel.from_dict(sos_model_config, sector_models + scenario_models)
4947
model_run_config['sos_model'] = sos_model
50-
LOGGER.debug("Model list: %s", list(model.name for model in sos_model.models))
48+
logging.debug("Model list: %s", list(model.name for model in sos_model.models))
5149

5250
model_run_config['strategies'] = store.read_strategies(model_run_config['name'])
53-
LOGGER.debug("Strategies: %s", [s['type'] for s in model_run_config['strategies']])
51+
logging.debug("Strategies: %s", [s['type'] for s in model_run_config['strategies']])
5452

5553
return model_run_config
5654

@@ -78,7 +76,7 @@ def get_scenario_models(scenarios, handler):
7876
scenario_definition['outputs'] = scenario_definition['provides']
7977
del scenario_definition['provides']
8078

81-
LOGGER.debug("Scenario definition: %s", scenario_name)
79+
logging.debug("Scenario definition: %s", scenario_name)
8280

8381
scenario_model = ScenarioModel.from_dict(scenario_definition)
8482
scenario_models.append(scenario_model)
@@ -123,7 +121,8 @@ def build_model_run(model_run_config):
123121
-------
124122
`smif.controller.modelrun.ModelRun`
125123
"""
126-
LOGGER.profiling_start('build_model_run', model_run_config['name'])
124+
logger = logging.getLogger()
125+
logger.profiling_start('build_model_run', model_run_config['name'])
127126
try:
128127
builder = ModelRunBuilder()
129128
builder.construct(model_run_config)
@@ -133,10 +132,10 @@ def build_model_run(model_run_config):
133132
traceback.print_exception(err_type, err_value, err_traceback)
134133
err_msg = str(error)
135134
if err_msg:
136-
LOGGER.error("An AssertionError occurred (%s) see details above.", err_msg)
135+
logger.error("An AssertionError occurred (%s) see details above.", err_msg)
137136
else:
138-
LOGGER.error("An AssertionError occurred, see details above.")
137+
logger.error("An AssertionError occurred, see details above.")
139138
exit(-1)
140139

141-
LOGGER.profiling_stop('build_model_run', model_run_config['name'])
140+
logger.profiling_stop('build_model_run', model_run_config['name'])
142141
return modelrun

src/smif/controller/execute.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
from smif.controller.build import build_model_run, get_model_run_definition
55
from smif.exception import SmifModelRunError
66

7-
LOGGER = logging.getLogger(__name__)
8-
97

108
def execute_model_run(model_run_ids, store, warm=False):
119
"""Runs the model run
@@ -17,23 +15,23 @@ def execute_model_run(model_run_ids, store, warm=False):
1715
"""
1816
model_run_definitions = []
1917
for model_run in model_run_ids:
20-
LOGGER.info("Getting model run definition for '%s'", model_run)
18+
logging.info("Getting model run definition for '%s'", model_run)
2119
model_run_definitions.append(get_model_run_definition(store, model_run))
2220

2321
for model_run_config in model_run_definitions:
2422

25-
LOGGER.info("Build model run from configuration data")
23+
logging.info("Build model run from configuration data")
2624
modelrun = build_model_run(model_run_config)
2725

28-
LOGGER.info("Running model run %s", modelrun.name)
26+
logging.info("Running model run %s", modelrun.name)
2927

3028
try:
3129
if warm:
3230
modelrun.run(store, store.prepare_warm_start(modelrun.name))
3331
else:
3432
modelrun.run(store)
3533
except SmifModelRunError as ex:
36-
LOGGER.exception(ex)
34+
logging.exception(ex)
3735
exit(1)
3836

3937
print("Model run '%s' complete" % modelrun.name)

src/smif/controller/setup.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44

55
import pkg_resources
66

7-
LOGGER = logging.getLogger(__name__)
8-
97

108
def copy_project_folder(directory):
119
"""Creates folder structure in the target directory
@@ -20,7 +18,7 @@ def copy_project_folder(directory):
2018
dirname = "the current directory"
2119
else:
2220
dirname = directory
23-
LOGGER.info("Created sample project in %s", dirname)
21+
logging.info("Created sample project in %s", dirname)
2422

2523

2624
def _recursive_overwrite(pkg, src, dest):

0 commit comments

Comments
 (0)