Mini Shell

Direktori : /opt/imh-python/lib/python3.9/site-packages/ngxstats/
Upload File :
Current File : //opt/imh-python/lib/python3.9/site-packages/ngxstats/cli.py

# vim: set ts=4 sw=4 expandtab syntax=python:
"""

ngxstats.cli
Realtime Nginx stats aggregation tool
CLI Entry-point

Copyright (c) 2019-2020 InMotion Hosting, Inc.
https://www.inmotionhosting.com/

@author J. Hipps <jacobh@inmotionhosting.com>

"""

import sys
import logging
import logging.handlers
from argparse import ArgumentParser

import yaml
from yaml import CDumper

from ngxstats import master
from ngxstats import __version__, __date__
from ngxstats.util import gconf, excepthook

logger = logging.getLogger('ngxstats')


def setup_logging(
    clevel=logging.INFO, flevel=logging.INFO, logfile='/var/log/ngxstats.log'
):
    """
    Setup logging
    """
    logger.setLevel(logging.DEBUG)

    # Console
    con = logging.StreamHandler()
    con.setLevel(clevel)
    con_format = logging.Formatter("[%(process)d] %(levelname)s: %(message)s")
    con.setFormatter(con_format)
    logger.addHandler(con)

    # File
    try:
        flog = logging.handlers.WatchedFileHandler(logfile)
        flog.setLevel(flevel)
        flog_format = logging.Formatter(
            "[%(asctime)s] %(name)s (%(process)d): %(levelname)s: %(message)s"
        )
        flog.setFormatter(flog_format)
        logger.addHandler(flog)
    except Exception as e:
        logger.warning("Failed to open logfile: %s", str(e))


def parse_cli(show_help=False):
    """
    Parse CLI arguments
    """
    parser = ArgumentParser(description="Realtime Nginx stats aggregation tool")
    parser.set_defaults(
        showconf=False, loglevel=logging.INFO, logfile='/var/log/ngxstats.log'
    )
    # fmt: off
    parser.add_argument(
        '--showconf', action='store_true',
        help="Output combined global configuration",
    )
    parser.add_argument(
        '--logfile', '-l', action='store', metavar="PATH",
        help="Log output file",
    )
    parser.add_argument(
        '--debug', '-d', dest='loglevel',
        action='store_const', const=logging.DEBUG,
        help="Enable debug output",
    )
    parser.add_argument(
        '--version', '-v', action='version',
        version=f"{__version__} ({__date__})",
    )
    # fmt: on
    if show_help:
        parser.print_help()
        sys.exit(1)

    return parser.parse_args()


def _main():
    """
    CLI Entry-point
    """
    sys.excepthook = excepthook

    args = parse_cli()
    setup_logging(args.loglevel, logfile=args.logfile)
    gconf.parse_config()

    if args.showconf:
        print("---")
        # pylint:disable=protected-access
        print(yaml.dump(gconf._conf, Dumper=CDumper, default_flow_style=False))
        return 0

    master.start()


if __name__ == '__main__':
    _main()

Zerion Mini Shell 1.0