streamlit_healthcheck.streamlit-healthcheck-cli
This module provides a command-line interface (CLI) for monitoring the health of Streamlit applications. It offers commands to start an API server for health checks and to initialize a new health check configuration file.
Commands:
serve: Starts the health check API server.
Options:
--host: Host address to bind the server (default: '0.0.0.0') --port: Port to run the server on (default: 8000) --config: Path to health check configuration file (default: 'config/health_check_config.json') --log-level: Set the logging level (choices: DEBUG, INFO, WARNING, ERROR, CRITICAL; default: INFO)init: Initializes a new health check configuration file.
Options:
--config: Path to health check configuration file (default: 'config/health_check_config.json')
Usage:
Run the CLI using the following command:
python -m streamlit-healthcheck.streamlit-healthcheck-cli [COMMAND] [OPTIONS]
Example:
Start the server with default configuration
python -m streamlit-healthcheck.streamlit-healthcheck-cli serve
Start the server with custom configuration
python -m streamlit-healthcheck.streamlit-healthcheck-cli serve --host 127.0.0.1 --port 8080 --config my_config.json --log-level DEBUG
Initialize a new configuration file
python -m streamlit-healthcheck.streamlit-healthcheck-cli init --config my_config.json
Logging:
Logging is configured to output to stdout with customizable log levels.
Error Handling:
All commands handle exceptions gracefully and provide informative error messages.
1# -*- coding: utf-8 -*- 2""" 3This module provides a command-line interface (CLI) for monitoring the health of Streamlit applications. 4It offers commands to start an API server for health checks and to initialize a new health check configuration file. 5 6Commands: 7--------- 8 9- serve: 10 Starts the health check API server. 11 12 Options: 13 14 --host: Host address to bind the server (default: '0.0.0.0') 15 --port: Port to run the server on (default: 8000) 16 --config: Path to health check configuration file (default: 'config/health_check_config.json') 17 --log-level: Set the logging level (choices: DEBUG, INFO, WARNING, ERROR, CRITICAL; default: INFO) 18- init: 19 Initializes a new health check configuration file. 20 21 Options: 22 23 --config: Path to health check configuration file (default: 'config/health_check_config.json') 24 25Usage: 26------ 27 28Run the CLI using the following command: 29 30```bash 31python -m streamlit-healthcheck.streamlit-healthcheck-cli [COMMAND] [OPTIONS] 32``` 33 34Example: 35-------- 36 37Start the server with default configuration 38 39```bash 40python -m streamlit-healthcheck.streamlit-healthcheck-cli serve 41``` 42 43Start the server with custom configuration 44 45```bash 46python -m streamlit-healthcheck.streamlit-healthcheck-cli serve --host 127.0.0.1 --port 8080 --config my_config.json --log-level DEBUG 47``` 48 49 50Initialize a new configuration file 51 52```bash 53python -m streamlit-healthcheck.streamlit-healthcheck-cli init --config my_config.json 54``` 55 56 57Logging: 58-------- 59 60Logging is configured to output to stdout with customizable log levels. 61 62Error Handling: 63--------------- 64 65All commands handle exceptions gracefully and provide informative error messages. 66""" 67import click 68import logging 69import sys 70from typing import Optional 71from .server import start_api_server 72# Configure logging 73logging.basicConfig( 74 level=logging.INFO, 75 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 76 handlers=[ 77 logging.StreamHandler(sys.stdout) 78 ] 79) 80logger = logging.getLogger(__name__) 81 82 83 84@click.group() 85def cli(): 86 """ 87 Command-line entry point for the streamlit-healthcheck tool. 88 This function implements the command-line interface (CLI) used to run 89 health checks against a Streamlit application or to serve a small 90 healthcheck UI. It is intended to be registered as a console_script 91 entry point for the package. 92 93 Behavior 94 -------- 95 96 - Parse command-line arguments (e.g. target URL of the Streamlit app, 97 timeout values, logging/verbosity flags, and optional configuration 98 file path). 99 - Validate arguments and configuration. 100 - Execute one or more health checks (HTTP / status checks, simple page 101 content assertions, or custom checks defined in a config). 102 - Optionally start a lightweight HTTP server that exposes the healthcheck 103 results or a human-readable status page. 104 - Emit structured logs and progress information to stdout/stderr. 105 - Exit with a zero status on success and non-zero on failure or error. 106 107 Arguments 108 --------- 109 110 - None (reads configuration from sys.argv and environment). 111 Return 112 - None. On completion the function typically calls sys.exit() with an 113 appropriate exit code. 114 115 Exit codes 116 ----------- 117 118 - 0: All health checks passed. 119 - 1: One or more health checks failed. 120 - 2: Invalid usage or configuration. 121 - 3: Unexpected runtime error (network failure, internal exception). 122 123 Side effects 124 ------------ 125 126 - Network requests to the target Streamlit instance. 127 - May bind to a local port if serving a status UI. 128 - Configures global logging and may call sys.exit(). 129 130 Examples 131 -------- 132 133 - Run checks against a local Streamlit app: 134 streamlit-healthcheck --url http://localhost:8501 --timeout 5 135 - Serve a status UI on port 9000: 136 streamlit-healthcheck --serve --port 9000 --config /path/to/config.yml 137 Notes 138 ----- 139 140 - The exact CLI flags and behavior are defined by the implemented argument 141 parser; this docstring describes the intended responsibilities and 142 observable outcomes of the CLI entry point. 143 """ 144 145 pass 146 147@cli.command() 148@click.option( 149 '--host', 150 default='0.0.0.0', 151 help='Host address to bind the server' 152) 153@click.option( 154 '--port', 155 default=8000, 156 type=int, 157 help='Port to run the server on' 158) 159@click.option( 160 '--config', 161 default='config/health_check_config.json', 162 type=click.Path(), 163 help='Path to health check configuration file' 164) 165@click.option( 166 '--log-level', 167 default='INFO', 168 type=click.Choice(['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], case_sensitive=False), 169 help='Set the logging level' 170) 171def serve(host: str, port: int, config: str, log_level: str): 172 """ 173 Start the health check API server. 174 Sets the global logging level, prints startup information to the console, and 175 invokes the underlying server start function. Any exception raised during 176 startup is logged and re-raised as a click.ClickException. 177 178 Parameters 179 ---------- 180 181 host : str 182 Hostname or IP address to bind the server to (e.g. "0.0.0.0" or "127.0.0.1"). 183 port : int 184 TCP port number to listen on. 185 config : str 186 Filesystem path to the configuration file used to configure the health check API. 187 log_level : str 188 Logging level name (case-insensitive), e.g. "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL". 189 190 Raises 191 ------ 192 193 click.ClickException 194 If an unexpected error occurs while starting the server; the underlying 195 exception message is propagated. 196 197 Side effects 198 ------------ 199 200 - Calls logging.getLogger().setLevel to adjust the global logging level. 201 - Emits informational messages via click.echo. 202 - Calls start_api_server(host, port, config) to start the service. 203 - On failure, logs the error via logger.error before raising a click.ClickException. 204 """ 205 206 try: 207 # Set logging level 208 logging.getLogger().setLevel(log_level.upper()) 209 210 click.echo(f"Starting health check API server on {host}:{port}") 211 click.echo(f"Using config file: {config}") 212 click.echo(f"Log level: {log_level}") 213 214 # Start the server 215 start_api_server(host=host, port=port, config=config) 216 217 except Exception as e: 218 logger.error(f"Failed to start server: {str(e)}") 219 raise click.ClickException(str(e)) 220 221@cli.command() 222@click.option( 223 '--config', 224 default='config/health_check_config.json', 225 type=click.Path(), 226 help='Path to health check configuration file' 227) 228def init(config: str): 229 """ 230 Initialize and persist a healthcheck service configuration. 231 Creates a HealthCheckService for the given configuration path, writes the default 232 configuration to disk, and prints a success message to stdout. Any failure during 233 service creation or saving is logged and re-raised as a click.ClickException so 234 CLI callers receive a clean, user-facing error. 235 236 Args: 237 config (str): Path to the configuration file to create. 238 239 Raises: 240 click.ClickException: If the configuration file could not be created or saved. 241 """ 242 243 from .healthcheck import HealthCheckService 244 245 try: 246 service = HealthCheckService(config_path=config) 247 service.save_config() 248 click.echo(f"Created new configuration file at: {config}") 249 250 except Exception as e: 251 logger.error(f"Failed to create config file: {str(e)}") 252 raise click.ClickException(str(e)) 253 254def main(): 255 """ 256 Run the command-line interface and handle top-level exceptions. 257 This function acts as the script entry point. It calls the module-level cli() 258 function to execute the command-line interface. Any exception raised during 259 cli() execution is caught, logged via the module-level logger, and causes the 260 process to exit with status code 1. 261 262 Behavior: 263 264 - Calls cli(). 265 - On successful completion, returns normally (None). 266 - On any Exception, logs an error message with logger.error and terminates 267 the process by calling sys.exit(1). 268 269 Dependencies: 270 271 - Expects cli, logger, and sys to be available in the module namespace. 272 273 Usage: 274 275 Intended to be invoked when the package/script is run as a program (e.g. from 276 if __name__ == "__main__": main()). 277 """ 278 try: 279 cli() 280 except Exception as e: 281 logger.error(f"Unexpected error: {str(e)}") 282 sys.exit(1) 283 284if __name__ == '__main__': 285 main()
Command-line entry point for the streamlit-healthcheck tool. This function implements the command-line interface (CLI) used to run health checks against a Streamlit application or to serve a small healthcheck UI. It is intended to be registered as a console_script entry point for the package.
Behavior
- Parse command-line arguments (e.g. target URL of the Streamlit app, timeout values, logging/verbosity flags, and optional configuration file path).
- Validate arguments and configuration.
- Execute one or more health checks (HTTP / status checks, simple page content assertions, or custom checks defined in a config).
- Optionally start a lightweight HTTP server that exposes the healthcheck results or a human-readable status page.
- Emit structured logs and progress information to stdout/stderr.
- Exit with a zero status on success and non-zero on failure or error.
Arguments
- None (reads configuration from sys.argv and environment). Return
- None. On completion the function typically calls sys.exit() with an appropriate exit code.
Exit codes
- 0: All health checks passed.
- 1: One or more health checks failed.
- 2: Invalid usage or configuration.
- 3: Unexpected runtime error (network failure, internal exception).
Side effects
- Network requests to the target Streamlit instance.
- May bind to a local port if serving a status UI.
- Configures global logging and may call sys.exit().
Examples
- Run checks against a local Streamlit app: streamlit-healthcheck --url http://localhost:8501 --timeout 5
Serve a status UI on port 9000: streamlit-healthcheck --serve --port 9000 --config /path/to/config.yml
Notes
The exact CLI flags and behavior are defined by the implemented argument parser; this docstring describes the intended responsibilities and observable outcomes of the CLI entry point.
Start the health check API server. Sets the global logging level, prints startup information to the console, and invokes the underlying server start function. Any exception raised during startup is logged and re-raised as a click.ClickException.
Parameters
host : str Hostname or IP address to bind the server to (e.g. "0.0.0.0" or "127.0.0.1"). port : int TCP port number to listen on. config : str Filesystem path to the configuration file used to configure the health check API. log_level : str Logging level name (case-insensitive), e.g. "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL".
Raises
click.ClickException If an unexpected error occurs while starting the server; the underlying exception message is propagated.
Side effects
- Calls logging.getLogger().setLevel to adjust the global logging level.
- Emits informational messages via click.echo.
- Calls start_api_server(host, port, config) to start the service.
- On failure, logs the error via logger.error before raising a click.ClickException.
Initialize and persist a healthcheck service configuration. Creates a HealthCheckService for the given configuration path, writes the default configuration to disk, and prints a success message to stdout. Any failure during service creation or saving is logged and re-raised as a click.ClickException so CLI callers receive a clean, user-facing error.
Args: config (str): Path to the configuration file to create.
Raises: click.ClickException: If the configuration file could not be created or saved.
255def main(): 256 """ 257 Run the command-line interface and handle top-level exceptions. 258 This function acts as the script entry point. It calls the module-level cli() 259 function to execute the command-line interface. Any exception raised during 260 cli() execution is caught, logged via the module-level logger, and causes the 261 process to exit with status code 1. 262 263 Behavior: 264 265 - Calls cli(). 266 - On successful completion, returns normally (None). 267 - On any Exception, logs an error message with logger.error and terminates 268 the process by calling sys.exit(1). 269 270 Dependencies: 271 272 - Expects cli, logger, and sys to be available in the module namespace. 273 274 Usage: 275 276 Intended to be invoked when the package/script is run as a program (e.g. from 277 if __name__ == "__main__": main()). 278 """ 279 try: 280 cli() 281 except Exception as e: 282 logger.error(f"Unexpected error: {str(e)}") 283 sys.exit(1)
Run the command-line interface and handle top-level exceptions. This function acts as the script entry point. It calls the module-level cli() function to execute the command-line interface. Any exception raised during cli() execution is caught, logged via the module-level logger, and causes the process to exit with status code 1.
Behavior:
- Calls cli().
- On successful completion, returns normally (None).
- On any Exception, logs an error message with logger.error and terminates the process by calling sys.exit(1).
Dependencies:
- Expects cli, logger, and sys to be available in the module namespace.
Usage:
Intended to be invoked when the package/script is run as a program (e.g. from if __name__ == "__main__": main()).