├── .gitignore ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── glogcli ├── .gitignore ├── __init__.py ├── _version.py ├── cli.py ├── dateutils.py ├── formats.py ├── graylog_api.py ├── input.py ├── output.py └── utils.py ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_api.py ├── test_config.py ├── test_date_utils.py ├── test_formats.py └── test_input.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *.cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # Jupyter Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # SageMath parsed files 79 | *.sage.py 80 | 81 | # Environments 82 | .env 83 | .venv 84 | env/ 85 | venv/ 86 | ENV/ 87 | 88 | # Spyder project settings 89 | .spyderproject 90 | .spyproject 91 | 92 | # Rope project settings 93 | .ropeproject 94 | 95 | # mkdocs documentation 96 | /site 97 | 98 | # mypy 99 | .mypy_cache/ 100 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | 6 | Contributors 7 | ------------ 8 | 9 | * Sinval Vieira 10 | * Victor Mendes 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Contributing 5 | ============ 6 | 7 | Contributions are welcome, and they are greatly appreciated! Every 8 | little bit helps, and credit will always be given. 9 | 10 | You can contribute in many ways: 11 | 12 | Types of Contributions 13 | ---------------------- 14 | 15 | Report Bugs 16 | ~~~~~~~~~~~ 17 | 18 | Report bugs at https://github.com/globocom/glog-cli/issues 19 | 20 | If you are reporting a bug, please include: 21 | 22 | * Your operating system name and version. 23 | * Any details about your local setup that might be helpful in troubleshooting. 24 | * Detailed steps to reproduce the bug. 25 | 26 | Fix Bugs 27 | ~~~~~~~~ 28 | 29 | Look through the GitHub issues for bugs. Anything tagged with "bug" 30 | and "help wanted" is open to whoever wants to implement it. 31 | 32 | Implement Features 33 | ~~~~~~~~~~~~~~~~~~ 34 | 35 | Look through the GitHub issues for features. Anything tagged with "enhancement" 36 | and "help wanted" is open to whoever wants to implement it. 37 | 38 | Write Documentation 39 | ~~~~~~~~~~~~~~~~~~~ 40 | 41 | Glog-CLI could always use more documentation, whether as part of the 42 | official Glog-CLI docs, in docstrings, or even on the web in blog posts, 43 | articles, and such. 44 | 45 | Submit Feedback 46 | ~~~~~~~~~~~~~~~ 47 | 48 | The best way to send feedback is to file an issue at https://github.com/globocom/glog-cli/issues 49 | 50 | If you are proposing a feature: 51 | 52 | * Explain in detail how it would work. 53 | * Keep the scope as narrow as possible, to make it easier to implement. 54 | * Remember that this is a volunteer-driven project, and that contributions 55 | are welcome :) 56 | 57 | Get Started! 58 | ------------ 59 | 60 | Ready to contribute? Here's how to set up `glogcli` for local development. 61 | 62 | 1. Fork the `glogcli` repo on GitHub. 63 | 2. Clone your fork locally:: 64 | 65 | $ git clone git@github.com:your_name_here/glogcli.git 66 | 67 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 68 | 69 | $ mkvirtualenv glogcli 70 | $ cd glogcli/ 71 | $ python setup.py develop 72 | 73 | 4. Create a branch for local development:: 74 | 75 | $ git checkout -b name-of-your-bugfix-or-feature 76 | 77 | Now you can make your changes locally. 78 | 79 | 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: 80 | 81 | $ flake8 glogcli tests 82 | $ python setup.py test or py.test 83 | $ tox 84 | 85 | To get flake8 and tox, just pip install them into your virtualenv. 86 | 87 | 6. Commit your changes and push your branch to GitHub:: 88 | 89 | $ git add . 90 | $ git commit -m "Your detailed description of your changes." 91 | $ git push origin name-of-your-bugfix-or-feature 92 | 93 | 7. Submit a pull request through the GitHub website. 94 | 95 | Pull Request Guidelines 96 | ----------------------- 97 | 98 | Before you submit a pull request, check that it meets these guidelines: 99 | 100 | 1. The pull request should include tests. 101 | 2. If the pull request adds functionality, the docs should be updated. Put 102 | your new functionality into a function with a docstring, and add the 103 | feature to the list in README.rst. 104 | 3. The pull request should work for Python 2.6, 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check 105 | https://travis-ci.org/sinvalmendes/glogcli/pull_requests 106 | and make sure that the tests pass for all supported Python versions. 107 | 108 | Tips 109 | ---- 110 | 111 | To run a subset of tests:: 112 | 113 | $ py.test tests.test_glogcli 114 | 115 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | History 3 | ======= 4 | 5 | 0.1.0 (2016-09-21) 6 | ------------------ 7 | 8 | * First release on PyPI. 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2016 Globo.com 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | 2 | include AUTHORS.rst 3 | 4 | include CONTRIBUTING.rst 5 | include HISTORY.rst 6 | include LICENSE 7 | include README.rst 8 | 9 | recursive-include tests * 10 | recursive-exclude * __pycache__ 11 | recursive-exclude * *.py[co] 12 | 13 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 14 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-test clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | 14 | define PRINT_HELP_PYSCRIPT 15 | import re, sys 16 | 17 | for line in sys.stdin: 18 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 19 | if match: 20 | target, help = match.groups() 21 | print("%-20s %s" % (target, help)) 22 | endef 23 | export PRINT_HELP_PYSCRIPT 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | 32 | clean-build: ## remove build artifacts 33 | rm -fr build/ 34 | rm -fr dist/ 35 | rm -fr .eggs/ 36 | find . -name '*.egg-info' -exec rm -fr {} + 37 | find . -name '*.egg' -exec rm -f {} + 38 | 39 | clean-pyc: ## remove Python file artifacts 40 | find . -name '*.pyc' -exec rm -f {} + 41 | find . -name '*.pyo' -exec rm -f {} + 42 | find . -name '*~' -exec rm -f {} + 43 | find . -name '__pycache__' -exec rm -fr {} + 44 | 45 | clean-test: ## remove test and coverage artifacts 46 | rm -fr .tox/ 47 | rm -f .coverage 48 | rm -fr htmlcov/ 49 | 50 | lint: ## check style with flake8 51 | python setup.py flake8 52 | 53 | test: ## run tests quickly with the default Python 54 | python setup.py test 55 | 56 | 57 | test-all: ## run tests on every Python version with tox 58 | tox 59 | 60 | coverage: ## check code coverage quickly with the default Python 61 | coverage run --source glogcli py.test 62 | 63 | coverage report -m 64 | coverage html 65 | $(BROWSER) htmlcov/index.html 66 | 67 | docs: ## generate Sphinx HTML documentation, including API docs 68 | rm -f docs/glogcli.rst 69 | rm -f docs/modules.rst 70 | sphinx-apidoc -o docs/ glogcli 71 | $(MAKE) -C docs clean 72 | $(MAKE) -C docs html 73 | $(BROWSER) docs/_build/html/index.html 74 | 75 | servedocs: docs ## compile the docs watching for changes 76 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 77 | 78 | release: clean ## package and upload a release 79 | python setup.py sdist upload 80 | python setup.py bdist_wheel upload 81 | 82 | dist: clean ## builds source and wheel package 83 | python setup.py sdist 84 | python setup.py bdist_wheel 85 | ls -l dist 86 | 87 | install: clean ## install the package to the active Python's site-packages 88 | python setup.py install 89 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Glog-CLI 2 | =============================== 3 | 4 | * Free software: Apache Software License 2.0 5 | 6 | Glog-CLI is an open source command line interface for Graylog2. 7 | 8 | ## Installation 9 | 10 | Requirements: Python 2 11 | 12 | Try: 13 | 14 | ```bash 15 | pip install glogcli 16 | ``` 17 | 18 | or: 19 | 20 | ```bash 21 | easy_install glogcli 22 | ``` 23 | 24 | or you can even install it from a GitHub clone: 25 | 26 | ```bash 27 | git clone https://github.com/globocom/glog-cli 28 | cd glog-cli/ 29 | pip install . -r requirements.txt 30 | ``` 31 | 32 | ## Usage 33 | 34 | Glog-CLI enables you to make searches using the official Graylog query language. To understand how to make queries 35 | please see the [documentation](http://docs.graylog.org/en/2.1/pages/queries.html). 36 | 37 | Once you've installed the tool now it's time to run some commands, the following: 38 | 39 | ```bash 40 | glogcli -h mygraylog.server.com -u john.doe -p password -@ "10 minutes ago" "source:my-app-server" 41 | ``` 42 | 43 | ```bash 44 | glogcli -h mygraylog.server.com -u john.doe -p password "message:200" 45 | ``` 46 | ```bash 47 | glogcli -h mygraylog.server.com -u john.doe -p password -f 48 | ``` 49 | 50 | ```bash 51 | glogcli -h mygraylog.server.com -u john.doe -p password "level:DEBUG" 52 | ``` 53 | 54 | ```bash 55 | glogcli -h mygraylog.server.com -u john.doe -p password "level:DEBUG" -f 56 | ``` 57 | 58 | ```bash 59 | glogcli -h mygraylog.server.com -u john.doe -p password "level:DEBUG" -d --fields timestamp,level,message -o dump.csv 60 | ``` 61 | 62 | ```bash 63 | glogcli -h mygraylog.server.com -u john-doe -p password -@ "2016-11-21 00:00:00" -# "2016-11-21 01:00:00" 'message:blabla' 64 | ``` 65 | 66 | ```bash 67 | glogcli -e dev -r short 68 | ``` 69 | 70 | ```bash 71 | glogcli -e dev -r short -st mystreamid 72 | ``` 73 | 74 | ```bash 75 | glogcli -e dev -r short -st '*' 76 | ``` 77 | 78 | 79 | ## Configuration 80 | 81 | 82 | Glog-CLI can reuse some common configurations like address of your Graylog server and your credentials, it will look for a 83 | *~/.glogcli.cfg* or a *glogcli.cfg* (in your current directory). Glog-CLI will use default environment and format 84 | whenever an environment or format is omitted. 85 | 86 | Here is a example for your glogcli.cfg file: 87 | 88 | ``` 89 | [environment:default] 90 | host=mygraylogserver.com 91 | port=443 92 | username=john.doe 93 | 94 | [environment:dev] 95 | host=mygraylogserver.dev.com 96 | port=443 97 | proxy=mycompanyproxy.com 98 | username=john.doe 99 | default_stream=57e14cde6fb78216a60d35e8 100 | 101 | [format:default] 102 | format={host} {level} {facility} {timestamp} {message} 103 | 104 | [format:short] 105 | format=[{timestamp}] {level} {message} 106 | 107 | [format:long] 108 | format=time: [{timestamp}] level: {level} msg: {message} tags: {tags} 109 | color=false 110 | ``` 111 | 112 | Please run the *help* command to more detailed information about all the client features. 113 | 114 | ``` 115 | Usage: glogcli [OPTIONS] [QUERY] 116 | 117 | Options: 118 | -v, --version Prints your glogcli version 119 | -h, --host TEXT Your graylog node's host 120 | -e, --environment TEXT Label of a preconfigured graylog node 121 | -sq, --saved-query List user saved queries for selection 122 | --port TEXT Your graylog port 123 | --no-tls Not use TLS to connect to Graylog server 124 | -u, --username TEXT Your graylog username 125 | -p, --password TEXT Your graylog password (default: prompt) 126 | -k, --keyring / -nk, --no-keyring 127 | Use keyring to store/retrieve password 128 | -@, --search-from TEXT Query range from 129 | -#, --search-to TEXT Query range to (default: now) 130 | --tail Show the last n lines for the query 131 | (default) 132 | -d, --dump Print the query result as a csv 133 | --fields TEXT Comma separated fields to be printed in the 134 | csv. 135 | -o, --output TEXT Output logs to file (only tail/dump mode) 136 | -f, --follow Poll the logging server for new logs 137 | matching the query (sets search from to now, 138 | limit to None) 139 | -n, --limit INTEGER Limit the number of results (default: 100) 140 | -a, --latency INTEGER Latency of polling queries (default: 2) 141 | -st, --stream TEXT Stream ID of the stream to query (default: 142 | no stream filter) 143 | -s, --sort TEXT Field used for sorting (default: timestamp) 144 | --asc / --desc Sort ascending / descending 145 | --proxy TEXT Proxy to use for the http/s request 146 | -r, --format-template TEXT Message format template for the log 147 | (default: default format 148 | --no-color Don't show colored logs 149 | -c, --config TEXT Custom config file path 150 | --help Show this message and exit. 151 | ``` 152 | 153 | ## Contributing 154 | See [contributing](https://github.com/globocom/glog-cli/blob/master/CONTRIBUTING.rst) document to learn how to contribute with us. 155 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Glog-CLI 2 | =============================== 3 | 4 | * Free software: Apache Software License 2.0 5 | 6 | Glog-CLI is an open source command line interface for Graylog2. 7 | 8 | Instalation 9 | -------- 10 | Try: 11 | 12 | pip install glogcli 13 | 14 | or: 15 | 16 | easy_install glogcli 17 | 18 | or you can even install it from a GitHub clone: 19 | 20 | git clone https://github.com/globocom/glog-cli 21 | cd glog-cli/ 22 | pip install . -r requirements.txt 23 | 24 | Usage 25 | -------- 26 | Glog-CLI enables you to make searches using the official Graylog query language. To understand how to make queries 27 | please see the `documentation `. 28 | 29 | Once you've installed the tool now it's time to run some commands, the following: 30 | 31 | > glogcli -h mygraylog.server.com -u john.doe -p password -@ "10 minutes ago" "source:my-app-server" 32 | 33 | - 34 | 35 | > glogcli -h mygraylog.server.com -u john.doe -p password "message:200" 36 | 37 | - 38 | 39 | > glogcli -h mygraylog.server.com -u john.doe -p password -f 40 | 41 | - 42 | 43 | > glogcli -h mygraylog.server.com -u john.doe -p password "level:DEBUG" 44 | 45 | - 46 | 47 | > glogcli -h mygraylog.server.com -u john.doe -p password "level:DEBUG" -f 48 | 49 | - 50 | 51 | > glogcli -h mygraylog.server.com -u john.doe -p password "level:DEBUG" -d --fields timestamp,level,message -o dump.csv 52 | 53 | - 54 | 55 | > glogcli -h mygraylog.server.com -u john-doe -p password -@ "2016-11-21 00:00:00" -# "2016-11-21 01:00:00" 'message:blabla' 56 | 57 | - 58 | 59 | > glogcli -e dev -r short 60 | 61 | - 62 | 63 | > glogcli -e dev -r short -st mystreamid 64 | 65 | - 66 | 67 | > glogcli -e dev -r short -st '*' 68 | 69 | 70 | 71 | Configuration 72 | -------- 73 | 74 | Glog-CLI can reuse some common configurations like address of your Graylog server and your credentials, it will look for a 75 | *~/.glogcli.cfg* or a *glogcli.cfg* (in your current directory). Glog-CLI will use default environment and format 76 | whenever an environment or format is omitted. 77 | 78 | Here is a example for your glogcli.cfg file: 79 | 80 | [environment:default] 81 | host=mygraylogserver.com 82 | port=443 83 | username=john.doe 84 | 85 | [environment:dev] 86 | host=mygraylogserver.dev.com 87 | port=443 88 | proxy=mycompanyproxy.com 89 | username=john.doe 90 | default_stream=57e14cde6fb78216a60d35e8 91 | 92 | [format:default] 93 | format={host} {level} {facility} {timestamp} {message} 94 | 95 | [format:short] 96 | format=[{timestamp}] {level} {message} 97 | 98 | [format:long] 99 | format=time: [{timestamp}] level: {level} msg: {message} tags: {tags} 100 | color=false 101 | 102 | Please run the *help* command to more detailed information about all the client features. 103 | 104 | Usage: glogcli [OPTIONS] [QUERY] 105 | 106 | Options: 107 | -v, --version Prints your glogcli version 108 | -h, --host TEXT Your graylog node's host 109 | -e, --environment TEXT Label of a preconfigured graylog node 110 | -sq, --saved-query List user saved queries for selection 111 | --port TEXT Your graylog port 112 | --no-tls Not use TLS to connect to Graylog server 113 | -u, --username TEXT Your graylog username 114 | -p, --password TEXT Your graylog password (default: prompt) 115 | -k, --keyring / -nk, --no-keyring 116 | Use keyring to store/retrieve password 117 | -@, --search-from TEXT Query range from 118 | -#, --search-to TEXT Query range to (default: now) 119 | --tail Show the last n lines for the query 120 | (default) 121 | -d, --dump Print the query result as a csv 122 | --fields TEXT Comma separated fields to be printed in the 123 | csv. 124 | -o, --output TEXT Output logs to file (only tail/dump mode) 125 | -f, --follow Poll the logging server for new logs 126 | matching the query (sets search from to now, 127 | limit to None) 128 | -n, --limit INTEGER Limit the number of results (default: 100) 129 | -a, --latency INTEGER Latency of polling queries (default: 2) 130 | -st, --stream TEXT Stream ID of the stream to query (default: 131 | no stream filter) 132 | -s, --sort TEXT Field used for sorting (default: timestamp) 133 | --asc / --desc Sort ascending / descending 134 | --proxy TEXT Proxy to use for the http/s request 135 | -r, --format-template TEXT Message format template for the log 136 | (default: default format 137 | --no-color Don't show colored logs 138 | -c, --config TEXT Custom config file path 139 | --help Show this message and exit. 140 | 141 | 142 | Contributing 143 | -------- 144 | 145 | See `contributing ` document to learn how to contribute with us. 146 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/glogcli.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/glogcli.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/glogcli" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/glogcli" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # glogcli documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another 20 | # directory, add these directories to sys.path here. If the directory is 21 | # relative to the documentation root, use os.path.abspath to make it 22 | # absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # Get the project root dir, which is the parent dir of this 26 | cwd = os.getcwd() 27 | project_root = os.path.dirname(cwd) 28 | 29 | # Insert the project root dir as the first element in the PYTHONPATH. 30 | # This lets us ensure that the source package is imported, and that its 31 | # version is used. 32 | sys.path.insert(0, project_root) 33 | 34 | import glogcli 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 44 | 45 | # Add any paths that contain templates here, relative to this directory. 46 | templates_path = ['_templates'] 47 | 48 | # The suffix of source filenames. 49 | source_suffix = '.rst' 50 | 51 | # The encoding of source files. 52 | #source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = u'Glog-CLI' 59 | copyright = u"2016, Sinval Vieira Mendes Neto" 60 | 61 | # The version info for the project you're documenting, acts as replacement 62 | # for |version| and |release|, also used in various other places throughout 63 | # the built documents. 64 | # 65 | # The short X.Y version. 66 | version = glogcli.__version__ 67 | # The full version, including alpha/beta/rc tags. 68 | release = glogcli.__version__ 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | #language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to 75 | # some non-false value, then it is used: 76 | #today = '' 77 | # Else, today_fmt is used as the format for a strftime call. 78 | #today_fmt = '%B %d, %Y' 79 | 80 | # List of patterns, relative to source directory, that match files and 81 | # directories to ignore when looking for source files. 82 | exclude_patterns = ['_build'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | #default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | #add_function_parentheses = True 90 | 91 | # If true, the current module name will be prepended to all description 92 | # unit titles (such as .. function::). 93 | #add_module_names = True 94 | 95 | # If true, sectionauthor and moduleauthor directives will be shown in the 96 | # output. They are ignored by default. 97 | #show_authors = False 98 | 99 | # The name of the Pygments (syntax highlighting) style to use. 100 | pygments_style = 'sphinx' 101 | 102 | # A list of ignored prefixes for module index sorting. 103 | #modindex_common_prefix = [] 104 | 105 | # If true, keep warnings as "system message" paragraphs in the built 106 | # documents. 107 | #keep_warnings = False 108 | 109 | 110 | # -- Options for HTML output ------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | html_theme = 'default' 115 | 116 | # Theme options are theme-specific and customize the look and feel of a 117 | # theme further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. If None, it defaults to 125 | # " v documentation". 126 | #html_title = None 127 | 128 | # A shorter title for the navigation bar. Default is the same as 129 | # html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the 133 | # top of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon 137 | # of the docs. This file should be a Windows icon file (.ico) being 138 | # 16x16 or 32x32 pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) 142 | # here, relative to this directory. They are copied after the builtin 143 | # static files, so a file named "default.css" will overwrite the builtin 144 | # "default.css". 145 | html_static_path = ['_static'] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page 148 | # bottom, using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names 159 | # to template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. 175 | # Default is True. 176 | #html_show_sphinx = True 177 | 178 | # If true, "(C) Copyright ..." is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_copyright = True 181 | 182 | # If true, an OpenSearch description file will be output, and all pages 183 | # will contain a tag referring to it. The value of this option 184 | # must be the base URL from which the finished HTML is served. 185 | #html_use_opensearch = '' 186 | 187 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 188 | #html_file_suffix = None 189 | 190 | # Output file base name for HTML help builder. 191 | htmlhelp_basename = 'glogclidoc' 192 | 193 | 194 | # -- Options for LaTeX output ------------------------------------------ 195 | 196 | latex_elements = { 197 | # The paper size ('letterpaper' or 'a4paper'). 198 | #'papersize': 'letterpaper', 199 | 200 | # The font size ('10pt', '11pt' or '12pt'). 201 | #'pointsize': '10pt', 202 | 203 | # Additional stuff for the LaTeX preamble. 204 | #'preamble': '', 205 | } 206 | 207 | # Grouping the document tree into LaTeX files. List of tuples 208 | # (source start file, target name, title, author, documentclass 209 | # [howto/manual]). 210 | latex_documents = [ 211 | ('index', 'glogcli.tex', 212 | u'Glog-CLI Documentation', 213 | u'Sinval Vieira Mendes Neto', 'manual'), 214 | ] 215 | 216 | # The name of an image file (relative to this directory) to place at 217 | # the top of the title page. 218 | #latex_logo = None 219 | 220 | # For "manual" documents, if this is true, then toplevel headings 221 | # are parts, not chapters. 222 | #latex_use_parts = False 223 | 224 | # If true, show page references after internal links. 225 | #latex_show_pagerefs = False 226 | 227 | # If true, show URL addresses after external links. 228 | #latex_show_urls = False 229 | 230 | # Documents to append as an appendix to all manuals. 231 | #latex_appendices = [] 232 | 233 | # If false, no module index is generated. 234 | #latex_domain_indices = True 235 | 236 | 237 | # -- Options for manual page output ------------------------------------ 238 | 239 | # One entry per manual page. List of tuples 240 | # (source start file, name, description, authors, manual section). 241 | man_pages = [ 242 | ('index', 'glogcli', 243 | u'Glog-CLI Documentation', 244 | [u'Sinval Vieira Mendes Neto'], 1) 245 | ] 246 | 247 | # If true, show URL addresses after external links. 248 | #man_show_urls = False 249 | 250 | 251 | # -- Options for Texinfo output ---------------------------------------- 252 | 253 | # Grouping the document tree into Texinfo files. List of tuples 254 | # (source start file, target name, title, author, 255 | # dir menu entry, description, category) 256 | texinfo_documents = [ 257 | ('index', 'glogcli', 258 | u'Glog-CLI Documentation', 259 | u'Sinval Vieira Mendes Neto', 260 | 'glogcli', 261 | 'One line description of project.', 262 | 'Miscellaneous'), 263 | ] 264 | 265 | # Documents to append as an appendix to all manuals. 266 | #texinfo_appendices = [] 267 | 268 | # If false, no module index is generated. 269 | #texinfo_domain_indices = True 270 | 271 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 272 | #texinfo_show_urls = 'footnote' 273 | 274 | # If true, do not generate a @detailmenu in the "Top" node's menu. 275 | #texinfo_no_detailmenu = False 276 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. glogcli documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Glog-CLI's documentation! 7 | ====================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authorshistory 19 | 20 | Indices and tables 21 | ================== 22 | 23 | * :ref:`genindex` 24 | * :ref:`modindex` 25 | * :ref:`search` 26 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | 8 | Stable release 9 | -------------- 10 | 11 | To install Glog-CLI, run this command in your terminal: 12 | 13 | .. code-block:: console 14 | 15 | $ pip install glogcli 16 | 17 | This is the preferred method to install Glog-CLI, as it will always install the most recent stable release. 18 | 19 | If you don't have `pip`_ installed, this `Python installation guide`_ can guide 20 | you through the process. 21 | 22 | .. _pip: https://pip.pypa.io 23 | .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ 24 | 25 | 26 | From sources 27 | ------------ 28 | 29 | The sources for Glog-CLI can be downloaded from the `Github repo`_. 30 | 31 | You can either clone the public repository: 32 | 33 | .. code-block:: console 34 | 35 | $ git clone git://github.com/sinvalmendes/glogcli 36 | 37 | Or download the `tarball`_: 38 | 39 | .. code-block:: console 40 | 41 | $ curl -OL https://github.com/sinvalmendes/glogcli/tarball/master 42 | 43 | Once you have a copy of the source, you can install it with: 44 | 45 | .. code-block:: console 46 | 47 | $ python setup.py install 48 | 49 | 50 | .. _Github repo: https://github.com/sinvalmendes/glogcli 51 | .. _tarball: https://github.com/sinvalmendes/glogcli/tarball/master 52 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\glogcli.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\glogcli.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | To use Glog-CLI in a project:: 6 | 7 | import glogcli 8 | -------------------------------------------------------------------------------- /glogcli/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /glogcli/__init__.py: -------------------------------------------------------------------------------- 1 | from glogcli._version import get_versions 2 | 3 | __version__ = get_versions()['version'] 4 | del get_versions 5 | -------------------------------------------------------------------------------- /glogcli/_version.py: -------------------------------------------------------------------------------- 1 | #! -*- coding: utf-8 -*- 2 | 3 | """ 4 | Retrieval of version number 5 | 6 | This file helps to compute a version number in source trees obtained from 7 | git-archive tarball (such as those provided by githubs download-from-tag 8 | feature). Distribution tarballs (built by setup.py sdist) and build 9 | directories (produced by setup.py build) will contain a much shorter file 10 | that just contains the computed version number. 11 | This file was generated by PyScaffold. 12 | """ 13 | 14 | import inspect 15 | import os 16 | import re 17 | import subprocess 18 | import sys 19 | 20 | __location__ = os.path.join(os.getcwd(), os.path.dirname( 21 | inspect.getfile(inspect.currentframe()))) 22 | 23 | # these strings will be replaced by git during git-archive 24 | git_refnames = "$Format:%d$" 25 | git_full = "$Format:%H$" 26 | 27 | # general settings 28 | tag_prefix = 'v' # tags are like v1.2.0 29 | package = "glogcli" 30 | namespace = [] 31 | root_pkg = namespace[0] if namespace else package 32 | if namespace: 33 | pkg_path = os.path.join(*namespace[-1].split('.') + [package]) 34 | else: 35 | pkg_path = package 36 | 37 | 38 | class ShellCommand(object): 39 | def __init__(self, command, shell=True, cwd=None): 40 | self._command = command 41 | self._shell = shell 42 | self._cwd = cwd 43 | 44 | def __call__(self, *args): 45 | command = "{cmd} {args}".format(cmd=self._command, 46 | args=subprocess.list2cmdline(args)) 47 | output = subprocess.check_output(command, 48 | shell=self._shell, 49 | cwd=self._cwd, 50 | stderr=subprocess.STDOUT, 51 | universal_newlines=True) 52 | return self._yield_output(output) 53 | 54 | def _yield_output(self, msg): 55 | for line in msg.splitlines(): 56 | yield line 57 | 58 | 59 | def get_git_cmd(**args): 60 | if sys.platform == "win32": 61 | for cmd in ["git.cmd", "git.exe"]: 62 | git = ShellCommand(cmd, **args) 63 | try: 64 | git("--version") 65 | except (subprocess.CalledProcessError, OSError): 66 | continue 67 | return git 68 | return None 69 | else: 70 | git = ShellCommand("git", **args) 71 | try: 72 | git("--version") 73 | except (subprocess.CalledProcessError, OSError): 74 | return None 75 | return git 76 | 77 | 78 | def version_from_git(tag_prefix, root, verbose=False): 79 | # this runs 'git' from the root of the source tree. This only gets called 80 | # if the git-archive 'subst' keywords were *not* expanded, and 81 | # _version.py hasn't already been rewritten with a short version string, 82 | # meaning we're inside a checked out source tree. 83 | git = get_git_cmd(cwd=root) 84 | if not git: 85 | print("no git found") 86 | return None 87 | try: 88 | tag = next(git("describe", "--tags", "--dirty", "--always")) 89 | except subprocess.CalledProcessError: 90 | return None 91 | if not tag.startswith(tag_prefix): 92 | if verbose: 93 | print("tag '{}' doesn't start with prefix '{}'".format(tag, 94 | tag_prefix)) 95 | return None 96 | tag = tag[len(tag_prefix):] 97 | sha1 = next(git("rev-parse", "HEAD")) 98 | full = sha1.strip() 99 | if tag.endswith("-dirty"): 100 | full += "-dirty" 101 | return {"version": tag, "full": full} 102 | 103 | 104 | def get_keywords(versionfile_abs): 105 | # the code embedded in _version.py can just fetch the value of these 106 | # keywords. When used from setup.py, we don't want to import _version.py, 107 | # so we do it with a regexp instead. This function is not used from 108 | # _version.py. 109 | keywords = dict() 110 | try: 111 | with open(versionfile_abs, "r") as fh: 112 | for line in fh.readlines(): 113 | if line.strip().startswith("git_refnames ="): 114 | mo = re.search(r'=\s*"(.*)"', line) 115 | if mo: 116 | keywords["refnames"] = mo.group(1) 117 | if line.strip().startswith("git_full ="): 118 | mo = re.search(r'=\s*"(.*)"', line) 119 | if mo: 120 | keywords["full"] = mo.group(1) 121 | except EnvironmentError: 122 | return None 123 | return keywords 124 | 125 | 126 | def version_from_keywords(keywords, tag_prefix, verbose=False): 127 | if not keywords: 128 | return None # keyword-finding function failed to find keywords 129 | refnames = keywords["refnames"].strip() 130 | if refnames.startswith("$Format"): 131 | if verbose: 132 | print("keywords are unexpanded, not using") 133 | return None # unexpanded, so not in an unpacked git-archive tarball 134 | refs = set([r.strip() for r in refnames.strip("()").split(",")]) 135 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of 136 | # just "foo-1.0". If we see a "tag: " prefix, prefer those. 137 | TAG = "tag: " 138 | tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) 139 | if not tags: 140 | # Either we're using git < 1.8.3, or there really are no tags. We use 141 | # a heuristic: assume all version tags have a digit. The old git %d 142 | # expansion behaves like git log --decorate=short and strips out the 143 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish 144 | # between branches and tags. By ignoring refnames without digits, we 145 | # filter out many common branch names like "release" and 146 | # "stabilization", as well as "HEAD" and "master". 147 | tags = set([r for r in refs if re.search(r'\d', r)]) 148 | if verbose: 149 | print("discarding '{}', no digits".format(",".join(refs - tags))) 150 | if verbose: 151 | print("likely tags: {}".format(",".join(sorted(tags)))) 152 | for ref in sorted(tags): 153 | # sorting will prefer e.g. "2.0" over "2.0rc1" 154 | if ref.startswith(tag_prefix): 155 | r = ref[len(tag_prefix):] 156 | if verbose: 157 | print("picking {}".format(r)) 158 | return {"version": r, 159 | "full": keywords["full"].strip()} 160 | else: 161 | if verbose: 162 | print("no suitable tags, using full revision id") 163 | return {"version": keywords["full"].strip(), 164 | "full": keywords["full"].strip()} 165 | 166 | 167 | def version_from_parentdir(parentdir_prefix, root, verbose=False): 168 | # Source tarballs conventionally unpack into a directory that includes 169 | # both the project name and a version string. 170 | dirname = os.path.basename(root) 171 | if not dirname.startswith(parentdir_prefix): 172 | if verbose: 173 | print("guessing rootdir is '{}', but '{}' doesn't start with " 174 | "prefix '{}'".format(root, dirname, parentdir_prefix)) 175 | return None 176 | version = dirname[len(parentdir_prefix):].split('-')[0] 177 | return {"version": version, "full": ""} 178 | 179 | 180 | def git2pep440(ver_str): 181 | dash_count = ver_str.count('-') 182 | if dash_count == 0: 183 | return ver_str 184 | elif dash_count == 1: 185 | return ver_str.split('-')[0] + "+dirty" 186 | elif dash_count == 2: 187 | tag, commits, sha1 = ver_str.split('-') 188 | return "{}.post0.dev{}+{}".format(tag, commits, sha1) 189 | elif dash_count == 3: 190 | tag, commits, sha1, _ = ver_str.split('-') 191 | return "{}.post0.dev{}+{}.dirty".format(tag, commits, sha1) 192 | else: 193 | raise RuntimeError("Invalid version string") 194 | 195 | 196 | def get_versions(verbose=False): 197 | vcs_kwds = {"refnames": git_refnames, "full": git_full} 198 | parentdir = package + '-' 199 | root = __location__ 200 | # pkg_path is the relative path from the top of the source 201 | # tree (where the .git directory might live) to this file. 202 | # Invert this to find the root of our package. 203 | for _ in pkg_path.split(os.sep): 204 | root = os.path.dirname(root) 205 | 206 | # different version retrieval methods as (method, args, comment) 207 | ver_retrieval = [ 208 | (version_from_keywords, (vcs_kwds, tag_prefix, verbose), 209 | 'expanded keywords'), 210 | (version_from_parentdir, (parentdir, root, verbose), 'parentdir'), 211 | (version_from_git, (tag_prefix, root, verbose), 'git') 212 | ] 213 | for method, args, comment in ver_retrieval: 214 | ver = method(*args) 215 | if ver: 216 | if verbose: 217 | print("got version from {}".format(comment)) 218 | break 219 | else: 220 | ver = {"version": "unknown", "full": ""} 221 | ver['version'] = git2pep440(ver['version']) 222 | return ver 223 | -------------------------------------------------------------------------------- /glogcli/cli.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import division, print_function, absolute_import 5 | import click 6 | import arrow 7 | from glogcli.graylog_api import SearchRange, SearchQuery, GraylogAPIFactory 8 | from glogcli.utils import get_config, get_color_option, get_glogcli_version 9 | from glogcli.output import LogPrinter 10 | from glogcli.input import CliInterface 11 | from glogcli.formats import FormatterFactory 12 | from glogcli import utils 13 | 14 | 15 | @click.command() 16 | @click.option("-v", "--version", default=False, is_flag=True, help="Prints your glogcli version") 17 | @click.option("-h", "--host", default=None, help="Your graylog node's host") 18 | @click.option("-e", "--environment", default='default', help="Label of a preconfigured graylog node") 19 | @click.option("-sq", "--saved-query", is_flag=True, default=False, help="List user saved queries for selection") 20 | @click.option("--port", default=None, help="Your graylog port") 21 | @click.option("--no-tls", default=False, is_flag=True, help="Not use TLS to connect to Graylog server") 22 | @click.option("-u", "--username", default=None, help="Your graylog username") 23 | @click.option("-p", "--password", default=None, help="Your graylog password (default: prompt)") 24 | @click.option("-k/-nk", "--keyring/--no-keyring", default=False, help="Use keyring to store/retrieve password") 25 | @click.option("-@", "--search-from", default=None, help="Query range from") 26 | @click.option("-#", "--search-to", default=None, help="Query range to (default: now)") 27 | @click.option('--tail', 'mode', flag_value='tail', default=True, help="Show the last n lines for the query (default)") 28 | @click.option('-d', '--dump', 'mode', flag_value='dump', help="Print the query result as a csv") 29 | @click.option('--fields', default=None, help="Comma separated fields to be printed in the csv. ", callback=lambda ctx, param, v: v.split(',') if v else None) 30 | @click.option('-o', '--output', default=None, help="Output logs to file (only tail/dump mode)") 31 | @click.option("-f", "--follow", default=False, is_flag=True, help="Poll the logging server for new logs matching the query (sets search from to now, limit to None)") 32 | @click.option("-n", "--limit", default=100, help="Limit the number of results (default: 100)") 33 | @click.option("-a", "--latency", default=2, help="Latency of polling queries (default: 2)") 34 | @click.option("-st", "--stream", default=None, help="Stream ID of the stream to query (default: no stream filter)") 35 | @click.option('--sort', '-s', default=None, help="Field used for sorting (default: timestamp)") 36 | @click.option("--asc/--desc", default=False, help="Sort ascending / descending") 37 | @click.option("--proxy", default=None, help="Proxy to use for the http/s request") 38 | @click.option('-r', '--format-template', default="default", help="Message format template for the log (default: default format") 39 | @click.option("--no-color", default=False, is_flag=True, help="Don't show colored logs") 40 | @click.option("-c", "--config", default="~/.glogcli.cfg", help="Custom config file path") 41 | @click.argument('query', default="*") 42 | def run(version, 43 | host, 44 | environment, 45 | saved_query, 46 | port, 47 | no_tls, 48 | username, 49 | password, 50 | keyring, 51 | search_from, 52 | search_to, 53 | mode, 54 | fields, 55 | output, 56 | follow, 57 | limit, 58 | latency, 59 | stream, 60 | sort, 61 | asc, 62 | proxy, 63 | format_template, 64 | no_color, 65 | config, 66 | query): 67 | 68 | cfg = get_config(config_file_path=config) 69 | 70 | if version: 71 | click.echo(get_glogcli_version()) 72 | exit() 73 | 74 | if search_from and follow: 75 | click.echo("-f (follow) and -@ (search from) are conflicting options, please choose one of them.") 76 | exit() 77 | 78 | if cfg.has_option(section='environment:%s' % environment, option='port') and port is None: 79 | port = cfg.get(section='environment:%s' % environment, option='port') 80 | 81 | if search_from is None: 82 | search_from = "5 minutes ago" 83 | 84 | graylog_api = GraylogAPIFactory.get_graylog_api(cfg, environment, host, password, port, proxy, no_tls, username, keyring) 85 | 86 | sr = SearchRange(from_time=search_from, to_time=search_to) 87 | 88 | if follow: 89 | limit = None 90 | sort = None 91 | sr.from_time = arrow.now().replace(seconds=-latency - 1) 92 | sr.to_time = arrow.now().replace(seconds=-latency) 93 | 94 | limit = None if limit <= 0 else limit 95 | fields = fields if mode == 'dump' else utils.extract_fields_from_format(cfg, format_template) 96 | color = get_color_option(cfg, format_template, no_color) 97 | 98 | stream_filter = CliInterface.select_stream(graylog_api, stream) 99 | if saved_query: 100 | query, fields = CliInterface.select_saved_query(graylog_api) 101 | 102 | q = SearchQuery(search_range=sr, query=query, limit=limit, filter=stream_filter, fields=fields, sort=sort, ascending=asc) 103 | 104 | formatter = FormatterFactory.get_formatter(mode, cfg, format_template, fields, color) 105 | LogPrinter().run_logprint(graylog_api, q, formatter, follow, output) 106 | 107 | 108 | if __name__ == "__main__": 109 | run() 110 | -------------------------------------------------------------------------------- /glogcli/dateutils.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import parsedatetime.parsedatetime as pdt 3 | import datetime 4 | import arrow 5 | import six 6 | from glogcli.utils import LOCAL_TIMEZONE 7 | 8 | 9 | def datetime_parser(s): 10 | try: 11 | ts = arrow.get(s) 12 | if ts.tzinfo == arrow.get().tzinfo: 13 | ts = ts.replace(tzinfo=LOCAL_TIMEZONE) 14 | except: 15 | c = pdt.Calendar() 16 | result, what = c.parse(s) 17 | 18 | ts = None 19 | if what in (1, 2, 3): 20 | ts = datetime.datetime(*result[:6]) 21 | ts = arrow.get(ts) 22 | ts = ts.replace(tzinfo=LOCAL_TIMEZONE) 23 | return ts 24 | 25 | if ts is None: 26 | raise ValueError("Cannot parse timestamp '{0}'".format(s)) 27 | 28 | return ts 29 | 30 | 31 | def datetime_converter(dt): 32 | if dt is None: 33 | return None 34 | elif isinstance(dt, six.string_types): 35 | return datetime_parser(dt) 36 | else: 37 | return arrow.get(dt) 38 | -------------------------------------------------------------------------------- /glogcli/formats.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | from termcolor import colored 3 | import syslog 4 | import six 5 | from glogcli import utils 6 | 7 | 8 | class Formatter(object): 9 | 10 | DEFAULT_FIELDS = [utils.TIMESTAMP, utils.LEVEL, utils.MESSAGE, utils.SOURCE, utils.FACILITY] 11 | 12 | def __init__(self, format_template, fields=None, color=True): 13 | self.format_template = format_template 14 | self.color = color 15 | self.fields = fields if fields else self.DEFAULT_FIELDS 16 | 17 | def format(self, entry): 18 | raise NotImplementedError() 19 | 20 | def encode_message(self, message): 21 | return message.encode('utf8') 22 | 23 | 24 | class TailFormatter(Formatter): 25 | 26 | def format(self, entry): 27 | message = entry.message 28 | timestamp = entry.timestamp.to("local") 29 | source = entry.message_dict.get("source", "") 30 | facility = entry.message_dict.get("facility", "") 31 | custom_fields = list(self.fields) 32 | 33 | log_level = LogLevel.find_by_syslog_code(entry.level) 34 | args = { 35 | 'timestamp': timestamp.format(utils.DEFAULT_DATE_FORMAT), 36 | 'level': log_level['name'], 37 | 'message': self.encode_message(message), 38 | 'source': source, 39 | 'facility': facility 40 | } 41 | 42 | for field in custom_fields: 43 | if field not in self.DEFAULT_FIELDS: 44 | args[field] = entry.message_dict.get(field, '') 45 | 46 | log = six.u(self.format_template).format(**args) 47 | 48 | if self.color: 49 | return colored(log, log_level['color'], log_level['bg_color']) 50 | else: 51 | return log 52 | 53 | 54 | class DumpFormatter(Formatter): 55 | 56 | def format(self, entry): 57 | formatted_fields = dict() 58 | for field in self.fields: 59 | if field == 'timestamp': 60 | field_value = entry.timestamp.to('local').format(utils.DEFAULT_DATE_FORMAT) 61 | elif field == 'level': 62 | field_value = LogLevel.find_by_syslog_code(entry.level).get('name') 63 | else: 64 | field_value = entry.message_dict.get(field, "") 65 | formatted_fields[field] = field_value 66 | return ";".join(map(lambda f: "'{val}'".format(val=formatted_fields.get(f)), self.fields)) 67 | 68 | 69 | class FormatterFactory(object): 70 | 71 | @staticmethod 72 | def get_formatter(mode, cfg, format_template, fields, color): 73 | format_template = FormatterFactory.get_message_format_template(cfg, format_template) 74 | if mode == "tail": 75 | return TailFormatter(format_template=format_template, fields=fields, color=color) 76 | elif mode == "dump": 77 | return DumpFormatter(format_template=format_template, fields=fields) 78 | 79 | @staticmethod 80 | def get_message_format_template(cfg, format_template_name): 81 | section_name = "format:" + format_template_name 82 | try: 83 | return cfg.get(section_name, utils.FORMAT) 84 | except: 85 | return utils.DEFAULT_MESSAGE_FORMAT_TEMPLATE 86 | 87 | 88 | class LogLevel(object): 89 | 90 | LEVELS = { 91 | syslog.LOG_CRIT: { 92 | 'name': 'CRITICAL', 93 | 'color': 'white', 94 | 'bg_color': 'on_red' 95 | }, 96 | syslog.LOG_ERR: { 97 | 'name': 'ERROR', 98 | 'color': 'red', 99 | 'bg_color': None 100 | }, 101 | syslog.LOG_WARNING: { 102 | 'name': 'WARNING', 103 | 'color': 'yellow', 104 | 'bg_color': None 105 | }, 106 | syslog.LOG_NOTICE: { 107 | 'name': 'NOTICE', 108 | 'color': 'green', 109 | 'bg_color': None 110 | }, 111 | syslog.LOG_INFO: { 112 | 'name': 'INFO', 113 | 'color': 'green', 114 | 'bg_color': None 115 | }, 116 | syslog.LOG_DEBUG: { 117 | 'name': 'DEBUG', 118 | 'color': 'cyan', 119 | 'bg_color': None 120 | }, 121 | } 122 | 123 | DEFAULT_CONFIG = { 124 | 'name': '', 125 | 'color': 'green', 126 | 'bg_color': None 127 | } 128 | 129 | @staticmethod 130 | def find_by_syslog_code(level): 131 | return LogLevel.LEVELS.get(level, LogLevel.DEFAULT_CONFIG) 132 | 133 | @staticmethod 134 | def find_by_level_name(level_name): 135 | for key, value in LogLevel.LEVELS.items(): 136 | if value['name'] == level_name: 137 | return key 138 | 139 | @staticmethod 140 | def list_levels(): 141 | return [l.get('name') for l in LogLevel.LEVELS.values()] 142 | -------------------------------------------------------------------------------- /glogcli/graylog_api.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import re 3 | import click 4 | import requests 5 | import arrow 6 | import syslog 7 | import six 8 | from glogcli import utils 9 | from glogcli.dateutils import datetime_converter 10 | from glogcli.utils import cli_error, store_password_in_keyring, get_password_from_keyring 11 | from glogcli.formats import LogLevel 12 | from glogcli.input import CliInterface 13 | 14 | 15 | class Message(object): 16 | 17 | def __init__(self, message_dict={}): 18 | self.message_dict = dict(message_dict[utils.MESSAGE]) 19 | self.timestamp = arrow.get(self.message_dict.get("timestamp", None)) 20 | self.level = self.message_dict.get("level", syslog.LOG_INFO) 21 | self.message = self.message_dict.get(utils.MESSAGE, "") 22 | 23 | 24 | class SearchResult(object): 25 | 26 | def __init__(self, result_dict={}): 27 | self.query = result_dict.get("query", None) 28 | self.query_object = None 29 | self.used_indices = result_dict.get("used_indices", None) 30 | self.queried_range = result_dict.get("queried_range", None) 31 | self.range_from = arrow.get(result_dict.get("from", None)) 32 | self.range_to = arrow.get(result_dict.get("to", None)) 33 | self.range_duration = result_dict.get("time", None) 34 | self.fields = result_dict.get("fields", []) 35 | self.total_results = result_dict.get("total_results", None) 36 | self.messages = list(map(Message, result_dict.get("messages", []))) 37 | 38 | 39 | class SearchRange(object): 40 | 41 | def __init__(self, from_time=None, to_time=None, relative=False): 42 | self.from_time = datetime_converter(from_time) 43 | self.to_time = datetime_converter(to_time) 44 | self.relative = relative 45 | 46 | def is_relative(self): 47 | return self.relative 48 | 49 | def range_in_seconds(self): 50 | if self.is_relative(): 51 | range = arrow.now('local').timestamp - self.from_time.timestamp 52 | else: 53 | range = (self.to_time - self.from_time).seconds 54 | 55 | if range < 1: 56 | return 1 57 | return range 58 | 59 | 60 | class SearchQuery(object): 61 | 62 | def __init__(self, search_range, query="*", limit=None, offset=None, filter=None, fields=None, sort=None, ascending=False): 63 | self.search_range = search_range 64 | self.query = SearchQuery.replace_log_level(query) 65 | self.limit = limit 66 | self.offset = offset 67 | self.filter = filter 68 | self.fields = fields 69 | self.sort = sort 70 | self.ascending = ascending 71 | 72 | @staticmethod 73 | def replace_log_level(query): 74 | log_level_regex = 'level\:\s*[a-zA-Z]+\s*' 75 | match = re.search(log_level_regex, query) 76 | if match: 77 | log_level_name = match.group(0).split(':')[1].strip().upper() 78 | log_level_code = LogLevel.find_by_level_name(log_level_name) 79 | if not log_level_code: 80 | message = "The given log level({}) is invalid. Use one of the following: {}" 81 | cli_error(message.format(log_level_name, LogLevel.list_levels())) 82 | exit() 83 | return re.sub(log_level_regex, 'level:%s ' % log_level_code, query) 84 | else: 85 | return query 86 | 87 | def copy_with_range(self, search_range): 88 | return SearchQuery(search_range, self.query, self.limit, self.offset, self.filter, self.fields, self.sort, self.ascending) 89 | 90 | 91 | class GraylogAPI(object): 92 | 93 | def __init__(self, host, port, username, api_path=utils.DEFAULT_API_PATH, password=None, host_tz='local', default_stream=None, scheme='http', proxies=None): 94 | self.host = host 95 | self.port = port 96 | if api_path.endswith("/") or len(api_path) == 0: 97 | self.api_path = api_path 98 | else: 99 | self.api_path = api_path + "/" 100 | self.username = username 101 | self.password = password 102 | self.user = None 103 | self.host_tz = host_tz 104 | self.default_stream = default_stream 105 | self.proxies = proxies 106 | self.get_header = {"Accept": "application/json"} 107 | self.base_url = "{scheme}://{host}:{port}/{api_path}".format(host=host, port=port, scheme=scheme, api_path=api_path) 108 | 109 | def update_host_timezone(self, timezone): 110 | if timezone: 111 | self.host_tz = timezone 112 | 113 | def get(self, url, **kwargs): 114 | params = {} 115 | 116 | for label, item in six.iteritems(kwargs): 117 | if isinstance(item, list): 118 | params[label + "[]"] = item 119 | else: 120 | params[label] = item 121 | 122 | r = requests.get(self.base_url + url, params=params, headers=self.get_header, auth=(self.username, self.password), proxies=self.proxies) 123 | if r.status_code == requests.codes.ok: 124 | return r.json() 125 | elif r.status_code == 401: 126 | click.echo("API error: {} Message: User authorization denied.".format(r.status_code)) 127 | exit() 128 | else: 129 | click.echo("API error: URL: {} Status: {} Message: {}".format(self.base_url + url, r.status_code, r.content)) 130 | exit() 131 | 132 | def search(self, query, fetch_all=False): 133 | sort = None 134 | if query.sort is not None: 135 | if query.ascending: 136 | sort = query.sort + ":asc" 137 | else: 138 | sort = query.sort + ":desc" 139 | 140 | if fetch_all and query.limit is None: 141 | result = self.search_raw( 142 | query.query, query.search_range, 1, query.offset, query.filter, query.fields, sort 143 | ) 144 | 145 | sr = SearchRange(from_time=result.range_from, to_time=result.range_to) 146 | 147 | if result.total_results > 10000: 148 | raise RuntimeError("Query returns more than 10000 log entries. Use offsets to query in chunks.") 149 | 150 | result = self.search_raw( 151 | query.query, sr, result.total_results, query.offset, query.filter, query.fields, sort 152 | ) 153 | 154 | else: 155 | result = self.search_raw( 156 | query.query, query.search_range, query.limit, query.offset, query.filter, query.fields, sort 157 | ) 158 | 159 | result.query_object = query 160 | return result 161 | 162 | def user_info(self): 163 | if not self.user: 164 | self.user = self.get(url=("users/" + self.username)) 165 | return self.user 166 | 167 | def streams(self): 168 | return self.get(url="streams/enabled") 169 | 170 | def get_saved_queries(self): 171 | return self.get(url="search/saved") 172 | 173 | def search_raw(self, query, search_range, limit=None, offset=None, filter=None, fields=None, sort=None): 174 | url = "search/universal/" 175 | range_args = {} 176 | 177 | if filter is None and self.default_stream is not None: 178 | filter = "streams:{}".format(self.default_stream) 179 | 180 | if search_range.is_relative(): 181 | url += "relative" 182 | range_args["range"] = search_range.range_in_seconds() 183 | else: 184 | url += "absolute" 185 | range_args["from"] = search_range.from_time.to(self.host_tz).format(utils.DEFAULT_DATE_FORMAT) 186 | to_time = arrow.now(self.host_tz) if search_range.to_time is None else search_range.to_time.to(self.host_tz) 187 | range_args["to"] = to_time.format(utils.DEFAULT_DATE_FORMAT) 188 | 189 | if fields is not None: 190 | fields = ",".join(fields) 191 | 192 | result = self.get( 193 | url=url, 194 | query=query, 195 | limit=limit, 196 | offset=offset, 197 | filter=filter, 198 | fields=fields, 199 | sort=sort, 200 | **range_args 201 | ) 202 | 203 | return SearchResult(result) 204 | 205 | 206 | class GraylogAPIFactory(object): 207 | 208 | @staticmethod 209 | def get_graylog_api(cfg, environment, host, password, port, proxy, no_tls, username, keyring): 210 | gl_api = None 211 | 212 | scheme = "https" 213 | 214 | if no_tls: 215 | scheme = "http" 216 | 217 | if scheme == "https" and port is None: 218 | port = 443 219 | port = port or 80 220 | 221 | proxies = {scheme: proxy} if proxy else None 222 | 223 | if environment is not None: 224 | gl_api = GraylogAPIFactory.api_from_config(cfg, environment, port, proxies, no_tls, username) 225 | else: 226 | if host is not None: 227 | if username is None: 228 | username = CliInterface.prompt_username(scheme, host, port) 229 | 230 | gl_api = GraylogAPIFactory.api_from_host( 231 | host=host, port=port, username=username, password=password, scheme=scheme, proxies=proxies, tls=no_tls 232 | ) 233 | else: 234 | if cfg.has_section("environment:default"): 235 | gl_api = GraylogAPIFactory.api_from_config(cfg, "default", port, proxies, no_tls, username) 236 | else: 237 | cli_error("Error: No host or environment configuration specified and no default found.") 238 | 239 | if not password and keyring: 240 | password = get_password_from_keyring(gl_api.host, gl_api.username) 241 | 242 | if not password: 243 | password = CliInterface.prompt_password(scheme, gl_api.host, gl_api.port, gl_api.username, gl_api.api_path) 244 | 245 | gl_api.password = password 246 | 247 | if keyring: 248 | store_password_in_keyring(gl_api.host, gl_api.username, password) 249 | 250 | gl_api.update_host_timezone(gl_api.user_info().get('timezone')) 251 | 252 | return gl_api 253 | 254 | @staticmethod 255 | def api_from_host(host, port, username, password, scheme, proxies=None, tls=True): 256 | scheme = "https" if tls else "http" 257 | return GraylogAPI(host=host, port=port, username=username, password=password, scheme=scheme, proxies=proxies) 258 | 259 | @staticmethod 260 | def api_from_config(cfg, env_name, port, proxies, no_tls, username): 261 | section_name = "environment:" + env_name 262 | 263 | host = None 264 | if cfg.has_option(section_name, utils.HOST): 265 | host = cfg.get(section_name, utils.HOST) 266 | else: 267 | cli_error("'host' option is not available in section [%(section_name)s]" % {'section_name': section_name}) 268 | 269 | if not port and cfg.has_option(section_name, utils.PORT): 270 | port = cfg.get(section_name, utils.PORT) 271 | 272 | if cfg.has_option(section_name, utils.API_PATH): 273 | api_path = cfg.get(section_name, utils.API_PATH) 274 | else: 275 | api_path = utils.DEFAULT_API_PATH 276 | 277 | scheme = "https" 278 | 279 | if no_tls: 280 | scheme = "http" 281 | 282 | if not username and cfg.has_option(section_name, utils.USERNAME): 283 | username = cfg.get(section_name, utils.USERNAME) 284 | elif not username: 285 | username = CliInterface.prompt_username(scheme, host, port) 286 | 287 | if not proxies and cfg.has_option(section_name, utils.PROXY): 288 | proxies = {scheme: cfg.get(section_name, utils.PROXY)} 289 | 290 | default_stream = None 291 | if cfg.has_option(section_name, utils.DEFAULT_STREAM): 292 | default_stream = cfg.get(section_name, utils.DEFAULT_STREAM) 293 | 294 | return GraylogAPI( 295 | host=host, port=port, api_path=api_path, username=username, default_stream=default_stream, scheme=scheme, proxies=proxies 296 | ) 297 | -------------------------------------------------------------------------------- /glogcli/input.py: -------------------------------------------------------------------------------- 1 | import getpass 2 | import click 3 | 4 | from glogcli.utils import cli_error 5 | from glogcli import utils 6 | 7 | 8 | class CliInterface(object): 9 | 10 | @staticmethod 11 | def select_stream(graylog_api, stream): 12 | is_admin = graylog_api.user["permissions"] == ["*"] or 'Admin' in graylog_api.user["roles"] 13 | stream = stream if stream is not None else graylog_api.default_stream 14 | 15 | if not stream: 16 | streams = graylog_api.streams()["streams"] 17 | click.echo("Please select a stream to query:") 18 | for i, st in enumerate(streams): 19 | stream_id = st["id"].encode(utils.UTF8) 20 | message = "{}: Stream '{}' (id: {})".format(i, st["title"].encode(utils.UTF8), stream_id) 21 | click.echo(message) 22 | 23 | if is_admin: 24 | message = "{}: Stream '{}'".format(len(streams), 'All Streams') 25 | click.echo(message) 26 | 27 | stream_index = click.prompt("Enter stream number:", type=int, default=0) 28 | 29 | if stream_index < len(streams): 30 | stream = streams[stream_index]["id"] 31 | elif stream_index >= len(streams) and not is_admin: 32 | CliInterface.select_stream(graylog_api, stream) 33 | 34 | if stream and stream != '*': 35 | return "streams:{}".format(stream) 36 | 37 | @staticmethod 38 | def select_saved_query(graylog_api): 39 | searches = graylog_api.get_saved_queries()["searches"] 40 | if not searches: 41 | cli_error("You have no saved queries to display.") 42 | 43 | for i, search in enumerate(searches): 44 | search_title = search["title"].encode(utils.UTF8) 45 | query = search["query"]["query"].encode(utils.UTF8) or "*" 46 | message = "{}: Query '{}' (query: {})".format(i, search_title, query) 47 | click.echo(message) 48 | search_index = click.prompt("Enter query number:", type=int, default=0) 49 | search = searches[search_index] 50 | query = search['query']['query'].encode(utils.UTF8) or '*'.encode(utils.UTF8) 51 | fields = search['query']['fields'].encode(utils.UTF8).split(','.encode(utils.UTF8)) 52 | 53 | return query, fields 54 | 55 | @staticmethod 56 | def prompt_password(scheme="", host=None, port=None, username=None, api_path=utils.DEFAULT_API_PATH): 57 | prompt_message = "Enter password for {username} at {scheme}://{host}:{port}/{api_path}".format( 58 | scheme=scheme, username=username, host=host, port=port, api_path=api_path 59 | ) 60 | return click.prompt(prompt_message, hide_input=True) 61 | 62 | @staticmethod 63 | def prompt_username(scheme="", host=None, port=None, api_path=utils.DEFAULT_API_PATH): 64 | return click.prompt("Enter username for {scheme}://{host}:{port}/{api_path}".format( 65 | scheme=scheme, host=host, port=port, api_path=api_path), default=getpass.getuser() 66 | ) 67 | -------------------------------------------------------------------------------- /glogcli/output.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import time 3 | import arrow 4 | from glogcli.graylog_api import SearchRange 5 | from glogcli.utils import LOCAL_TIMEZONE 6 | 7 | import sys 8 | 9 | reload(sys) 10 | sys.setdefaultencoding('utf8') 11 | 12 | 13 | class SimpleBuffer(object): 14 | 15 | def __init__(self): 16 | self.buffer = [] 17 | 18 | def insert(self, object): 19 | self.buffer.append(object) 20 | 21 | def _clean_buffer(self): 22 | self.buffer = [] 23 | 24 | def is_object_buffered(self, object): 25 | is_object_buffered = object in self.buffer 26 | if len(self.buffer) > 1000: 27 | self._clean_buffer() 28 | 29 | return is_object_buffered 30 | 31 | 32 | class LogPrinter(object): 33 | 34 | def __init__(self): 35 | self.message_buffer = SimpleBuffer() 36 | 37 | def run_logprint(self, api, query, formatter, follow=False, output=None, header=None, interval=1000): 38 | if follow: 39 | assert query.limit is None 40 | 41 | close_output = False 42 | if output is not None and isinstance(output, basestring): 43 | output = open(output, "a") 44 | close_output = True 45 | 46 | try: 47 | while True: 48 | self.run_logprint(api, query, formatter, follow=False, output=output) 49 | new_range = SearchRange(to_time=arrow.now(LOCAL_TIMEZONE), from_time=arrow.now(LOCAL_TIMEZONE).replace(seconds=-5)) 50 | query = query.copy_with_range(new_range) 51 | time.sleep(interval / 1000.0) 52 | except KeyboardInterrupt: 53 | print("\nInterrupted follow mode. Exiting...") 54 | 55 | if close_output: 56 | output.close() 57 | 58 | else: 59 | result = api.search(query, fetch_all=True) 60 | formatted_msgs = [] 61 | for message in result.messages: 62 | message_id = message.message_dict.get('_id') 63 | if not self.message_buffer.is_object_buffered(message_id): 64 | formatted_msgs.append(formatter.format(message)) 65 | self.message_buffer.insert(message_id) 66 | 67 | formatted_msgs.reverse() 68 | 69 | if formatted_msgs: 70 | if output is None: 71 | for msg in formatted_msgs: 72 | print(msg.encode('utf-8').strip()) 73 | else: 74 | if isinstance(output, basestring): 75 | with open(output, "a") as f: 76 | f.writelines(('\n'.join(formatted_msgs) + '\n').encode('utf-8').strip()) 77 | else: 78 | output.writelines(('\n'.join(formatted_msgs) + '\n').encode('utf-8').strip()) 79 | return result 80 | -------------------------------------------------------------------------------- /glogcli/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | 3 | try: 4 | import configparser 5 | except: 6 | from six.moves import configparser 7 | 8 | import re 9 | import os 10 | import sys 11 | import click 12 | import keyring 13 | 14 | 15 | DEFAULT_DATE_FORMAT = "YYYY-MM-DD HH:mm:ss.SSS" 16 | MESSAGE = "message" 17 | FACILITY = "facility" 18 | SOURCE = "source" 19 | LEVEL = "level" 20 | TIMESTAMP = "timestamp" 21 | MODULE = "module" 22 | LINE = "line" 23 | LOCAL_TIMEZONE = "local" 24 | UTF8 = "utf-8" 25 | USERNAME = "username" 26 | PASSWORD = "password" 27 | PORT = "port" 28 | TLS = "tls" 29 | HOST = "host" 30 | API_PATH = "api_path" 31 | DEFAULT_API_PATH = "api/" 32 | FORMAT = "format" 33 | COLOR = "color" 34 | PROXY = "proxy" 35 | DEFAULT_STREAM = "default_stream" 36 | DEFAULT_MESSAGE_FORMAT_TEMPLATE = "{source} {level} {timestamp} {facility} {message}" 37 | 38 | 39 | def get_glogcli_version(): 40 | return "0.8.1" 41 | 42 | 43 | def get_config(config_file_path="~/.glogcli.cfg"): 44 | config = configparser.ConfigParser() 45 | try: 46 | open(os.path.expanduser(config_file_path)) 47 | except Exception: 48 | click.echo("[WARNING] - Could not find %s file. Please create the configuration file like:" % config_file_path) 49 | click.echo("\n[environment:default]\n" 50 | "host=mygraylogserver.com\n" 51 | "port=443\n" 52 | "username=john.doe\n" 53 | "default_stream=*\n" 54 | "\n" 55 | "[environment:dev]\n" 56 | "host=mygraylogserver.dev.com\n" 57 | "port=443\n" 58 | "proxy=mycompanyproxy.com\n" 59 | "username=john.doe\n" 60 | "default_stream=57e14cde6fb78216a60d35e8\n" 61 | "\n" 62 | "[format:default]\n" 63 | "format={host} {level} {facility} {timestamp} {message}\n" 64 | "\n" 65 | "[format:short]\n" 66 | "format=[{timestamp}] {level} {message}\n" 67 | "\n" 68 | "[format:long]\n" 69 | "format=time: [{timestamp}] level: {level} msg: {message} tags: {tags}\n" 70 | "color=false\n" 71 | "\n") 72 | 73 | config.read(os.path.expanduser(config_file_path)) 74 | return config 75 | 76 | 77 | def cli_error(msg): 78 | click.echo(click.style(msg, fg='red')) 79 | sys.exit(1) 80 | 81 | 82 | def _get_host(cfg, section_name): 83 | return cfg.has_option(section_name, "host") 84 | 85 | 86 | def store_password_in_keyring(host, username, password): 87 | keyring.set_password('glog_' + host, username, password) 88 | 89 | 90 | def get_password_from_keyring(host, username): 91 | return keyring.get_password('glog_' + host, username) 92 | 93 | 94 | def extract_fields_from_format(cfg, format_name): 95 | if cfg.has_option("format:" + format_name, FORMAT): 96 | fields = re.findall('\{.*?\}', cfg.get("format:" + format_name, FORMAT)) 97 | return [f[1:-1] for f in fields] 98 | 99 | 100 | def get_color_option(cfg, format_name, no_color): 101 | if no_color: 102 | return False 103 | if cfg.has_option("format:" + format_name, COLOR): 104 | return cfg.get("format:" + format_name, COLOR) == 'true' 105 | else: 106 | return True 107 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bumpversion==0.5.3 2 | wheel==0.29.0 3 | watchdog==0.8.3 4 | flake8==2.6.0 5 | tox==2.3.1 6 | coverage==4.1 7 | Sphinx==1.4.4 8 | click>=3.3,<7 9 | keyring==8.7 10 | parsedatetime>=1.4,<3 11 | python-dateutil>=2.4.1,<3 12 | requests>=2.4.3,<3.0 13 | arrow>=0.5.4,<0.8 14 | termcolor==1.1.0 15 | six>=1.9.0 16 | pytest==2.9.2 17 | mock==1.3.0 18 | httpretty==0.8.14 19 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.8.3 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version='{current_version}' 8 | replace = version='{new_version}' 9 | 10 | [bumpversion:file:glogcli/__init__.py] 11 | search = __version__ = '{current_version}' 12 | replace = __version__ = '{new_version}' 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [metadata] 18 | description-file = README.md 19 | 20 | [flake8] 21 | exclude = docs 22 | ignore = E501 23 | 24 | [aliases] 25 | test=pytest 26 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from setuptools import setup 5 | 6 | 7 | with open('README.rst') as readme_file: 8 | readme = readme_file.read() 9 | 10 | with open('HISTORY.rst') as history_file: 11 | history = history_file.read() 12 | 13 | install_requires = [ 14 | 'click>=3.3,<7', 15 | 'keyring==8.7', 16 | 'parsedatetime>=1.4,<3', 17 | 'python-dateutil>=2.4.1,<3', 18 | 'requests>=2.4.3,<3.0', 19 | 'arrow>=0.5.4,<0.8', 20 | 'termcolor==1.1.0', 21 | 'six>=1.9.0', 22 | ] 23 | 24 | tests_require = [ 25 | 'coverage==4.1', 26 | 'httpretty==0.8.14', 27 | 'mock==1.3.0', 28 | 'pytest==2.9.2', 29 | ] 30 | 31 | setup_requires = [ 32 | 'bumpversion==0.5.3', 33 | 'flake8==2.6.0', 34 | 'pytest-runner', 35 | 'wheel==0.29.0', 36 | ] 37 | 38 | setup( 39 | name='glogcli', 40 | version='0.8.3', 41 | description="Graylog command line interface.", 42 | long_description=readme + '\n\n' + history, 43 | author="Sinval Vieira", 44 | author_email='sinvalneto01@gmail.com', 45 | url='https://github.com/globocom/glog-cli', 46 | download_url='https://github.com/globocom/glog-cli/tarball/0.8.3', 47 | packages=[ 48 | 'glogcli', 49 | ], 50 | package_dir={'glogcli': 51 | 'glogcli'}, 52 | entry_points={ 53 | 'console_scripts': [ 54 | 'glogcli=glogcli.cli:run' 55 | ] 56 | }, 57 | include_package_data=True, 58 | install_requires=install_requires, 59 | setup_requires=setup_requires, 60 | license="Apache Software License 2.0", 61 | zip_safe=False, 62 | keywords='glogcli', 63 | classifiers=[ 64 | 'Development Status :: 2 - Pre-Alpha', 65 | 'Intended Audience :: Developers', 66 | 'License :: OSI Approved :: Apache Software License', 67 | 'Natural Language :: English', 68 | "Programming Language :: Python :: 2", 69 | 'Programming Language :: Python :: 2.6', 70 | 'Programming Language :: Python :: 2.7', 71 | ], 72 | test_suite='tests', 73 | tests_require=tests_require 74 | ) 75 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /tests/test_api.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import unittest 3 | import arrow 4 | import httpretty 5 | import glogcli.graylog_api as api 6 | 7 | 8 | class GraylogAPITestCase(unittest.TestCase): 9 | 10 | def setUp(self): 11 | self.api = api.GraylogAPI("dummyhost", 80, "dummy", password="dummy") 12 | 13 | def test_search_range(self): 14 | sr = api.SearchRange("10 minutes ago", arrow.now()) 15 | self.assertEquals(600, sr.range_in_seconds()) 16 | 17 | sr = api.SearchRange("10 minutes ago", relative=True) 18 | self.assertEquals(600, sr.range_in_seconds()) 19 | 20 | sr = api.SearchRange("10 minutes ago") 21 | with self.assertRaises(Exception): 22 | sr.range_in_seconds() 23 | 24 | sr = api.SearchRange("10 minutes ago", "10 minutes ago") 25 | self.assertEquals(1, sr.range_in_seconds()) 26 | 27 | @httpretty.activate 28 | def test_graylog_api_search(self): 29 | httpretty.register_uri( 30 | httpretty.GET, "http://dummyhost:80/api/search/universal/absolute", 31 | body=self.generate_search_result(), 32 | content_type="application/json" 33 | ) 34 | 35 | # More of some dummy tests now 36 | sr = api.SearchRange("10 minutes ago", arrow.now()) 37 | q = api.SearchQuery(sr) 38 | result = self.api.search(q) 39 | self.assertEquals(len(result.messages), 1) 40 | self.assertEquals("*", result.query) 41 | 42 | q = api.SearchQuery(sr, fields=["level", "module", "message", "timestamp"], sort="level", ascending=True) 43 | qq = q.copy_with_range(sr) 44 | result = self.api.search(qq) 45 | self.assertEquals(len(result.messages), 1) 46 | self.assertEquals("*", result.query, ) 47 | 48 | q = api.SearchQuery(sr, fields=["level", "module", "message", "timestamp"], sort="level", ascending=False) 49 | result = self.api.search(q) 50 | self.assertEquals(len(result.messages), 1) 51 | self.assertEquals("*", result.query) 52 | 53 | result = self.api.search(q, fetch_all=True) 54 | self.assertEquals(len(result.messages), 1) 55 | self.assertEquals("*", result.query) 56 | 57 | @httpretty.activate 58 | def test_to_many_results(self): 59 | httpretty.register_uri( 60 | httpretty.GET, "http://dummyhost:80/api/search/universal/absolute", 61 | body=self.generate_search_result(1000000), 62 | content_type="application/json" 63 | ) 64 | 65 | sr = api.SearchRange("10 minutes ago", arrow.now()) 66 | q = api.SearchQuery(sr) 67 | 68 | with self.assertRaises(RuntimeError): 69 | self.api.search(q, fetch_all=True) 70 | 71 | @httpretty.activate 72 | def test_userinfo(self): 73 | httpretty.register_uri( 74 | httpretty.GET, "http://dummyhost:80/api/users/dummy", 75 | body='{"someuser" : "info" }', 76 | content_type="application/json" 77 | ) 78 | 79 | result = self.api.user_info() 80 | self.assertEquals({"someuser": "info"}, result) 81 | 82 | @httpretty.activate 83 | def test_streams(self): 84 | httpretty.register_uri( 85 | httpretty.GET, "http://dummyhost:80/api/streams/enabled", 86 | body='[{"somestream" : "a" }]', 87 | content_type="application/json" 88 | ) 89 | 90 | result = self.api.streams() 91 | self.assertEquals([{"somestream": "a"}], result) 92 | 93 | @httpretty.activate 94 | def test_saved_searches(self): 95 | httpretty.register_uri( 96 | httpretty.GET, "http://dummyhost:80/api/search/saved", 97 | body='{"searches" : [{"query": {"query": "level:INFO", "fields":"timestamp,message"}}]}', 98 | content_type="application/json" 99 | ) 100 | 101 | saved_searches = self.api.get_saved_queries() 102 | self.assertEquals("level:INFO", saved_searches['searches'][0]['query']['query']) 103 | self.assertEquals("timestamp,message", saved_searches['searches'][0]['query']['fields']) 104 | 105 | def generate_search_result(self, total_results=1000): 106 | result = """{{ 107 | "query": "*", 108 | "built_query": "{{\\"from\\":0,\\"size\\":150,\\"query\\":{{\\"match_all\\":{{}},\\"post_filter\\":{{\\"range\\":{{\\"timestamp\\":{{\\"from\\":\\"2015-04-20 10:33:01.000\\",\\"to\\":\\"2015-04-20 10:43:01.795\\",\\"include_lower\\":true,\\"include_upper\\":true}}}},\\"sort\\":[{{\\"timestamp\\":{{\\"order\\":\\"desc\\"}}]}}", 109 | "used_indices": [ 110 | {{ 111 | "index": "graylog2_20", 112 | "calculation_took_ms": 3, 113 | "calculated_at": "2015-04-18T20:00:10.000Z", 114 | "starts": "2015-04-18T20:00:10.000Z" 115 | }} 116 | ], 117 | "messages": [ 118 | {{ 119 | "message": {{ 120 | "level": 7, 121 | "module": "Database", 122 | "streams": [ 123 | "1111111" 124 | ], 125 | "source": "host1", 126 | "message": "Some message", 127 | "gl2_source_input": "1111111", 128 | "version": "1.1", 129 | "full_message": "Some extended message", 130 | "gl2_source_node": "c03b2ce1-8246-408b-9ca6-32309640d252", 131 | "_id": "0bc08503-e74a-11e4-a01b-52540021a4c5", 132 | "timestamp": "2015-04-20T10:43:01.793Z" 133 | }}, 134 | "index": "graylog2_20" 135 | }} 136 | ], 137 | "fields": [ 138 | "line", 139 | "source", 140 | "file", 141 | "text", 142 | "tag", 143 | "level", 144 | "module", 145 | "message", 146 | "version", 147 | "name", 148 | "facility" 149 | ], 150 | "time": 1, 151 | "total_results": {total_results}, 152 | "from": "2015-04-20T10:33:01.000Z", 153 | "to": "2015-04-20T10:43:01.795Z" 154 | }} 155 | """ 156 | return result.format(total_results=total_results) 157 | 158 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from mock import Mock, MagicMock 3 | from glogcli.utils import extract_fields_from_format, get_color_option 4 | 5 | 6 | class UtilsTestCase(unittest.TestCase): 7 | 8 | def test_get_color_with_color_option_enabled(self): 9 | self.assertTrue(get_color_option(self.mock_config('true', True), 'format_name', no_color=False)) 10 | self.assertTrue(get_color_option(self.mock_config('', False), 'format_name', no_color=False)) 11 | 12 | def test_get_color_with_no_color_option_disabled(self): 13 | self.assertFalse(get_color_option(self.mock_config('true', True), 'format_name', no_color=True)) 14 | self.assertFalse(get_color_option(self.mock_config('false', True), 'format_name', no_color=False)) 15 | self.assertFalse(get_color_option(self.mock_config('false', True), 'format_name', no_color=True)) 16 | self.assertFalse(get_color_option(self.mock_config('False', True), 'format_name', no_color=True)) 17 | self.assertFalse(get_color_option(self.mock_config('NO', True), 'format_name', no_color=True)) 18 | 19 | def mock_config(self, get_return=None, has_option_return=None): 20 | mock = MagicMock() 21 | mock.get = Mock(return_value=get_return) 22 | mock.has_option = Mock(return_value=has_option_return) 23 | return mock 24 | -------------------------------------------------------------------------------- /tests/test_date_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import arrow 3 | from glogcli.dateutils import datetime_parser, datetime_converter 4 | 5 | 6 | class DateUtilsTestCase(unittest.TestCase): 7 | 8 | def test_datetime_parser(self): 9 | now = arrow.now() 10 | ts_tuples = [ 11 | ("10 minutes ago", lambda x: x.replace(minutes=-10, microsecond=0, tzinfo='local')), 12 | ("1 day ago", lambda x: x.replace(days=-1, microsecond=0, tzinfo='local')), 13 | ("yesterday midnight", 14 | lambda x: x.replace(days=-1, hour=0, minute=0, second=0, microsecond=0, tzinfo='local')), 15 | ("1986-04-24 00:51:24+02:00", lambda x: arrow.get("1986-04-24 00:51:24+02:00")), 16 | ("2001-01-01 01:01:01", lambda x: arrow.get("2001-01-01 01:01:01").replace(tzinfo="local")), 17 | (now, lambda x: now)] 18 | 19 | for (s, ts) in ts_tuples: 20 | self.assertEquals(datetime_parser(s), ts(arrow.now())) 21 | 22 | with self.assertRaises(ValueError): 23 | datetime_parser("fdjkldfhskl") 24 | 25 | def test_datetime_converter(self): 26 | now = arrow.now() 27 | self.assertIsNone(datetime_converter(None)) 28 | self.assertEquals(datetime_converter(now), now) 29 | self.assertEquals(datetime_converter("1 day ago") , arrow.now().replace(days=-1, microsecond=0, tzinfo='local')) -------------------------------------------------------------------------------- /tests/test_formats.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import arrow 3 | import syslog 4 | from glogcli import utils 5 | from termcolor import colored 6 | from glogcli.formats import TailFormatter, DumpFormatter, LogLevel 7 | from glogcli.graylog_api import Message 8 | 9 | 10 | class FormatterTestCase(unittest.TestCase): 11 | 12 | def setUp(self): 13 | self.timestamp = arrow.utcnow() 14 | self.message = Message({ 15 | 'index': 'graylog', 16 | 'message': { 17 | 'a': 1, 18 | 'b': 2, 19 | 'c': 3, 20 | 'level': 7, 21 | 'message': 'dummy message', 22 | 'source': 'dummy.source', 23 | 'timestamp': self.timestamp 24 | } 25 | }) 26 | 27 | 28 | class TailFormatterTestCase(FormatterTestCase): 29 | 30 | def test_format(self): 31 | log = TailFormatter('({source}) - {message}', color=False).format(self.message) 32 | self.assertEquals('(dummy.source) - dummy message', log) 33 | 34 | def test_format_colored_with_level_debug(self): 35 | self.message.level = syslog.LOG_DEBUG 36 | log = TailFormatter('({source}) - {message}', color=True).format(self.message) 37 | self.assertEquals(colored('(dummy.source) - dummy message', 'cyan'), log) 38 | 39 | def test_format_colored_with_level_error(self): 40 | self.message.level = syslog.LOG_ERR 41 | log = TailFormatter('({source}) - {message}', color=True).format(self.message) 42 | self.assertEquals(colored('(dummy.source) - dummy message', 'red'), log) 43 | 44 | def test_format_colored_with_level_info(self): 45 | self.message.level = syslog.LOG_INFO 46 | log = TailFormatter('({source}) - {message}', color=True).format(self.message) 47 | self.assertEquals(colored('(dummy.source) - dummy message', 'green'), log) 48 | 49 | def test_format_colored_with_level_warning(self): 50 | self.message.level = syslog.LOG_WARNING 51 | log = TailFormatter('({source}) - {message}', color=True).format(self.message) 52 | self.assertEquals(colored('(dummy.source) - dummy message', 'yellow'), log) 53 | 54 | def test_format_colored_with_level_critical(self): 55 | self.message.level = syslog.LOG_CRIT 56 | log = TailFormatter('({source}) - {message}', color=True).format(self.message) 57 | self.assertEquals(colored('(dummy.source) - dummy message', 'white', 'on_red'), log) 58 | 59 | def test_format_with_log_level(self): 60 | log = TailFormatter('({level}) - {message}', color=False).format(self.message) 61 | self.assertEquals('(DEBUG) - dummy message', log) 62 | 63 | def test_format_with_timestamp(self): 64 | log = TailFormatter('({timestamp}) - {message}', color=False).format(self.message) 65 | timestamp_local_format = self.timestamp.to('local').format(utils.DEFAULT_DATE_FORMAT) 66 | self.assertEquals('({}) - dummy message'.format(timestamp_local_format), log) 67 | 68 | def test_format_with_custom_fields(self): 69 | log = TailFormatter('{a} {b} {c}', fields=['a', 'b', 'c'], color=False).format(self.message) 70 | self.assertEquals('1 2 3', log) 71 | 72 | def test_format_with_blank_fields(self): 73 | log = TailFormatter('{blank_field}', fields=['blank_field'], color=False).format(self.message) 74 | self.assertEquals('', log) 75 | 76 | 77 | class DumpFormatterTestCase(FormatterTestCase): 78 | 79 | def test_format(self): 80 | log = DumpFormatter(None, fields=['level', 'message']).format(self.message) 81 | self.assertEquals("'DEBUG';'dummy message'", log) 82 | 83 | def test_format_with_custom_fields(self): 84 | log = DumpFormatter(None, fields=['a', 'b']).format(self.message) 85 | self.assertEquals("'1';'2'", log) 86 | 87 | def test_format_with_blank_field(self): 88 | log = DumpFormatter(None, fields=['level', 'blank_fields']).format(self.message) 89 | self.assertEquals("'DEBUG';''", log) 90 | 91 | 92 | class LogLevelTestCase(unittest.TestCase): 93 | 94 | def test_get_log_level_from_code(self): 95 | self.assertEquals('CRITICAL', LogLevel.find_by_syslog_code(syslog.LOG_CRIT)['name']) 96 | self.assertEquals('WARNING', LogLevel.find_by_syslog_code(syslog.LOG_WARNING)['name']) 97 | self.assertEquals('DEBUG', LogLevel.find_by_syslog_code(syslog.LOG_DEBUG)['name']) 98 | self.assertEquals('INFO', LogLevel.find_by_syslog_code(syslog.LOG_INFO)['name']) 99 | self.assertEquals('ERROR', LogLevel.find_by_syslog_code(syslog.LOG_ERR)['name']) 100 | self.assertEquals('NOTICE', LogLevel.find_by_syslog_code(syslog.LOG_NOTICE)['name']) 101 | self.assertEquals('', LogLevel.find_by_syslog_code(9999)['name']) 102 | 103 | def test_get_log_level_code(self): 104 | self.assertEquals(syslog.LOG_CRIT, LogLevel.find_by_level_name('CRITICAL')) 105 | self.assertEquals(syslog.LOG_WARNING, LogLevel.find_by_level_name('WARNING')) 106 | self.assertEquals(syslog.LOG_DEBUG, LogLevel.find_by_level_name('DEBUG')) 107 | self.assertEquals(syslog.LOG_INFO, LogLevel.find_by_level_name('INFO')) 108 | self.assertEquals(syslog.LOG_ERR, LogLevel.find_by_level_name('ERROR')) 109 | self.assertEquals(syslog.LOG_NOTICE, LogLevel.find_by_level_name('NOTICE')) 110 | self.assertIsNone(LogLevel.find_by_level_name('UNKNOWN')) 111 | 112 | def test_list_levels(self): 113 | self.assertEquals(['CRITICAL', 'ERROR', 'WARNING', 'NOTICE', 'INFO', 'DEBUG'], LogLevel.list_levels()) 114 | -------------------------------------------------------------------------------- /tests/test_input.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from mock import MagicMock, Mock, patch 4 | 5 | from glogcli import utils 6 | from glogcli.input import CliInterface 7 | 8 | 9 | class CliInterfaceTestCase(unittest.TestCase): 10 | 11 | def setUp(self): 12 | self.admin_user = {'permissions': ['*'], 'roles': ['Admin']} 13 | self.regular_user = {'permissions': ['dashboard'], 'roles': ['some_role']} 14 | self.streams = {'streams': [ 15 | {'title': 'Main stream', 'id': '123'}, 16 | {'title': 'Other stream', 'id': '456'} 17 | ]} 18 | self.saved_queries = {'searches': [ 19 | {'query': {'query': '*', 'fields': 'timestamp,level,message'}, 'title': 'All'}, 20 | {'query': {'query': 'level:DEBUG', 'fields': 'timestamp,message'}, 'title': 'Debug'} 21 | ]} 22 | 23 | def test_select_stream_given_stream_passed(self): 24 | graylog_api = self._mock_graylog_api_streams(user=self.admin_user) 25 | stream_filter = CliInterface.select_stream(graylog_api, '123456') 26 | self.assertEquals('streams:123456', stream_filter) 27 | 28 | def test_select_stream_with_default_stream_set(self): 29 | graylog_api = self._mock_graylog_api_streams(user=self.admin_user, default_stream='abc') 30 | stream_filter = CliInterface.select_stream(graylog_api, None) 31 | self.assertEquals('streams:abc', stream_filter) 32 | 33 | def test_select_stream_with_no_stream_set_and_admin_user(self): 34 | graylog_api = self._mock_graylog_api_streams(user=self.admin_user) 35 | stream_filter = CliInterface.select_stream(graylog_api, '*') 36 | self.assertEquals(None, stream_filter) 37 | 38 | def test_select_stream_with_regular_user(self): 39 | graylog_api = self._mock_graylog_api_streams(stream_list=self.streams, user=self.regular_user) 40 | self._mock_prompt_stream(1) 41 | stream_filter = CliInterface.select_stream(graylog_api, None) 42 | self.assertEquals('streams:456', stream_filter) 43 | 44 | def test_select_stream_with_admin_user_and_all_streams_options_chosen(self): 45 | graylog_api = self._mock_graylog_api_streams(stream_list=self.streams, user=self.admin_user) 46 | self._mock_prompt_stream(2) 47 | stream_filter = CliInterface.select_stream(graylog_api, None) 48 | self.assertEquals(None, stream_filter) 49 | 50 | def test_select_saved_query(self): 51 | graylog_api = self._mock_graylog_api_saved_query(self.saved_queries) 52 | self._mock_prompt_stream(0) 53 | query, fields = CliInterface.select_saved_query(graylog_api) 54 | self.assertEquals('*'.encode(utils.UTF8), query) 55 | self.assertEquals([ 56 | 'timestamp'.encode(utils.UTF8), 57 | 'level'.encode(utils.UTF8), 58 | 'message'.encode(utils.UTF8) 59 | ], fields) 60 | 61 | self._mock_prompt_stream(1) 62 | query, fields = CliInterface.select_saved_query(graylog_api) 63 | self.assertEquals('level:DEBUG'.encode(utils.UTF8), query) 64 | self.assertEquals([ 65 | 'timestamp'.encode(utils.UTF8), 66 | 'message'.encode(utils.UTF8) 67 | ], fields) 68 | 69 | def test_select_saved_query_no_queries_found_for_user(self): 70 | graylog_api = self._mock_graylog_api_saved_query({'searches': []}) 71 | self._mock_prompt_stream(0) 72 | with self.assertRaises(SystemExit): 73 | CliInterface.select_saved_query(graylog_api) 74 | 75 | def _mock_graylog_api_streams(self, stream_list=None, default_stream=None, user=None): 76 | mock = MagicMock() 77 | mock.default_stream = default_stream 78 | mock.user = user 79 | mock.streams = Mock(return_value=stream_list) 80 | return mock 81 | 82 | def _mock_graylog_api_saved_query(self, saved_queries): 83 | mock = MagicMock() 84 | mock.get_saved_queries = Mock(return_value=saved_queries) 85 | return mock 86 | 87 | def _mock_prompt_stream(self, prompt_return): 88 | mock = patch('click.prompt').start() 89 | mock.return_value = prompt_return 90 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py33, py34, py35, py36, flake8 3 | 4 | [testenv:flake8] 5 | commands=python setup.py flake8 6 | 7 | [testenv] 8 | commands = 9 | pip install -e . 10 | python setup.py test 11 | --------------------------------------------------------------------------------