[PATCH 1 of 4 V2] [cubicweb-ctl] backport --loglevel option of pyramid to all instance commands

Laurent Peuch cortex at worlddomination.be
Wed Jul 24 16:29:29 CEST 2019


# HG changeset patch
# User Laurent Peuch <cortex at worlddomination.be>
# Date 1558454897 -7200
#      Tue May 21 18:08:17 2019 +0200
# Node ID 2e5939059a2f13e21d18104fb4c6977d4e513808
# Parent  eb83daa6949545bb81bcac6b5fda41d73a37837a
# EXP-Topic improve-cli
[cubicweb-ctl] backport --loglevel option of pyramid to all instance commands

diff --git a/cubicweb/cwctl.py b/cubicweb/cwctl.py
--- a/cubicweb/cwctl.py
+++ b/cubicweb/cwctl.py
@@ -44,6 +44,8 @@ from cubicweb.cwconfig import CubicWebCo
 from cubicweb.toolsutils import Command, rm, create_dir, underline_title
 from cubicweb.__pkginfo__ import version as cw_version
 
+LOG_LEVELS = ('debug', 'info', 'warning', 'error')
+
 # don't check duplicated commands, it occurs when reloading site_cubicweb
 CWCTL = CommandLine('cubicweb-ctl', 'The CubicWeb swiss-knife.',
                     version=cw_version, check_duplicated_command=False)
@@ -126,6 +128,13 @@ class InstanceCommand(Command):
           'help': 'launch pdb on exception',
           }
          ),
+        ("loglevel",
+         {'type': 'choice', 'default': None, 'metavar': '<log level>',
+          'choices': LOG_LEVELS, 'short': 'l',
+          'help': 'allow to specify log level for debugging (choices: %s)'
+                  % (', '.join(LOG_LEVELS)),
+          }
+         ),
     )
     actionverb = None
 
@@ -136,6 +145,9 @@ class InstanceCommand(Command):
         appid = args[0]
         cmdmeth = getattr(self, '%s_instance' % self.name)
 
+        cwconfig = cwcfg.config_for(appid)
+        init_cmdline_log_threshold(cwconfig, self['loglevel'])
+
         try:
             status = cmdmeth(appid) or 0
         except (ExecutionError, ConfigurationError) as ex:
@@ -415,7 +427,6 @@ class DeleteInstanceCommand(Command):
     name = 'delete'
     arguments = '<instance>'
     min_args = max_args = 1
-    options = ()
 
     def run(self, args):
         """run the command with its specific arguments"""
@@ -622,30 +633,31 @@ class ShellCommand(Command):
     arguments = '<instance> [batch command file(s)] [-- <script arguments>]'
     min_args = 1
     max_args = None
-    options = (
-        ('system-only',
-         {'short': 'S', 'action': 'store_true',
-          'help': 'only connect to the system source when the instance is '
-          'using multiple sources. You can\'t use this option and the '
-          '--ext-sources option at the same time.',
-          'group': 'local'
-          }),
-
-        ('ext-sources',
-         {'short': 'E', 'type': 'csv', 'metavar': '<sources>',
-          'help': "For multisources instances, specify to which sources the \
-repository should connect to for upgrading. When unspecified or 'all' given, \
-will connect to all defined sources. If 'migration' is given, appropriate \
-sources for migration will be automatically selected.",
-          'group': 'local'
-          }),
-
-        ('force',
-         {'short': 'f', 'action': 'store_true',
-          'help': 'don\'t check instance is up to date.',
-          'group': 'local'
-          }),
-
+    options = merge_options(
+        (
+            ('system-only',
+             {'short': 'S', 'action': 'store_true',
+              'help': 'only connect to the system source when the instance is '
+              'using multiple sources. You can\'t use this option and the '
+              '--ext-sources option at the same time.',
+              'group': 'local'
+              }),
+
+            ('ext-sources',
+             {'short': 'E', 'type': 'csv', 'metavar': '<sources>',
+              'help': "For multisources instances, specify to which sources the \
+    repository should connect to for upgrading. When unspecified or 'all' given, \
+    will connect to all defined sources. If 'migration' is given, appropriate \
+    sources for migration will be automatically selected.",
+              'group': 'local'
+              }),
+
+            ('force',
+             {'short': 'f', 'action': 'store_true',
+              'help': 'don\'t check instance is up to date.',
+              'group': 'local'
+              }),
+        ) + InstanceCommand.options
     )
 
     def _get_mih(self, appid):
diff --git a/cubicweb/pyramid/pyramidctl.py b/cubicweb/pyramid/pyramidctl.py
--- a/cubicweb/pyramid/pyramidctl.py
+++ b/cubicweb/pyramid/pyramidctl.py
@@ -35,9 +35,11 @@ import threading
 import subprocess
 import warnings
 
+from logilab.common.configuration import merge_options
+
 from cubicweb import ExecutionError
 from cubicweb.cwconfig import CubicWebConfiguration as cwcfg
-from cubicweb.cwctl import CWCTL, InstanceCommand, init_cmdline_log_threshold
+from cubicweb.cwctl import CWCTL, InstanceCommand
 from cubicweb.pyramid import wsgi_application_from_cwconfig
 from cubicweb.pyramid.config import get_random_secret_key
 from cubicweb.server import serverctl, set_debug
@@ -49,7 +51,6 @@ import waitress
 MAXFD = 1024
 
 DBG_FLAGS = ('RQL', 'SQL', 'REPO', 'HOOKS', 'OPS', 'SEC', 'MORE')
-LOG_LEVELS = ('debug', 'info', 'warning', 'error')
 
 
 def _generate_pyramid_ini_file(pyramid_ini_path):
@@ -97,7 +98,7 @@ class PyramidStartHandler(InstanceComman
     name = 'pyramid'
     actionverb = 'started'
 
-    options = (
+    options = merge_options((
         ('no-daemon',
          {'action': 'store_true',
           'help': 'Run the server in the foreground.'}),
@@ -115,12 +116,6 @@ class PyramidStartHandler(InstanceComman
         ('reload-interval',
          {'type': 'int', 'default': 1,
           'help': 'Interval, in seconds, between file modifications checks'}),
-        ('loglevel',
-         {'short': 'l', 'type': 'choice', 'metavar': '<log level>',
-          'default': None, 'choices': LOG_LEVELS,
-          'help': 'debug if -D is set, error otherwise; '
-                  'one of %s' % (LOG_LEVELS,),
-          }),
         ('dbglevel',
          {'type': 'multiple_choice', 'metavar': '<dbg level>',
           'default': None,
@@ -148,7 +143,7 @@ class PyramidStartHandler(InstanceComman
           'metavar': 'key1:value1,key2:value2',
           'default': {},
           'help': 'override <key> configuration file option with <value>.'}),
-    )
+    ) + InstanceCommand.options)
 
     _reloader_environ_key = 'CW_RELOADER_SHOULD_RUN'
 
@@ -369,7 +364,6 @@ class PyramidStartHandler(InstanceComman
         if self['dbglevel']:
             self['loglevel'] = 'debug'
             set_debug('|'.join('DBG_' + x.upper() for x in self['dbglevel']))
-        init_cmdline_log_threshold(cwconfig, self['loglevel'])
 
         app = wsgi_application_from_cwconfig(
             cwconfig, profile=self['profile'],
diff --git a/cubicweb/test/unittest_cwctl.py b/cubicweb/test/unittest_cwctl.py
--- a/cubicweb/test/unittest_cwctl.py
+++ b/cubicweb/test/unittest_cwctl.py
@@ -108,8 +108,11 @@ class InstanceCommandTest(unittest.TestC
         self.CWCTL.register(_TestCommand)
         self.CWCTL.register(_TestFailCommand)
 
+        self.fake_config = MagicMock()
+        self.fake_config.global_set_option = MagicMock()
+
         # pretend that this instance exists
-        patcher = patch.object(cwcfg, 'config_for', return_value=object())
+        patcher = patch.object(cwcfg, 'config_for', return_value=self.fake_config)
         patcher.start()
         self.addCleanup(patcher.stop)
 
@@ -164,6 +167,17 @@ class InstanceCommandTest(unittest.TestC
 
         test_fail_instance.assert_called_once()
 
+    def test_set_loglevel(self):
+        LOG_LEVELS = ('debug', 'info', 'warning', 'error')
+
+        for log_level in LOG_LEVELS:
+            with self.assertRaises(SystemExit) as cm:
+                self.CWCTL.run(["test", "some_instance", "--loglevel", log_level])
+            self.assertEqual(cm.exception.code, 0)
+
+            self.fake_config.global_set_option.assert_called_with('log-threshold',
+                                                                  log_level.upper())
+
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/doc/changes/3.27.rst b/doc/changes/3.27.rst
--- a/doc/changes/3.27.rst
+++ b/doc/changes/3.27.rst
@@ -20,6 +20,9 @@ New features
 * add a --pdb flag to all cubicweb-ctl command to launch (i)pdb if an exception
   occurs during a command execution.
 
+* the --loglevel flag is available for all cubicweb-ctl instance commands (and
+  not only the "pyramid" one)
+
 Backwards incompatible changes
 ------------------------------
 



More information about the cubicweb-devel mailing list