├── .circleci └── config.yml ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── dependabot.yml ├── .gitignore ├── .goreleaser.yml ├── Dockerfile ├── Dockerfile.release ├── Gopkg.lock ├── Gopkg.toml ├── LICENSE ├── README.md ├── _config.yml ├── cloudwatch ├── client.go ├── cloudwatchlogs_test.go ├── eventTTLCache.go ├── eventTTLCache_test.go ├── lsgroups.go ├── lsstreams.go └── tail.go ├── coordinator.go ├── cw.bash ├── cw.zsh ├── go.mod ├── go.sum ├── images ├── cw-logo.png └── cw-logo1280x640.png ├── main.go ├── main_test.go ├── snap └── snapcraft.yaml └── versioncheck.go /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | docker: 5 | - image: cimg/go:1.20.3 6 | working_directory: ~/github.com/lucagrulla/cw 7 | steps: 8 | - checkout 9 | - run: go test ./... -parallel=2 10 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: lucagrulla 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Which command 16 | 2. Which flags/arguments are used 17 | 18 | **Expected behavior** 19 | A clear and concise description of what you expected to happen. 20 | 21 | **Screenshots** 22 | If applicable, add screenshots to help explain your problem. 23 | 24 | **Desktop (please complete the following information):** 25 | - OS: [e.g. MacOS 10.14.2] 26 | - Terminal (bash, zsh) 27 | - cw version (`cw --version`) 28 | 29 | **Additional context** 30 | Add any other context about the problem here. 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gomod 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 10 8 | ignore: 9 | - dependency-name: github.com/aws/aws-sdk-go-v2 10 | versions: 11 | - 1.3.0 12 | - 1.3.1 13 | - 1.3.2 14 | - 1.3.3 15 | - dependency-name: github.com/aws/aws-sdk-go-v2/config 16 | versions: 17 | - 1.1.1 18 | - 1.1.3 19 | - 1.1.4 20 | - 1.1.5 21 | - dependency-name: github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs 22 | versions: 23 | - 1.2.0 24 | - 1.2.1 25 | - dependency-name: github.com/aws/aws-sdk-go 26 | versions: 27 | - 1.37.10 28 | - 1.37.15 29 | - 1.37.20 30 | - 1.37.24 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | cw 2 | /dist 3 | .vscode/ -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | builds: 2 | - 3 | env: 4 | - CGO_ENABLED=0 5 | goos: 6 | - windows 7 | - darwin 8 | - linux 9 | goarch: 10 | - 386 11 | - amd64 12 | - arm 13 | - arm64 14 | archives: 15 | - 16 | rlcp: true 17 | replacements: 18 | darwin: Darwin 19 | linux: Linux 20 | windows: Windows 21 | 386: i386 22 | amd64: x86_64 23 | files: 24 | - cw.bash 25 | - cw.zsh 26 | - LICENSE 27 | - README.md 28 | checksum: 29 | name_template: 'checksums.txt' 30 | snapshot: 31 | name_template: "{{ .Tag }}-next" 32 | changelog: 33 | sort: asc 34 | filters: 35 | exclude: 36 | - '^docs:' 37 | - '^test:' 38 | brews: 39 | - 40 | name: cw 41 | tap: 42 | owner: lucagrulla 43 | name: homebrew-tap 44 | commit_author: 45 | name: lucagrulla 46 | email: luca@lucagrulla.com 47 | folder: Formula 48 | homepage: "https://www.lucagrulla.com/cw" 49 | description: "The best way to tail AWS Cloudwatch Logs from your terminal" 50 | caveats: "In order to get cw completion, 51 | [bash] you need to install `bash-completion` with brew. 52 | OR 53 | [zsh], add the following line to your ~/.zshrc: 54 | source #{HOMEBREW_PREFIX}/share/zsh/site-functions/cw.zsh" 55 | install: | 56 | bin.install "cw" 57 | 58 | bash_completion.install "cw.bash" 59 | zsh_completion.install "cw.zsh" 60 | scoop: 61 | bucket: 62 | owner: lucagrulla 63 | name: cw-scoop-bucket 64 | homepage: "https://www.lucagrulla.com/cw" 65 | commit_author: 66 | name: lucagrulla 67 | email: luca@lucagrulla.com 68 | description: "The best way to tail AWS Cloudwatch Logs from your terminal" 69 | license: Apache-2.0 70 | persist: 71 | - "data" 72 | - "config.toml" 73 | nfpms: 74 | - 75 | id: cw 76 | file_name_template: '{{ .ProjectName }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' 77 | homepage: https://www.lucagrulla.com/cw 78 | description: The best way to tail AWS Cloudwatch Logs from your terminal 79 | maintainer: Luca Grulla luca.grulla+cw@gmail.com 80 | license: Apache2 81 | vendor: cw 82 | formats: 83 | - rpm 84 | # dependencies: 85 | # - git 86 | recommends: 87 | - rpm 88 | - 89 | id: cw-tail 90 | package_name: cw-tail # Use the package name "cw-tail" to avoid conflicts with https://launchpad.net/ubuntu/bionic/amd64/cw 91 | replaces: 92 | - cw (<< 3.3.0) 93 | file_name_template: '{{ .ProjectName }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' 94 | homepage: https://www.lucagrulla.com/cw 95 | description: The best way to tail AWS Cloudwatch Logs from your terminal 96 | maintainer: Luca Grulla luca.grulla+cw@gmail.com 97 | license: Apache2 98 | vendor: cw 99 | formats: 100 | - deb 101 | # dependencies: 102 | # - git 103 | 104 | snapcrafts: 105 | - 106 | name: cw-sh 107 | name_template: '{{ .ProjectName }}-sh_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' 108 | summary: The best way to tail AWS Cloudwatch Logs from your terminal 109 | description: | 110 | The best way to tail AWS Cloudwatch Logs from your terminal 111 | grade: stable 112 | base: core18 113 | confinement: strict 114 | apps: 115 | cw: 116 | plugs: [network, dot-aws-config-credentials] 117 | plugs: 118 | network: 119 | dot-aws-config-credentials: 120 | interface: personal-files 121 | read: 122 | - $HOME/.aws/config 123 | - $HOME/.aws/credentials 124 | publish: true 125 | 126 | dockers: 127 | - image_templates: ["lucagrulla/{{ .ProjectName }}:{{ .Version }}-i386"] 128 | goarch: 386 129 | dockerfile: Dockerfile.release 130 | build_flag_templates: 131 | - --platform=linux/386 132 | - --label=org.opencontainers.image.title={{ .ProjectName }} 133 | - --label=org.opencontainers.image.description={{ .ProjectName }} 134 | - --label=org.opencontainers.image.url=https://www.lucagrulla.com/cw 135 | - --label=org.opencontainers.image.source=https://github.com/lucagrulla/cw 136 | - --label=org.opencontainers.image.version={{ .Version }} 137 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 138 | - --label=org.opencontainers.image.licenses=Apache-2.0 139 | - image_templates: ["lucagrulla/{{ .ProjectName }}:{{ .Version }}-amd64"] 140 | goarch: amd64 141 | dockerfile: Dockerfile.release 142 | build_flag_templates: 143 | - --platform=linux/amd64 144 | - --label=org.opencontainers.image.title={{ .ProjectName }} 145 | - --label=org.opencontainers.image.description={{ .ProjectName }} 146 | - --label=org.opencontainers.image.url=https://www.lucagrulla.com/cw 147 | - --label=org.opencontainers.image.source=https://github.com/lucagrulla/cw 148 | - --label=org.opencontainers.image.version={{ .Version }} 149 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 150 | - --label=org.opencontainers.image.licenses=Apache-2.0 151 | - image_templates: ["lucagrulla/{{ .ProjectName }}:{{ .Version }}-arm64v8"] 152 | goarch: arm64 153 | dockerfile: Dockerfile.release 154 | build_flag_templates: 155 | - --platform=linux/arm64/v8 156 | - --label=org.opencontainers.image.title={{ .ProjectName }} 157 | - --label=org.opencontainers.image.description={{ .ProjectName }} 158 | - --label=org.opencontainers.image.url=https://www.lucagrulla.com/cw 159 | - --label=org.opencontainers.image.source=https://github.com/lucagrulla/cw 160 | - --label=org.opencontainers.image.version={{ .Version }} 161 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 162 | - --label=org.opencontainers.image.licenses=Apache-2.0 163 | docker_manifests: 164 | - name_template: "lucagrulla/{{ .ProjectName }}:{{ .Version }}" 165 | image_templates: 166 | - lucagrulla/{{ .ProjectName }}:{{ .Version }}-i386 167 | - lucagrulla/{{ .ProjectName }}:{{ .Version }}-amd64 168 | - lucagrulla/{{ .ProjectName }}:{{ .Version }}-arm64v8 169 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.15-alpine AS build_base 2 | 3 | RUN apk add --no-cache git 4 | 5 | # Set the Current Working Directory inside the container 6 | WORKDIR /tmp/cw 7 | 8 | # We want to populate the module cache based on the go.{mod,sum} files. 9 | COPY go.mod . 10 | COPY go.sum . 11 | 12 | RUN go mod download 13 | 14 | COPY . . 15 | 16 | # Unit tests 17 | RUN CGO_ENABLED=0 go test -v 18 | 19 | # Build the Go app 20 | RUN go build -o ./out/cw . 21 | 22 | 23 | # Start fresh from a smaller image 24 | FROM alpine:3 25 | RUN apk add ca-certificates 26 | 27 | COPY --from=build_base /tmp/cw/out/cw /app/cw 28 | 29 | ENTRYPOINT ["/app/cw"] 30 | -------------------------------------------------------------------------------- /Dockerfile.release: -------------------------------------------------------------------------------- 1 | FROM alpine 2 | 3 | ENTRYPOINT ["/usr/bin/cw"] 4 | 5 | COPY cw /usr/bin/cw 6 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | branch = "master" 6 | name = "github.com/alecthomas/template" 7 | packages = [ 8 | ".", 9 | "parse" 10 | ] 11 | revision = "a0175ee3bccc567396460bf5acd36800cb10c49c" 12 | 13 | [[projects]] 14 | branch = "master" 15 | name = "github.com/alecthomas/units" 16 | packages = ["."] 17 | revision = "2efee857e7cfd4f3d0138cc3cbb1b4966962b93a" 18 | 19 | [[projects]] 20 | name = "github.com/aws/aws-sdk-go" 21 | packages = [ 22 | "aws", 23 | "aws/awserr", 24 | "aws/awsutil", 25 | "aws/client", 26 | "aws/client/metadata", 27 | "aws/corehandlers", 28 | "aws/credentials", 29 | "aws/credentials/ec2rolecreds", 30 | "aws/credentials/endpointcreds", 31 | "aws/credentials/stscreds", 32 | "aws/csm", 33 | "aws/defaults", 34 | "aws/ec2metadata", 35 | "aws/endpoints", 36 | "aws/request", 37 | "aws/session", 38 | "aws/signer/v4", 39 | "internal/sdkio", 40 | "internal/sdkrand", 41 | "internal/shareddefaults", 42 | "private/protocol", 43 | "private/protocol/json/jsonutil", 44 | "private/protocol/jsonrpc", 45 | "private/protocol/query", 46 | "private/protocol/query/queryutil", 47 | "private/protocol/rest", 48 | "private/protocol/xml/xmlutil", 49 | "service/cloudwatchlogs", 50 | "service/sts" 51 | ] 52 | revision = "852052a10992d92f68b9a60862a3312292524903" 53 | version = "v1.14.17" 54 | 55 | [[projects]] 56 | name = "github.com/davecgh/go-spew" 57 | packages = ["spew"] 58 | revision = "346938d642f2ec3594ed81d874461961cd0faa76" 59 | version = "v1.1.0" 60 | 61 | [[projects]] 62 | name = "github.com/fatih/color" 63 | packages = ["."] 64 | revision = "5b77d2a35fb0ede96d138fc9a99f5c9b6aef11b4" 65 | version = "v1.7.0" 66 | 67 | [[projects]] 68 | name = "github.com/go-ini/ini" 69 | packages = ["."] 70 | revision = "06f5f3d67269ccec1fe5fe4134ba6e982984f7f5" 71 | version = "v1.37.0" 72 | 73 | [[projects]] 74 | name = "github.com/jmespath/go-jmespath" 75 | packages = ["."] 76 | revision = "0b12d6b5" 77 | 78 | [[projects]] 79 | name = "github.com/mattn/go-colorable" 80 | packages = ["."] 81 | revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072" 82 | version = "v0.0.9" 83 | 84 | [[projects]] 85 | name = "github.com/mattn/go-isatty" 86 | packages = ["."] 87 | revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" 88 | version = "v0.0.3" 89 | 90 | [[projects]] 91 | name = "github.com/pmezard/go-difflib" 92 | packages = ["difflib"] 93 | revision = "792786c7400a136282c1664665ae0a8db921c6c2" 94 | version = "v1.0.0" 95 | 96 | [[projects]] 97 | name = "github.com/stretchr/testify" 98 | packages = ["assert"] 99 | revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" 100 | version = "v1.2.2" 101 | 102 | [[projects]] 103 | branch = "master" 104 | name = "golang.org/x/sys" 105 | packages = ["unix"] 106 | revision = "9527bec2660bd847c050fda93a0f0c6dee0800bb" 107 | 108 | [[projects]] 109 | name = "gopkg.in/alecthomas/kingpin.v2" 110 | packages = ["."] 111 | revision = "947dcec5ba9c011838740e680966fd7087a71d0d" 112 | version = "v2.2.6" 113 | 114 | [solve-meta] 115 | analyzer-name = "dep" 116 | analyzer-version = 1 117 | inputs-digest = "30e3c958943f3d3fff78aad61c0b49c8491c77024f2e1eb3bf4640489a5186f6" 118 | solver-name = "gps-cdcl" 119 | solver-version = 1 120 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | 22 | 23 | [[constraint]] 24 | name = "github.com/fatih/color" 25 | version = "1.5.0" 26 | 27 | [[constraint]] 28 | name = "gopkg.in/alecthomas/kingpin.v2" 29 | version = "2.2.5" 30 | 31 | 32 | [[constraint]] 33 | name = "github.com/aws/aws-sdk-go" 34 | version = "1.14.13" 35 | -------------------------------------------------------------------------------- /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 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cw 2 | 3 | [![Release](https://img.shields.io/github/release/lucagrulla/cw.svg?style=flat-square)](https://github.com/lucagrulla/cw/releases/latest) 4 | [![Software License](https://img.shields.io/badge/license-apache2-brightgreen.svg?style=flat-square)](LICENSE.md) 5 | ![Github All Releases](https://img.shields.io/github/downloads/lucagrulla/cw/total.svg) 6 | ![CircleCI branch](https://img.shields.io/circleci/project/github/lucagrulla/cw/master.svg?label=CircleCI) 7 | 8 | ![cw - the best way to tail AWS CloudWatch Logs](https://github.com/lucagrulla/cw/raw/master/images/cw-logo1280x640.png) 9 | 10 | The **best** way to tail AWS CloudWatch Logs from your terminal. 11 | 12 | Author - [Luca Grulla](https://www.lucagrulla.com) - [https://www.lucagrulla.com](https://www.lucagrulla.com) 13 | 14 | 15 | * [Features](##features) 16 | * [Installation](#installation) 17 | * [Commands and options](#commands-and-options) 18 | * [Examples](#examples) 19 | * [AWS credentials and configuration](#AWS-credentials-and-configuration) 20 | * [Miscellaneous](#miscellaneous) 21 | * [Release notes](https://github.com/lucagrulla/cw/wiki/Release-notes) 22 | 23 | ## Features 24 | 25 | - **No external dependencies** 26 | - cw is a native executable targeting your OS. No pip, npm, rubygems. 27 | - **Fast**. 28 | - cw is written in golang and compiled against your architecture. 29 | - **Flexible date and time parser**. 30 | - Work with either `Local` timezone or `UTC` (default). 31 | - Flexible parsing. 32 | - Human friendly formats, i.e. `2d1h20m` to indicate 2 days, 1 hour and 20 minutes ago. 33 | - a specific hour, i.e. `13:10` to indicate 13:10 of today. 34 | - a full timestamp `2018-10-20T8:53`. 35 | - **Multi log groups tailing** 36 | - tail multiple log groups in parallel: `cw tail my-auth-service my-web`. 37 | - Powerful built-in **grep** (`--grep`) and **grepv** (`--grepv`). 38 | - [JMESPath](https://jmespath.org/) support for JSON queries (matching the [AWS CLI `--query`](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html#cli-usage-filter-client-side) flag) 39 | - **Pipe operator** supported 40 | - `echo my-group | cw tail` and `cat groups.txt | cw tail`. 41 | - **Redirection operator >>** supported 42 | - `cw tail -f my-stream >> myfile.txt`. 43 | - Coloured output 44 | - `--no-color` flag to disable if needed. 45 | - Flexible credentials control. 46 | - By default the **AWS .aws/credentials and .aws/profile** files are used. Overrides can be achieved with the `--profile` and `--region` flags. 47 | 48 | ## Installation 49 | 50 | ### Mac OSX 51 | 52 | #### using [Homebrew](https://brew.sh) 53 | 54 | ```bash 55 | brew tap lucagrulla/tap 56 | brew install cw 57 | ``` 58 | 59 | ### Linux 60 | 61 | #### using [Linuxbrew](https://linuxbrew.sh/brew/) 62 | 63 | ```bash 64 | brew tap lucagrulla/tap 65 | brew install cw 66 | ``` 67 | 68 | #### .deb/.rpm 69 | 70 | Download the `.deb` or `.rpm` from the [releases page](https://github.com/lucagrulla/cw/releases/latest) and install with `dpkg -i` and `rpm -i` respectively. 71 | 72 | #### using [Snapcraft.io](https://snapcraft.io) 73 | 74 | _Note_: If you upgrade to 3.3.0 please note the new alias command. This is required to comply with snapcraft new release rules. 75 | 76 | ```bash 77 | snap install cw-sh 78 | sudo snap connect cw-sh:dot-aws-config-credentials 79 | sudo snap alias cw-sh.cw cw 80 | ``` 81 | 82 | `cw` runs with strict confinement; the `dot-aws-config-credentials` interface connection is required to have access to `.aws/config` and `.aws/credentials` files 83 | 84 | [![Get it from the Snap Store](https://snapcraft.io/static/images/badges/en/snap-store-white.svg)](https://snapcraft.io/cw-sh) 85 | 86 | ### On Windows 87 | 88 | #### using [Scoop.sh](https://scoop.sh/) 89 | 90 | ```bash 91 | scoop bucket add cw https://github.com/lucagrulla/cw-scoop-bucket.git 92 | scoop install cw 93 | ``` 94 | 95 | ### Go tools 96 | 97 | ```bash 98 | go get github.com/lucagrulla/cw 99 | ``` 100 | 101 | ## Commands and options 102 | 103 | ### Global flags 104 | 105 | - `--profile=profile-name` Override the AWS profile used for connection. 106 | - `--region=aws-region` Override the target AWS region. 107 | - `--no-color` Disable coloured output. 108 | - `--endpoint` The target AWS endpoint url. By default cw will use the default aws endpoints. 109 | - `--no-version-check` Ignore checks if a newer version of the module is available. 110 | 111 | ### Commands 112 | 113 | - `cw ls` list all the log groups/log streams within a group 114 | 115 | ```console 116 | Usage: cw ls 117 | 118 | show an entity 119 | 120 | Flags: 121 | -h, --help Show context-sensitive help. 122 | --endpoint=URL The target AWS endpoint url. By default cw will use the default aws endpoints. NOTE: v4.0.0 123 | dropped the flag short version. 124 | --profile=PROFILE The target AWS profile. By default cw will use the default profile defined in the 125 | .aws/credentials file. NOTE: v4.0.0 dropped the flag short version. 126 | --region=REGION The target AWS region. By default cw will use the default region defined in the 127 | .aws/credentials file. NOTE: v4.0.0 dropped the flag short version. 128 | --no-color Disable coloured output.NOTE: v4.0.0 dropped the flag short version. 129 | --version Print version information and quit 130 | --no-version-check Ignore checks if a newer version of the module is available. 131 | 132 | Commands: 133 | ls groups 134 | Show all groups. 135 | 136 | ls streams 137 | Show all streams in a given log group. 138 | 139 | cw: error: expected one of "groups", "streams" 140 | ``` 141 | 142 | - `cw tail` tail a given log group/log stream 143 | 144 | ```console 145 | Usage: cw tail ... 146 | 147 | Tail log groups/streams. 148 | 149 | Arguments: 150 | ... The log group and stream name, with group:prefix syntax. Stream name can be just the prefix. If no stream name is specified all stream names in the given 151 | group will be tailed. Multiple group/stream tuple can be passed. e.g. cw tail group1:prefix1 group2:prefix2 group3:prefix3. 152 | 153 | Flags: 154 | -h, --help Show context-sensitive help. 155 | --endpoint=URL The target AWS endpoint url. By default cw will use the default aws endpoints. NOTE: v4.0.0 dropped the flag short version. 156 | --profile=PROFILE The target AWS profile. By default cw will use the default profile defined in the .aws/credentials file. NOTE: v4.0.0 dropped the flag short version. 157 | --region=REGION The target AWS region. By default cw will use the default region defined in the .aws/credentials file. NOTE: v4.0.0 dropped the flag short version. 158 | --no-color Disable coloured output.NOTE: v4.0.0 dropped the flag short version. 159 | --version Print version information and quit 160 | --no-version-check Ignore checks if a newer version of the module is available. 161 | 162 | -f, --follow Don't stop when the end of streams is reached, but rather wait for additional data to be appended. 163 | -t, --timestamp Print the event timestamp. 164 | -i, --event-id Print the event Id. 165 | -s, --stream-name Print the log stream name this event belongs to. 166 | -n, --group-name Print the log group name this event belongs to. 167 | -r, --retry Keep trying to open a log group/log stream if it is inaccessible. 168 | -b, --start="2021-04-11T08:21:52" The UTC start time. Passed as either date/time or human-friendly format. The human-friendly format accepts the number of days, hours and minutes prior to 169 | the present. Denote days with 'd', hours with 'h' and minutes with 'm' i.e. 80m, 4h30m, 2d4h. If just time is used (format: hh[:mm]) it is expanded to 170 | today at the given time. Full available date/time format: 2017-02-27[T09[:00[:00]]. 171 | -e, --end=STRING The UTC end time. Passed as either date/time or human-friendly format. The human-friendly format accepts the number of days, hours and minutes prior to the 172 | present. Denote days with 'd', hours with 'h' and minutes with 'm' i.e. 80m, 4h30m, 2d4h. If just time is used (format: hh[:mm]) it is expanded to today at 173 | the given time. Full available date/time format: 2017-02-27[T09[:00[:00]]. 174 | -l, --local Treat date and time in Local timezone. 175 | -g, --grep=STRING Pattern to filter logs by. See http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html for syntax. 176 | -v, --grepv=STRING Equivalent of grep --invert-match. Invert match pattern to filter logs by. 177 | -q, --query=STRING Equivalent of the --query flag in AWS CLI. Takes a JMESPath expression to filter JSON logs by. If the query fails (e.g. the log message was not JSON) then the original line is returned. 178 | ``` 179 | 180 | ## Examples 181 | 182 | - list of the available log groups 183 | - `cw ls groups` 184 | - list of the log streams in a given log group 185 | - `cw ls streams my-log-group` 186 | - tail and follow given log groups/streams 187 | 188 | - `cw tail -f my-log-group` 189 | - `cw tail -f my-log-group:my-log-stream-prefix` 190 | - `cw tail -f my-log-group:my-log-stream-prefix my-log-group2` 191 | - `cw tail -f my-log-group:my-log-stream-prefix -b2017-01-01T08:10:10 -e2017-01-01T08:05:00` 192 | - `cw tail -f my-log-group:my-log-stream-prefix -b7d` to start from 7 days ago. 193 | - `cw tail -f my-log-group:my-log-stream-prefix -b3h` to start from 3 hours ago. 194 | - `cw tail -f my-log-group:my-log-stream-prefix -b100m` to start from 100 minutes ago. 195 | - `cw tail -f my-log-group:my-log-stream-prefix -b2h30m` to start from 2 hours and 30 minutes ago. 196 | - `cw tail -f my-log-group -b9:00 -e9:01` 197 | 198 | - query JSON logs using [JMESPath](https://jmespath.org/) syntax 199 | - `cw tail -f my-log-group --query "machines[?state=='running'].name"` 200 | 201 | ## Time and Dates 202 | 203 | Time and dates are treated as UTC by default. 204 | Use the `--local` flag if you prefer to use Local zone. 205 | 206 | ## AWS credentials and configuration 207 | 208 | `cw` uses the default credentials profile (stored in ./aws/credentials) for authentication and shared config (.aws/config) for identifying the target AWS region. Both profile and region are overridable via the `profile` and `region` global flags. 209 | 210 | ### AWS SSO 211 | 212 | AWS SSO is supported if you: 213 | 214 | * use a CLI profile (either `default` or an alternate named profile) that includes the various SSO properties 215 | * `sso_start_url`, `sso_account_id`, `sso_role_name`, etc 216 | * have a valid, active SSO session 217 | * via `aws sso login` 218 | 219 | If you get an error message that includes `...failed to sign request: failed to retrieve credentials: the SSO session has expired or is invalid...` then you should renew your SSO session via `aws sso login` (and specify the named profile, if appropriate). 220 | 221 | ## Miscellaneous 222 | 223 | ### Use `cw` behind a proxy 224 | 225 | Please use `HTTP_PROXY` environment variable as required by AWS cli: 226 | 227 | 228 | ## Breaking changes notes 229 | 230 | Read [here](https://github.com/lucagrulla/cw/wiki/Breaking-changes-notes) 231 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate 2 | google_analytics: "UA-1839356-1" 3 | url: https://www.lucagrulla.com 4 | 5 | # title: cw 6 | # description: The best way to tail AWS CloudWatch Logs from your terminal 7 | # google_analytics: UA-1839356-1 8 | # show_downloads: true 9 | # #theme: jekyll-theme-minimal 10 | # remote_theme: pmarsceill/just-the-docs 11 | # url: https://www.lucagrulla.com 12 | # aux_links: 13 | # " Made with ❤️ by Luca Grulla": 14 | # - "https://www.lucagrulla.com" 15 | # " Github repo": 16 | # - "https://github.com/lucagrulla/cw" 17 | 18 | 19 | -------------------------------------------------------------------------------- /cloudwatch/client.go: -------------------------------------------------------------------------------- 1 | // Package cloudwatch provides primitives to interact with Cloudwatch logs 2 | package cloudwatch 3 | 4 | import ( 5 | "context" 6 | "fmt" 7 | "log" 8 | "os" 9 | 10 | "github.com/aws/aws-sdk-go-v2/aws" 11 | "github.com/aws/aws-sdk-go-v2/config" 12 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs" 13 | ) 14 | 15 | // New creates a new instance of the cloudwatchlogs client 16 | func New(awsEndpointURL *string, awsProfile *string, awsRegion *string, log *log.Logger) *cloudwatchlogs.Client { 17 | //workaround to figure out the user actual home dir within a SNAP (rather than the sandboxed one) 18 | //and access the .aws folder in its default location 19 | if os.Getenv("SNAP_INSTANCE_NAME") != "" { 20 | log.Printf("Snap Identified") 21 | realUserHomeDir := fmt.Sprintf("/home/%s", os.Getenv("USER")) 22 | if os.Getenv("AWS_SHARED_CREDENTIALS_FILE") == "" { 23 | credentialsPath := fmt.Sprintf("%s/.aws/credentials", realUserHomeDir) 24 | log.Printf("No custom credentials file location. Overriding to %s", credentialsPath) 25 | os.Setenv("AWS_SHARED_CREDENTIALS_FILE", credentialsPath) 26 | } 27 | if os.Getenv("AWS_CONFIG_FILE") == "" { 28 | configPath := fmt.Sprintf("%s/.aws/config", realUserHomeDir) 29 | log.Printf("No custom config file location. Overriding to %s", configPath) 30 | os.Setenv("AWS_CONFIG_FILE", configPath) 31 | } 32 | } 33 | 34 | profile := "" 35 | region := "" 36 | if awsProfile != nil && *awsProfile != "" { 37 | profile = *awsProfile 38 | } 39 | if awsRegion != nil && *awsRegion != "" { 40 | region = *awsRegion 41 | } 42 | 43 | log.Printf("awsProfile: %s, awsRegion: %s endpoint: %s\n", profile, region, *awsEndpointURL) 44 | 45 | customResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { 46 | // customResolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) { 47 | if awsEndpointURL != nil && *awsEndpointURL != "" { 48 | log.Printf("awsEndpointURL:%s", *awsEndpointURL) 49 | return aws.Endpoint{ 50 | PartitionID: "aws", 51 | URL: *awsEndpointURL, 52 | SigningRegion: region, 53 | SigningName: "logs", 54 | }, nil 55 | } 56 | // returning EndpointNotFoundError will allow the service to fallback to it's default resolution 57 | return aws.Endpoint{}, &aws.EndpointNotFoundError{} 58 | }) 59 | 60 | cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithSharedConfigProfile(profile), 61 | config.WithEndpointResolverWithOptions(customResolver), config.WithRegion(region)) 62 | if err != nil { 63 | os.Exit(1) 64 | } 65 | return cloudwatchlogs.NewFromConfig(cfg) 66 | } 67 | -------------------------------------------------------------------------------- /cloudwatch/cloudwatchlogs_test.go: -------------------------------------------------------------------------------- 1 | package cloudwatch 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io" 7 | "log" 8 | "os" 9 | "testing" 10 | "time" 11 | 12 | "github.com/aws/aws-sdk-go-v2/aws" 13 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs" 14 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types" 15 | "github.com/stretchr/testify/assert" 16 | ) 17 | 18 | var ( 19 | streams = []types.LogStream{ 20 | {LogStreamName: aws.String("stream1"), LastIngestionTime: aws.Int64(time.Now().Unix())}, 21 | {LogStreamName: aws.String("stream2"), LastIngestionTime: aws.Int64(time.Now().AddDate(1, 0, 0).Unix())}} 22 | ) 23 | 24 | type MockPager struct { 25 | PageNum int 26 | Pages []*cloudwatchlogs.DescribeLogStreamsOutput 27 | err error 28 | } 29 | 30 | func (m *MockPager) HasMorePages() bool { 31 | return m.PageNum < len(m.Pages) 32 | } 33 | func (m *MockPager) NextPage(ctx context.Context, optFns ...func(*cloudwatchlogs.Options)) (*cloudwatchlogs.DescribeLogStreamsOutput, error) { 34 | if m.err != nil { 35 | return nil, m.err 36 | } 37 | if m.PageNum >= len(m.Pages) { 38 | return nil, fmt.Errorf("no more pages") 39 | } 40 | output := m.Pages[m.PageNum] 41 | m.PageNum++ 42 | return output, nil 43 | } 44 | 45 | func TestLsStreams(t *testing.T) { 46 | pag := &MockPager{PageNum: 0, 47 | Pages: []*cloudwatchlogs.DescribeLogStreamsOutput{{LogStreams: streams}}, 48 | } 49 | ch := make(chan types.LogStream) 50 | errCh := make(chan error) 51 | go getStreams(pag, errCh, ch) 52 | 53 | for l := range ch { 54 | assert.Contains(t, streams, l) 55 | } 56 | } 57 | 58 | func TestTailShouldFailIfNoStreamsAdNoRetry(t *testing.T) { 59 | idleCh := make(chan bool) 60 | 61 | fetchStreams := func() (<-chan types.LogStream, <-chan error) { 62 | ch := make(chan types.LogStream) 63 | errCh := make(chan error, 1) 64 | rnf := &types.ResourceNotFoundException{ 65 | Message: new(string), 66 | } 67 | errCh <- rnf 68 | return ch, errCh 69 | } 70 | retry := false 71 | debugLog := log.New(io.Discard, "cw [debug] ", log.LstdFlags) 72 | err := initialiseStreams(&retry, idleCh, nil, fetchStreams, debugLog) 73 | 74 | assert.Error(t, err) 75 | } 76 | 77 | func TestTailWaitForStreamsWithRetry(t *testing.T) { 78 | log.SetOutput(os.Stderr) 79 | idleCh := make(chan bool, 1) 80 | 81 | callsToFetchStreams := 0 82 | fetchStreams := func() (<-chan types.LogStream, <-chan error) { 83 | callsToFetchStreams++ 84 | ch := make(chan types.LogStream, 5) 85 | errCh := make(chan error, 1) 86 | 87 | if callsToFetchStreams == 2 { 88 | for _, s := range streams { 89 | ch <- s 90 | } 91 | close(ch) 92 | } else { 93 | rnf := &types.ResourceNotFoundException{ 94 | Message: new(string), 95 | } 96 | errCh <- rnf 97 | } 98 | return ch, errCh 99 | } 100 | 101 | retry := true 102 | logStreams := &logStreamsType{} 103 | debugLog := log.New(io.Discard, "cw [debug] ", log.LstdFlags) 104 | err := initialiseStreams(&retry, idleCh, logStreams, fetchStreams, debugLog) 105 | 106 | assert.Nil(t, err) 107 | assert.Len(t, logStreams.get(), 2) 108 | var streamNames []string 109 | for _, ls := range streams { 110 | streamNames = append(streamNames, *ls.LogStreamName) 111 | } 112 | for _, s := range logStreams.get() { 113 | assert.Contains(t, streamNames, s) 114 | } 115 | } 116 | 117 | func TestShortenLogStreamsListIfTooLong(t *testing.T) { 118 | 119 | var streams = []types.LogStream{} 120 | 121 | size := 105 122 | for i := 0; i < size; i++ { 123 | name := fmt.Sprintf("streams%d", i) 124 | x := &types.LogStream{LogStreamName: aws.String(name)} 125 | streams = append(streams, *x) 126 | } 127 | 128 | assert.Len(t, streams, size) 129 | streams = sortLogStreamsByMostRecentEvent(streams) 130 | assert.Len(t, streams, 100) 131 | } 132 | 133 | func TestSortLogStreamsByMostRecentEvent(t *testing.T) { 134 | 135 | var streams = []types.LogStream{} 136 | 137 | size := 105 138 | for i := 0; i < size; i++ { 139 | t := aws.Int64(time.Now().AddDate(0, 0, -i).Unix()) 140 | name := fmt.Sprintf("stream%d", i) 141 | x := &types.LogStream{LogStreamName: aws.String(name), LastIngestionTime: t} 142 | streams = append(streams, *x) 143 | } 144 | 145 | first := streams[0] 146 | last := streams[size-1] 147 | assert.Greater(t, *first.LastIngestionTime, *last.LastIngestionTime) 148 | streams = sortLogStreamsByMostRecentEvent(streams) 149 | 150 | // eventTimestamp := *s.LastEventTimestamp / 1000 151 | // ts := time.Unix(eventTimestamp, 0).Format(timeFormat) 152 | 153 | assert.Len(t, streams, 100) 154 | assert.Equal(t, *streams[len(streams)-1].LogStreamName, "stream0") 155 | first = streams[0] 156 | last = streams[len(streams)-1] 157 | assert.Less(t, *first.LastIngestionTime, *last.LastIngestionTime) 158 | } 159 | -------------------------------------------------------------------------------- /cloudwatch/eventTTLCache.go: -------------------------------------------------------------------------------- 1 | package cloudwatch 2 | 3 | import ( 4 | "log" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | const defaultPurgeFreq = 10 * time.Second 10 | 11 | type eventCache struct { 12 | seen map[string]int64 13 | mostRecentTS int64 14 | sync.RWMutex 15 | } 16 | 17 | func createCache(ttl time.Duration, purgeFreq time.Duration, log *log.Logger) *eventCache { 18 | if purgeFreq == 0 { 19 | purgeFreq = defaultPurgeFreq 20 | } 21 | cache := &eventCache{seen: make(map[string]int64)} 22 | 23 | log.Printf("cache: ttl:%s check-time:%s\n", ttl.String(), purgeFreq.String()) 24 | 25 | janitor := func(c *eventCache, ttl time.Duration, freq time.Duration) { 26 | cacheTicker := time.NewTicker(purgeFreq) 27 | for range cacheTicker.C { 28 | c.Lock() 29 | 30 | var ids []string 31 | now := time.Now() 32 | for id, ts := range c.seen { 33 | if ts != c.mostRecentTS { //keep logs with latest timestamp to avoid duplication on consecutive calls 34 | t := time.Unix(ts/1000, 0) 35 | purgeCandidate := now.Sub(t).Seconds() >= ttl.Seconds() 36 | if purgeCandidate { 37 | ids = append(ids, id) 38 | } 39 | } else { 40 | log.Printf("%s to be retained with timestamp %d \n", id, ts) 41 | } 42 | } 43 | log.Println("entries to purge:", len(ids)) 44 | 45 | for _, id := range ids { 46 | delete(c.seen, id) 47 | } 48 | c.Unlock() 49 | } 50 | } 51 | 52 | go janitor(cache, ttl, purgeFreq) 53 | 54 | return cache 55 | } 56 | 57 | func (c *eventCache) Has(eventID string) bool { 58 | c.RLock() 59 | defer c.RUnlock() 60 | return c.seen[eventID] != 0 61 | } 62 | 63 | func (c *eventCache) Add(eventID string, ts int64) { 64 | c.Lock() 65 | defer c.Unlock() 66 | c.seen[eventID] = ts 67 | c.mostRecentTS = ts 68 | } 69 | 70 | func (c *eventCache) Size() int { 71 | c.RLock() 72 | defer c.RUnlock() 73 | return len(c.seen) 74 | } 75 | -------------------------------------------------------------------------------- /cloudwatch/eventTTLCache_test.go: -------------------------------------------------------------------------------- 1 | package cloudwatch 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "testing" 7 | "time" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | const ttl = 1 * time.Second 13 | const purgeFreq = 2 * time.Second 14 | 15 | func TestCache(t *testing.T) { 16 | l := log.New(io.Discard, "", log.LstdFlags) 17 | 18 | a := assert.New(t) 19 | cache := createCache(ttl, purgeFreq, l) 20 | cache.Add("1", 1) 21 | cache.Add("2", 2) 22 | cache.Add("3", 3) 23 | 24 | a.True(cache.Has("1")) 25 | a.True(cache.Has("2")) 26 | a.True(cache.Has("3")) 27 | 28 | time.Sleep((purgeFreq + (1 * time.Second))) //wait for the cache janitor to kick in 29 | 30 | a.False(cache.Has("1")) 31 | a.False(cache.Has("2")) 32 | 33 | a.True(cache.Has("3"), "last added item should be retained") 34 | 35 | a.Equal(cache.Size(), 1) 36 | } 37 | -------------------------------------------------------------------------------- /cloudwatch/lsgroups.go: -------------------------------------------------------------------------------- 1 | package cloudwatch 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs" 9 | ) 10 | 11 | //LsGroups lists the stream groups 12 | //It returns a channel where stream groups are published 13 | func LsGroups(cwc *cloudwatchlogs.Client) <-chan *string { 14 | ch := make(chan *string) 15 | params := &cloudwatchlogs.DescribeLogGroupsInput{} 16 | 17 | go func() { 18 | paginator := cloudwatchlogs.NewDescribeLogGroupsPaginator(cwc, params) 19 | for paginator.HasMorePages() { 20 | res, err := paginator.NextPage(context.TODO()) 21 | if err != nil { 22 | fmt.Fprintln(os.Stderr, err.Error()) 23 | close(ch) 24 | os.Exit(1) 25 | } 26 | for _, logGroup := range res.LogGroups { 27 | ch <- logGroup.LogGroupName 28 | } 29 | } 30 | close(ch) 31 | }() 32 | return ch 33 | } 34 | -------------------------------------------------------------------------------- /cloudwatch/lsstreams.go: -------------------------------------------------------------------------------- 1 | package cloudwatch 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs" 7 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types" 8 | ) 9 | 10 | type logStreamsPager interface { 11 | HasMorePages() bool 12 | NextPage(ctx context.Context, optFns ...func(*cloudwatchlogs.Options)) (*cloudwatchlogs.DescribeLogStreamsOutput, error) 13 | } 14 | 15 | func getStreams(paginator logStreamsPager, errCh chan error, ch chan types.LogStream) { 16 | for paginator.HasMorePages() { 17 | res, err := paginator.NextPage(context.TODO()) 18 | if err != nil { 19 | errCh <- err 20 | return 21 | } 22 | 23 | for _, logStream := range res.LogStreams { 24 | ch <- logStream 25 | } 26 | 27 | } 28 | close(ch) 29 | close(errCh) 30 | } 31 | 32 | //LsStreams lists the streams of a given stream group 33 | //It returns a channel where the stream names are published in order of Last Ingestion Time (the first stream is the one with older Last Ingestion Time) 34 | func LsStreams(cwc cloudwatchlogs.DescribeLogStreamsAPIClient, groupName *string, streamName *string) (<-chan types.LogStream, <-chan error) { 35 | ch := make(chan types.LogStream) 36 | errCh := make(chan error) 37 | 38 | params := &cloudwatchlogs.DescribeLogStreamsInput{ 39 | LogGroupName: groupName} 40 | if streamName != nil && *streamName != "" { 41 | params.LogStreamNamePrefix = streamName 42 | } 43 | paginator := cloudwatchlogs.NewDescribeLogStreamsPaginator(cwc, params) 44 | go getStreams(paginator, errCh, ch) 45 | return ch, errCh 46 | } 47 | -------------------------------------------------------------------------------- /cloudwatch/tail.go: -------------------------------------------------------------------------------- 1 | package cloudwatch 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "log" 8 | "os" 9 | "regexp" 10 | "sort" 11 | "strings" 12 | "sync" 13 | "time" 14 | 15 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs" 16 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types" 17 | ) 18 | 19 | type logStreamsType struct { 20 | groupStreams []string 21 | sync.RWMutex 22 | } 23 | 24 | func (s *logStreamsType) reset(groupStreams []string) { 25 | s.Lock() 26 | defer s.Unlock() 27 | s.groupStreams = groupStreams 28 | } 29 | 30 | func (s *logStreamsType) get() []string { 31 | s.Lock() 32 | defer s.Unlock() 33 | return s.groupStreams 34 | } 35 | 36 | func makeParams(logGroupName string, streamNames []string, _ *string, 37 | startTimeInMillis int64, endTimeInMillis int64, 38 | grep *string, follow *bool) *cloudwatchlogs.FilterLogEventsInput { 39 | 40 | params := &cloudwatchlogs.FilterLogEventsInput{ 41 | LogGroupName: &logGroupName, 42 | StartTime: &startTimeInMillis} 43 | 44 | if *grep != "" { 45 | params.FilterPattern = grep 46 | } 47 | 48 | if streamNames != nil { 49 | params.LogStreamNames = streamNames 50 | } 51 | // if logStreamNamePrefix != nil { 52 | // params.LogStreamNamePrefix = logStreamNamePrefix 53 | // } 54 | 55 | if !*follow && endTimeInMillis != 0 { 56 | params.EndTime = &endTimeInMillis 57 | } 58 | return params 59 | } 60 | 61 | type fs func() (<-chan types.LogStream, <-chan error) 62 | 63 | func sortLogStreamsByMostRecentEvent(logStream []types.LogStream) []types.LogStream { 64 | sort.SliceStable(logStream, func(i, j int) bool { 65 | var streamALastIngestionTime int64 = 0 66 | var streamBLastIngestionTime int64 = 0 67 | 68 | if ingestionTime := logStream[i].LastIngestionTime; ingestionTime != nil { 69 | streamALastIngestionTime = *ingestionTime 70 | } 71 | 72 | if ingestionTime := logStream[j].LastIngestionTime; ingestionTime != nil { 73 | streamBLastIngestionTime = *ingestionTime 74 | } 75 | 76 | return streamALastIngestionTime < streamBLastIngestionTime 77 | }) 78 | if len(logStream) > 100 { 79 | logStream = logStream[len(logStream)-100:] 80 | } 81 | return logStream 82 | } 83 | 84 | func initialiseStreams(retry *bool, idle chan<- bool, logStreams *logStreamsType, fetchStreams fs, logger *log.Logger) error { 85 | executionCh := make(chan time.Time, 1) 86 | executionCh <- time.Now() 87 | 88 | getTargetStreams := func() ([]string, error) { 89 | var streams []types.LogStream 90 | foundStreams, errCh := fetchStreams() 91 | outerLoop: 92 | for { 93 | select { 94 | case e := <-errCh: 95 | if e != nil { 96 | logger.Println("error while fetching log streams.", e) 97 | return nil, e 98 | } 99 | case stream, ok := <-foundStreams: //TODO improve performance 100 | if ok { 101 | streams = append(streams, stream) 102 | } else { 103 | break outerLoop 104 | } 105 | case <-time.After(5 * time.Second): 106 | //TODO handle deadlock scenario 107 | } 108 | } 109 | //FilterLogEventPages won't take more than 100 stream names, the most one with most recent activities will be used. 110 | logger.Println("streams found:", len(streams)) 111 | 112 | if len(streams) >= 100 { 113 | streams = sortLogStreamsByMostRecentEvent(streams) 114 | } 115 | 116 | var streamNames []string 117 | for _, s := range streams { 118 | streamNames = append(streamNames, *s.LogStreamName) 119 | } 120 | return streamNames, nil 121 | } 122 | 123 | for range executionCh { 124 | s, e := getTargetStreams() 125 | if e != nil { 126 | rnf := &types.ResourceNotFoundException{} 127 | if errors.As(e, &rnf) && *retry { 128 | logger.Println("log group not available but retry flag. Re-check in 150 milliseconds.") 129 | timer := time.After(time.Millisecond * 150) 130 | executionCh <- <-timer 131 | } else { 132 | return e 133 | } 134 | } else { 135 | logStreams.reset(s) 136 | 137 | idle <- true 138 | close(executionCh) 139 | } 140 | } 141 | //refresh streams list every 5 secs 142 | t := time.NewTicker(time.Second * 5) 143 | go func() { 144 | for range t.C { 145 | s, _ := getTargetStreams() 146 | if s != nil { 147 | logStreams.reset(s) 148 | } 149 | } 150 | }() 151 | return nil 152 | } 153 | 154 | type TailConfig struct { 155 | LogGroupName *string 156 | LogStreamName *string 157 | Follow *bool 158 | Retry *bool 159 | StartTime *time.Time 160 | EndTime *time.Time 161 | Grep *string 162 | Grepv *string 163 | } 164 | 165 | //Tail tails the given stream names in the specified log group name 166 | //To tail all the available streams logStreamName has to be '*' 167 | //It returns a channel where logs line are published 168 | //Unless the follow flag is true the channel is closed once there are no more events available 169 | func Tail(cwc *cloudwatchlogs.Client, 170 | tailConfig TailConfig, 171 | limiter <-chan time.Time, 172 | logger *log.Logger) (<-chan types.FilteredLogEvent, error) { 173 | 174 | lastSeenTimestamp := tailConfig.StartTime.Unix() * 1000 175 | var endTimeInMillis int64 176 | if !tailConfig.EndTime.IsZero() { 177 | endTimeInMillis = tailConfig.EndTime.Unix() * 1000 178 | } 179 | 180 | ch := make(chan types.FilteredLogEvent, 1000) 181 | idle := make(chan bool, 1) 182 | 183 | ttl := 60 * time.Second 184 | cache := createCache(ttl, defaultPurgeFreq, logger) 185 | 186 | logStreams := &logStreamsType{} 187 | 188 | if tailConfig.LogStreamName != nil && *tailConfig.LogStreamName != "" { 189 | fetchStreams := func() (<-chan types.LogStream, <-chan error) { 190 | return LsStreams(cwc, tailConfig.LogGroupName, tailConfig.LogStreamName) 191 | } 192 | err := initialiseStreams(tailConfig.Retry, idle, logStreams, fetchStreams, logger) 193 | if err != nil { 194 | // logger.Println("got an error back:", err) 195 | return nil, err 196 | } 197 | } else { 198 | idle <- true 199 | } 200 | re := regexp.MustCompile(*tailConfig.Grepv) 201 | go func() { 202 | for range limiter { 203 | select { 204 | case <-idle: 205 | logParam := makeParams(*tailConfig.LogGroupName, logStreams.get(), tailConfig.LogStreamName, lastSeenTimestamp, endTimeInMillis, tailConfig.Grep, tailConfig.Follow) 206 | paginator := cloudwatchlogs.NewFilterLogEventsPaginator(cwc, logParam) 207 | for paginator.HasMorePages() { 208 | res, err := paginator.NextPage(context.TODO()) 209 | if err != nil { 210 | logger.Println(err.Error()) 211 | if strings.Contains(err.Error(), "ThrottlingException") { //could not find the native error...fmt. 212 | logger.Printf("Rate exceeded for %s. Wait for 250ms then retry.\n", *tailConfig.LogGroupName) 213 | 214 | //Wait and fire request again. 1 Retry allowed. 215 | time.Sleep(250 * time.Millisecond) 216 | res, err = paginator.NextPage(context.TODO()) 217 | if err != nil { 218 | fmt.Fprintln(os.Stderr, err.Error()) 219 | os.Exit(1) 220 | } 221 | } else { 222 | fmt.Fprintln(os.Stderr, err.Error()) 223 | os.Exit(1) 224 | } 225 | } 226 | for _, event := range res.Events { 227 | if *tailConfig.Grepv == "" || !re.MatchString(*event.Message) { 228 | if !cache.Has(*event.EventId) { 229 | eventTimestamp := *event.Timestamp 230 | 231 | if eventTimestamp != lastSeenTimestamp { 232 | if eventTimestamp < lastSeenTimestamp { 233 | logger.Printf("old event:%s, ev-ts:%d, last-ts:%d, cache-size:%d \n", *event.Message, eventTimestamp, lastSeenTimestamp, cache.Size()) 234 | } 235 | lastSeenTimestamp = eventTimestamp 236 | } 237 | cache.Add(*event.EventId, *event.Timestamp) 238 | ch <- event 239 | } else { 240 | logger.Printf("%s already seen\n", *event.EventId) 241 | } 242 | } 243 | } 244 | 245 | } 246 | if !*tailConfig.Follow { 247 | close(ch) 248 | } else { 249 | idle <- true 250 | } 251 | case <-time.After(5 * time.Millisecond): 252 | logger.Printf("%s still tailing, Skip polling.\n", *tailConfig.LogGroupName) 253 | } 254 | } 255 | }() 256 | return ch, nil 257 | } 258 | -------------------------------------------------------------------------------- /coordinator.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/ring" 5 | "log" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | type tailCoordinator struct { 11 | targets *ring.Ring 12 | sync.RWMutex 13 | log *log.Logger 14 | } 15 | 16 | func (f *tailCoordinator) start(targets []chan<- time.Time) { 17 | f.targets = ring.New(len(targets)) 18 | for i := 0; i < f.targets.Len(); i++ { 19 | f.targets.Value = targets[i] 20 | f.targets = f.targets.Next() 21 | } 22 | 23 | //AWS API accepts 5 reqs/sec for account 24 | ticker := time.NewTicker(250 * time.Millisecond) 25 | go func() { 26 | for range ticker.C { 27 | if f.targets == nil { 28 | f.log.Println("coordinator: ring buffer is empty, exiting scheduler.") 29 | return 30 | } 31 | f.Lock() 32 | x := f.targets.Value.(chan<- time.Time) 33 | x <- time.Now() 34 | f.targets = f.targets.Next() 35 | f.Unlock() 36 | } 37 | }() 38 | } 39 | 40 | func (f *tailCoordinator) remove(c chan<- time.Time) { 41 | f.RLock() 42 | initialLen := f.targets.Len() 43 | f.RUnlock() 44 | 45 | var visited int 46 | f.Lock() 47 | defer f.Unlock() 48 | 49 | if f.targets.Len() == 1 { 50 | f.targets = ring.New(0) 51 | f.log.Println("coordinator: single node buffer: reset", f.targets.Len()) 52 | 53 | return 54 | } 55 | 56 | for visited = 0; visited < f.targets.Len(); visited++ { 57 | if f.targets.Value == c { 58 | targetChan := f.targets.Value.(chan<- time.Time) 59 | 60 | f.targets = f.targets.Prev() 61 | f.targets.Unlink(1) 62 | close(targetChan) 63 | f.log.Printf("coordinator: channel found and removed at index: %d\n", visited) 64 | 65 | break 66 | } 67 | f.targets = f.targets.Next() 68 | } 69 | 70 | if f.targets.Len() < initialLen { 71 | for i := 0; i < visited; i++ { 72 | f.targets = f.targets.Prev() 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /cw.bash: -------------------------------------------------------------------------------- 1 | _cw_bash_autocomplete() { 2 | local cur prev opts base 3 | COMPREPLY=() 4 | cur="${COMP_WORDS[COMP_CWORD]}" 5 | opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} ) 6 | COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) 7 | return 0 8 | } 9 | complete -F _cw_bash_autocomplete cw -------------------------------------------------------------------------------- /cw.zsh: -------------------------------------------------------------------------------- 1 | #compdef cw 2 | autoload -U compinit && compinit 3 | autoload -U bashcompinit && bashcompinit 4 | 5 | _cw_bash_autocomplete() { 6 | local cur prev opts base 7 | COMPREPLY=() 8 | cur="${COMP_WORDS[COMP_CWORD]}" 9 | opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} ) 10 | COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) 11 | return 0 12 | } 13 | complete -F _cw_bash_autocomplete cw -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/lucagrulla/cw 2 | 3 | require ( 4 | github.com/alecthomas/kong v0.8.0 5 | github.com/aws/aws-sdk-go-v2 v1.17.8 6 | github.com/aws/aws-sdk-go-v2/config v1.18.21 7 | github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.20.9 8 | github.com/fatih/color v1.15.0 9 | github.com/jmespath/go-jmespath v0.4.0 10 | github.com/stretchr/testify v1.8.4 11 | golang.org/x/sys v0.7.0 // indirect 12 | ) 13 | 14 | go 1.13 15 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/alecthomas/assert/v2 v2.1.0 h1:tbredtNcQnoSd3QBhQWI7QZ3XHOVkw1Moklp2ojoH/0= 2 | github.com/alecthomas/assert/v2 v2.1.0/go.mod h1:b/+1DI2Q6NckYi+3mXyH3wFb8qG37K/DuK80n7WefXA= 3 | github.com/alecthomas/kong v0.8.0 h1:ryDCzutfIqJPnNn0omnrgHLbAggDQM2VWHikE1xqK7s= 4 | github.com/alecthomas/kong v0.8.0/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U= 5 | github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE= 6 | github.com/alecthomas/repr v0.1.0/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= 7 | github.com/aws/aws-sdk-go-v2 v1.17.8 h1:GMupCNNI7FARX27L7GjCJM8NgivWbRgpjNI/hOQjFS8= 8 | github.com/aws/aws-sdk-go-v2 v1.17.8/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= 9 | github.com/aws/aws-sdk-go-v2/config v1.18.21 h1:ENTXWKwE8b9YXgQCsruGLhvA9bhg+RqAsL9XEMEsa2c= 10 | github.com/aws/aws-sdk-go-v2/config v1.18.21/go.mod h1:+jPQiVPz1diRnjj6VGqWcLK6EzNmQ42l7J3OqGTLsSY= 11 | github.com/aws/aws-sdk-go-v2/credentials v1.13.20 h1:oZCEFcrMppP/CNiS8myzv9JgOzq2s0d3v3MXYil/mxQ= 12 | github.com/aws/aws-sdk-go-v2/credentials v1.13.20/go.mod h1:xtZnXErtbZ8YGXC3+8WfajpMBn5Ga/3ojZdxHq6iI8o= 13 | github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.2 h1:jOzQAesnBFDmz93feqKnsTHsXrlwWORNZMFHMV+WLFU= 14 | github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.2/go.mod h1:cDh1p6XkSGSwSRIArWRc6+UqAQ7x4alQ0QfpVR6f+co= 15 | github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.32 h1:dpbVNUjczQ8Ae3QKHbpHBpfvaVkRdesxpTOe9pTouhU= 16 | github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.32/go.mod h1:RudqOgadTWdcS3t/erPQo24pcVEoYyqj/kKW5Vya21I= 17 | github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.26 h1:QH2kOS3Ht7x+u0gHCh06CXL/h6G8LQJFpZfFBYBNboo= 18 | github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.26/go.mod h1:vq86l7956VgFr0/FWQ2BWnK07QC3WYsepKzy33qqY5U= 19 | github.com/aws/aws-sdk-go-v2/internal/ini v1.3.33 h1:HbH1VjUgrCdLJ+4lnnuLI4iVNRvBbBELGaJ5f69ClA8= 20 | github.com/aws/aws-sdk-go-v2/internal/ini v1.3.33/go.mod h1:zG2FcwjQarWaqXSCGpgcr3RSjZ6dHGguZSppUL0XR7Q= 21 | github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.20.9 h1:sXs+JjIwgKA27t+5O8YgXl0cmZpEmctyDVO5y6cMdqA= 22 | github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.20.9/go.mod h1:CpWhQvomfSbbrfUhq9sq/w2x4wbkQOAqGJbcPS2AINA= 23 | github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.26 h1:uUt4XctZLhl9wBE1L8lobU3bVN8SNUP7T+olb0bWBO4= 24 | github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.26/go.mod h1:Bd4C/4PkVGubtNe5iMXu5BNnaBi/9t/UsFspPt4ram8= 25 | github.com/aws/aws-sdk-go-v2/service/sso v1.12.8 h1:5cb3D6xb006bPTqEfCNaEA6PPEfBXxxy4NNeX/44kGk= 26 | github.com/aws/aws-sdk-go-v2/service/sso v1.12.8/go.mod h1:GNIveDnP+aE3jujyUSH5aZ/rktsTM5EvtKnCqBZawdw= 27 | github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.8 h1:NZaj0ngZMzsubWZbrEFSB4rgSQRbFq38Sd6KBxHuOIU= 28 | github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.8/go.mod h1:44qFP1g7pfd+U+sQHLPalAPKnyfTZjJsYR4xIwsJy5o= 29 | github.com/aws/aws-sdk-go-v2/service/sts v1.18.9 h1:Qf1aWwnsNkyAoqDqmdM3nHwN78XQjec27LjM6b9vyfI= 30 | github.com/aws/aws-sdk-go-v2/service/sts v1.18.9/go.mod h1:yyW88BEPXA2fGFyI2KCcZC3dNpiT0CZAHaF+i656/tQ= 31 | github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= 32 | github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= 33 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 34 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 35 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 36 | github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= 37 | github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= 38 | github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= 39 | github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 40 | github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= 41 | github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= 42 | github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= 43 | github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= 44 | github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= 45 | github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= 46 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= 47 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= 48 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 49 | github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= 50 | github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 51 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 52 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 53 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 54 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 55 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 56 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 57 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 58 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 59 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 60 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 61 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 62 | golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= 63 | golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 64 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 65 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 66 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= 67 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 68 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 69 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 70 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 71 | -------------------------------------------------------------------------------- /images/cw-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lucagrulla/cw/25e8679c2c05ec8ca7781d768a1ae5a8e8b136aa/images/cw-logo.png -------------------------------------------------------------------------------- /images/cw-logo1280x640.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lucagrulla/cw/25e8679c2c05ec8ca7781d768a1ae5a8e8b136aa/images/cw-logo1280x640.png -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "log" 10 | "os" 11 | "regexp" 12 | "strconv" 13 | "strings" 14 | "sync" 15 | "time" 16 | "unicode" 17 | 18 | "github.com/alecthomas/kong" 19 | "github.com/aws/aws-sdk-go-v2/aws" 20 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs" 21 | "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types" 22 | 23 | "github.com/fatih/color" 24 | "github.com/jmespath/go-jmespath" 25 | "github.com/lucagrulla/cw/cloudwatch" 26 | ) 27 | 28 | const ( 29 | timeFormat = "2006-01-02T15:04:05" 30 | ) 31 | 32 | var version = "" //injected at build time 33 | 34 | func timestampToTime(timeStamp *string, local bool) (time.Time, error) { 35 | var zone *time.Location 36 | if local { 37 | zone = time.Local 38 | } else { 39 | zone = time.UTC 40 | } 41 | if regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`).MatchString(*timeStamp) { 42 | t, _ := time.ParseInLocation("2006-01-02", *timeStamp, zone) 43 | return t, nil 44 | } else if regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}$`).MatchString(*timeStamp) { 45 | t, _ := time.ParseInLocation("2006-01-02T15", *timeStamp, zone) 46 | return t, nil 47 | } else if regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$`).MatchString(*timeStamp) { 48 | t, _ := time.ParseInLocation("2006-01-02T15:04", *timeStamp, zone) 49 | return t, nil 50 | } else if regexp.MustCompile(`^\d{1,2}$`).MatchString(*timeStamp) { 51 | y, m, d := time.Now().In(zone).Date() 52 | t, _ := strconv.Atoi(*timeStamp) 53 | return time.Date(y, m, d, t, 0, 0, 0, zone), nil 54 | } else if res := regexp.MustCompile(`^(?P\d{1,2}):(?P\d{2})$`).FindStringSubmatch(*timeStamp); res != nil { 55 | y, m, d := time.Now().Date() 56 | 57 | t, _ := strconv.Atoi(res[1]) 58 | mm, _ := strconv.Atoi(res[2]) 59 | 60 | return time.Date(y, m, d, t, mm, 0, 0, zone), nil 61 | } else if res := regexp.MustCompile( 62 | `^(?:(?P\d{1,})(?:d))?(?P(?:\d{1,}h)?(?:\d{1,}m)?)?$`).FindStringSubmatch( 63 | *timeStamp); res != nil { 64 | // Unfortunately, ParseDuration does not support day time unit 65 | days, _ := strconv.Atoi(res[1]) 66 | d, _ := time.ParseDuration(res[2]) 67 | 68 | t := time.Now().In(zone).AddDate(0, 0, -days).Add(-d) 69 | y, m, dd := t.Date() 70 | return time.Date(y, m, dd, t.Hour(), t.Minute(), 0, 0, zone), nil 71 | } 72 | 73 | //TODO check even last scenario and if it's not a recognized pattern throw an error 74 | t, err := time.ParseInLocation("2006-01-02T15:04:05", *timeStamp, zone) 75 | if err != nil { 76 | return t, err 77 | } 78 | return t, nil 79 | } 80 | 81 | type logEvent struct { 82 | // logEvent cloudwatchlogs.FilteredLogEvent 83 | logEvent types.FilteredLogEvent 84 | logGroup string 85 | } 86 | 87 | type formatConfig struct { 88 | PrintTime bool 89 | PrintStreamName bool 90 | PrintGroupName bool 91 | PrintEventID bool 92 | Query *jmespath.JMESPath 93 | } 94 | 95 | type logEventFormatter struct { 96 | Log *log.Logger 97 | FormatConfig formatConfig 98 | } 99 | 100 | // jmespathQuery returns a the stringified results of a pre-compiled JMESPath query 101 | // if the query fails, it will return the original string. 102 | func (f logEventFormatter) jmespathQuery(s string, query jmespath.JMESPath) string { 103 | var data interface{} 104 | err := json.Unmarshal([]byte(s), &data) 105 | if err != nil { 106 | f.Log.Printf("Failed query using jmespathQuery: Error: %v\n", err) 107 | return s 108 | } 109 | result, err := query.Search(data) 110 | if err != nil { 111 | f.Log.Printf("Failed query using jmespathQuery: Error: %v\n", err) 112 | return s 113 | } 114 | if result == nil { 115 | return fmt.Sprintf(" %s", s) 116 | } 117 | searchResult, err := json.Marshal(result) 118 | if err != nil { 119 | f.Log.Printf("Failed to marshall jmespathQuery result to json: Error: %v\n", err) 120 | return s 121 | } 122 | return string(searchResult) 123 | } 124 | 125 | func (f logEventFormatter) formatLogMsg(ev logEvent) string { 126 | msg := *ev.logEvent.Message 127 | 128 | if f.FormatConfig.Query != nil { 129 | msg = f.jmespathQuery(msg, *f.FormatConfig.Query) 130 | } 131 | 132 | if f.FormatConfig.PrintEventID { 133 | msg = fmt.Sprintf("%s - %s", color.YellowString(*ev.logEvent.EventId), msg) 134 | } 135 | if f.FormatConfig.PrintStreamName { 136 | msg = fmt.Sprintf("%s - %s", color.BlueString(*ev.logEvent.LogStreamName), msg) 137 | } 138 | 139 | if f.FormatConfig.PrintGroupName { 140 | msg = fmt.Sprintf("%s - %s", color.CyanString(ev.logGroup), msg) 141 | } 142 | 143 | if f.FormatConfig.PrintTime { 144 | eventTimestamp := *ev.logEvent.Timestamp / 1000 145 | ts := time.Unix(eventTimestamp, 0).Format(timeFormat) 146 | msg = fmt.Sprintf("%s - %s", color.GreenString(ts), msg) 147 | } 148 | return msg 149 | } 150 | 151 | func fromStdin() []string { 152 | var groups []string 153 | info, _ := os.Stdin.Stat() 154 | if info.Mode()&os.ModeNamedPipe != 0 { 155 | scanner := bufio.NewScanner(os.Stdin) 156 | for scanner.Scan() { 157 | input := scanner.Text() 158 | if len(input) > 0 { 159 | tokens := strings.FieldsFunc(strings.TrimSpace(scanner.Text()), func(c rune) bool { 160 | return unicode.IsSpace(c) 161 | }) 162 | groups = append(groups, tokens...) 163 | } 164 | } 165 | } 166 | return groups 167 | } 168 | 169 | type appContext struct { 170 | Debug bool 171 | Client cloudwatchlogs.Client 172 | DebugLog *log.Logger 173 | } 174 | 175 | type lsGroupsCmd struct { 176 | } 177 | type lsStreamsCmd struct { 178 | GroupName string `arg required name:"group" help:"The group name."` 179 | } 180 | 181 | type tailCmd struct { 182 | LogGroupStreamName []string `arg required name:"groupName[:logStreamPrefix]" help:"The log group and stream name, with group:prefix syntax. Stream name can be just the prefix. If no stream name is specified all stream names in the given group will be tailed. Multiple group/stream tuple can be passed. e.g. cw tail group1:prefix1 group2:prefix2 group3:prefix3."` 183 | Follow bool `help:"Don't stop when the end of streams is reached, but rather wait for additional data to be appended." default:"false" short:"f"` 184 | PrintTimeStamp bool `name:"timestamp" help:"Print the event timestamp." short:"t" default:"false"` 185 | PrintEventID bool `name:"event-id" help:"Print the event Id." short:"i" default:"false"` 186 | PrintStreamName bool `name:"stream-name" help:"Print the log stream name this event belongs to." short:"s" default:"false"` 187 | PrintGroupName bool `name:"group-name" help:"Print the log group name this event belongs to." short:"n" default:"false"` 188 | Retry bool `name:"retry" help:"Keep trying to open a log group/log stream if it is inaccessible." short:"r" default:"false"` 189 | StartTime string `name:"start" help:"The UTC start time. Passed as either date/time or human-friendly format. The human-friendly format accepts the number of days, hours and minutes prior to the present. Denote days with 'd', hours with 'h' and minutes with 'm' i.e. 80m, 4h30m, 2d4h. If just time is used (format: hh[:mm]) it is expanded to today at the given time. Full available date/time format: 2017-02-27[T09[:00[:00]]." short:"b" default:"${now}"` 190 | EndTime string `name:"end" help:"The UTC end time. Passed as either date/time or human-friendly format. The human-friendly format accepts the number of days, hours and minutes prior to the present. Denote days with 'd', hours with 'h' and minutes with 'm' i.e. 80m, 4h30m, 2d4h. If just time is used (format: hh[:mm]) it is expanded to today at the given time. Full available date/time format: 2017-02-27[T09[:00[:00]]." short:"e" default:""` 191 | Local bool `name:"local" help:"Treat date and time in Local timezone." short:"l" default:"false"` 192 | Grep string `name:"grep" help:"Pattern to filter logs by. See http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html for syntax." short:"g" default:""` 193 | Grepv string `name:"grepv" help:"Equivalent of grep --invert-match. Invert match pattern to filter logs by." short:"v" default:""` 194 | Query string `name:"query" help:"Equivalent of the --query flag in AWS CLI. Takes a JMESPath expression to filter JSON logs by." short:"q" default:""` 195 | } 196 | 197 | func (t *tailCmd) Run(ctx *appContext) error { 198 | if additionalInput := fromStdin(); additionalInput != nil { 199 | t.LogGroupStreamName = append(t.LogGroupStreamName, additionalInput...) 200 | } 201 | if len(t.LogGroupStreamName) == 0 { 202 | fmt.Fprintln(os.Stderr, "cw: error: required argument 'groupName[:logStreamPrefix]' not provided, try --help") 203 | os.Exit(1) 204 | } 205 | 206 | st, err := timestampToTime(&t.StartTime, t.Local) 207 | if err != nil { 208 | fmt.Fprintf(os.Stderr, "can't parse %s as a valid date/time\n", t.StartTime) 209 | os.Exit(1) 210 | } 211 | var et time.Time 212 | if t.EndTime != "" { 213 | endT, errr := timestampToTime(&t.EndTime, t.Local) 214 | if errr != nil { 215 | fmt.Fprintf(os.Stderr, "can't parse %s as a valid date/time\n", t.EndTime) 216 | os.Exit(1) 217 | } else { 218 | et = endT 219 | } 220 | } 221 | out := make(chan *logEvent) 222 | 223 | var wg sync.WaitGroup 224 | 225 | triggerChannels := make([]chan<- time.Time, len(t.LogGroupStreamName)) 226 | 227 | coordinator := &tailCoordinator{log: ctx.DebugLog} 228 | for idx, gs := range t.LogGroupStreamName { 229 | trigger := make(chan time.Time, 1) 230 | go func(groupStream string) { 231 | tokens := strings.Split(groupStream, ":") 232 | var prefix string 233 | group := tokens[0] 234 | if len(tokens) > 1 && tokens[1] != "*" { 235 | prefix = tokens[1] 236 | } 237 | ch, e := cloudwatch.Tail(&ctx.Client, cloudwatch.TailConfig{ 238 | LogGroupName: &group, 239 | LogStreamName: &prefix, 240 | Follow: &t.Follow, 241 | Retry: &t.Retry, 242 | StartTime: &st, 243 | EndTime: &et, 244 | Grep: &t.Grep, 245 | Grepv: &t.Grepv, 246 | }, trigger, ctx.DebugLog) 247 | if e != nil { 248 | fmt.Fprintln(os.Stderr, e.Error()) 249 | os.Exit(1) 250 | } 251 | for le := range ch { 252 | out <- &logEvent{logEvent: le, logGroup: group} 253 | } 254 | coordinator.remove(trigger) 255 | wg.Done() 256 | }(gs) 257 | triggerChannels[idx] = trigger 258 | wg.Add(1) 259 | } 260 | 261 | coordinator.start(triggerChannels) 262 | 263 | go func() { 264 | wg.Wait() 265 | ctx.DebugLog.Println("closing main channel...") 266 | 267 | close(out) 268 | }() 269 | 270 | config := formatConfig{ 271 | PrintTime: t.PrintTimeStamp, 272 | PrintStreamName: t.PrintStreamName, 273 | PrintGroupName: t.PrintGroupName, 274 | PrintEventID: t.PrintEventID, 275 | } 276 | if t.Query != "" { 277 | query, err := jmespath.Compile(t.Query) 278 | if err != nil { 279 | return fmt.Errorf("failed to parse query as JMESPath query. Query: \"%s\", error: \"%w\"", t.Query, err) 280 | } 281 | config.Query = query 282 | } 283 | 284 | formatter := logEventFormatter{ 285 | FormatConfig: config, 286 | Log: ctx.DebugLog} 287 | 288 | for logEv := range out { 289 | fmt.Println(formatter.formatLogMsg(*logEv)) 290 | } 291 | return nil 292 | } 293 | 294 | type lsCmd struct { 295 | LsGroups lsGroupsCmd `cmd name:"groups" help:"Show all groups."` 296 | LsStreamsCmd lsStreamsCmd `cmd name:"streams" help:"Show all streams in a given log group."` 297 | } 298 | 299 | func (l *lsStreamsCmd) Run(ctx *appContext) error { 300 | foundStreams, errorsCh := cloudwatch.LsStreams(&ctx.Client, &l.GroupName, aws.String("")) 301 | for { 302 | select { 303 | case e := <-errorsCh: 304 | if e != nil { 305 | rnf := &types.ResourceNotFoundException{} 306 | if errors.As(e, &rnf) { 307 | fmt.Fprintln(os.Stderr, *rnf.Message) 308 | } else { 309 | fmt.Fprintln(os.Stderr, e.Error()) 310 | } 311 | os.Exit(1) 312 | } 313 | case msg, ok := <-foundStreams: 314 | if ok { 315 | fmt.Println(*msg.LogStreamName) 316 | } else { 317 | return nil 318 | } 319 | case <-time.After(5 * time.Second): 320 | fmt.Fprintln(os.Stderr, "Unable to fetch log streams.") 321 | os.Exit(1) 322 | } 323 | } 324 | } 325 | 326 | func (r *lsGroupsCmd) Run(ctx *appContext) error { 327 | for msg := range cloudwatch.LsGroups(&ctx.Client) { 328 | fmt.Println(*msg) 329 | } 330 | return nil 331 | } 332 | 333 | var cli struct { 334 | Debug bool `name:"debug" hidden help:"Enable debug mode."` 335 | 336 | AwsEndpointURL string `name:"endpoint" help:"The target AWS endpoint url. By default cw will use the default aws endpoints. NOTE: v4.0.0 dropped the flag short version." placeholder:"URL"` 337 | AwsProfile string `help:"The target AWS profile. By default cw will use the default profile defined in the .aws/credentials file. NOTE: v4.0.0 dropped the flag short version." name:"profile" placeholder:"PROFILE"` 338 | AwsRegion string `name:"region" help:"The target AWS region. By default cw will use the default region defined in the .aws/credentials file. NOTE: v4.0.0 dropped the flag short version." placeholder:"REGION"` 339 | NoColor bool `name:"no-color" help:"Disable coloured output.NOTE: v4.0.0 dropped the flag short version. " default:"false"` 340 | NoVersionCheck bool `name:"no-version-check" help:"Ignore checks if a newer version of the module is available. " default:"false"` 341 | Version kong.VersionFlag `name:"version" help:"Print version information and quit"` 342 | 343 | Ls lsCmd `cmd help:"show an entity"` 344 | Tail tailCmd `cmd help:"Tail log groups/streams."` 345 | } 346 | 347 | func main() { 348 | 349 | ctx := kong.Parse(&cli, 350 | kong.Vars{"now": time.Now().UTC().Add(-45 * time.Second).Format(timeFormat), "version": version}, 351 | kong.UsageOnError(), 352 | kong.Name("cw"), 353 | kong.Description("The best way to tail AWS Cloudwatch Logs from your terminal.")) 354 | 355 | debugLog := log.New(io.Discard, "cw [debug] ", log.LstdFlags) 356 | if cli.Debug { 357 | debugLog.SetOutput(os.Stderr) 358 | debugLog.Println("Debug mode is on. Will print debug messages to stderr") 359 | } 360 | 361 | if !cli.NoVersionCheck { 362 | defer newVersionMsg(version, fetchLatestVersion()) 363 | go versionCheckOnSigterm() 364 | } 365 | 366 | if cli.NoColor { 367 | color.NoColor = true 368 | } 369 | client := cloudwatch.New(&cli.AwsEndpointURL, &cli.AwsProfile, &cli.AwsRegion, debugLog) 370 | err := ctx.Run(&appContext{Debug: cli.Debug, Client: *client, DebugLog: debugLog}) 371 | ctx.FatalIfErrorf(err) 372 | } 373 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | //"fmt" 5 | 6 | "io" 7 | "log" 8 | "testing" 9 | "time" 10 | 11 | "github.com/stretchr/testify/assert" //"reflect" 12 | ) 13 | 14 | func TestTimestampToTime(t *testing.T) { 15 | assert := assert.New(t) 16 | 17 | a := "2017-03-12" 18 | parsedTime, _ := timestampToTime(&a, false) 19 | assert.Equal(time.Date(2017, 3, 12, 0, 0, 0, 0, time.UTC), parsedTime, 20 | "wrong parsing for input %s", a) 21 | 22 | a = "2017-03-12T18" 23 | parsedTime, _ = timestampToTime(&a, false) 24 | 25 | assert.Equal(time.Date(2017, 3, 12, 18, 0, 0, 0, time.UTC), parsedTime, 26 | "wrong parsing for input %s", a) 27 | 28 | a = "2017-03-12T18:22" 29 | parsedTime, _ = timestampToTime(&a, false) 30 | 31 | assert.Equal(time.Date(2017, 3, 12, 18, 22, 0, 0, time.UTC), parsedTime, 32 | "wrong parsing for input %s", a) 33 | 34 | a = "2017-03-12T18:22:23" 35 | parsedTime, _ = timestampToTime(&a, false) 36 | 37 | assert.Equal(time.Date(2017, 3, 12, 18, 22, 23, 0, time.UTC), parsedTime, 38 | "wrong parsing for input %s", a) 39 | 40 | a = "18" 41 | y, m, d := time.Now().Date() 42 | parsedTime, _ = timestampToTime(&a, false) 43 | 44 | assert.Equal(time.Date(y, m, d, 18, 0, 0, 0, time.UTC), parsedTime, 45 | "wrong parsing for input %s", a) 46 | 47 | a = "18:31" 48 | y, m, d = time.Now().Date() 49 | parsedTime, _ = timestampToTime(&a, false) 50 | 51 | assert.Equal(time.Date(y, m, d, 18, 31, 0, 0, time.UTC), parsedTime, 52 | "wrong parsing for input %s", a) 53 | } 54 | 55 | func TestHumanReadableTimeToTime(t *testing.T) { 56 | assert := assert.New(t) 57 | 58 | s := "2d" 59 | x := time.Now().UTC().AddDate(0, 0, -2) 60 | 61 | y, m, d := x.Date() 62 | 63 | parsedTime, _ := timestampToTime(&s, false) 64 | assert.Equal(time.Date(y, m, d, x.Hour(), x.Minute(), 0, 0, time.UTC), 65 | parsedTime, "wrong parsing for input %s", s) 66 | 67 | s = "03d50m" 68 | dd, _ := time.ParseDuration(`50m`) 69 | x = time.Now().UTC().AddDate(0, 0, -3).Add(-dd) 70 | 71 | y, m, d = x.Date() 72 | 73 | parsedTime, _ = timestampToTime(&s, false) 74 | assert.Equal(time.Date(y, m, d, x.Hour(), x.Minute(), 0, 0, time.UTC), 75 | parsedTime, "wrong parsing for input %s", s) 76 | 77 | s = "32h" 78 | dd, _ = time.ParseDuration(s) 79 | x = time.Now().UTC().Add(-dd) 80 | 81 | y, m, d = x.Date() 82 | 83 | parsedTime, _ = timestampToTime(&s, false) 84 | assert.Equal(time.Date(y, m, d, x.Hour(), x.Minute(), 0, 0, time.UTC), parsedTime, "wrong parsing for input %s", s) 85 | 86 | s = "50m" 87 | dd, _ = time.ParseDuration(s) 88 | x = time.Now().UTC().Add(-dd) 89 | 90 | y, m, d = x.Date() 91 | 92 | parsedTime, _ = timestampToTime(&s, false) 93 | assert.Equal(time.Date(y, m, d, x.Hour(), x.Minute(), 0, 0, time.UTC), parsedTime, "wrong parsing for input %s", s) 94 | 95 | s = "2h30m" 96 | dd, _ = time.ParseDuration(s) 97 | x = time.Now().UTC().Add(-dd) 98 | 99 | y, m, d = x.Date() 100 | 101 | parsedTime, _ = timestampToTime(&s, false) 102 | assert.Equal(time.Date(y, m, d, x.Hour(), x.Minute(), 0, 0, time.UTC), parsedTime, "wrong parsing for input %s", s) 103 | } 104 | 105 | func TestWrongFormat(t *testing.T) { 106 | assert := assert.New(t) 107 | a := "log-group" 108 | _, err := timestampToTime(&a, false) 109 | assert.Error(err) 110 | } 111 | 112 | func TestCoordinatorRemoveItem(t *testing.T) { 113 | a := assert.New(t) 114 | log := log.New(io.Discard, "", log.LstdFlags) 115 | 116 | groupTrigger1 := make(chan time.Time, 1) 117 | groupTrigger2 := make(chan time.Time, 1) 118 | 119 | channels := []chan<- time.Time{chan<- time.Time(groupTrigger1), 120 | chan<- time.Time(groupTrigger2)} 121 | 122 | coordinator := &tailCoordinator{log: log} 123 | coordinator.start(channels) 124 | 125 | coordinator.remove(channels[0]) 126 | 127 | select { 128 | case _, ok := <-groupTrigger1: 129 | if ok { 130 | a.Fail("Channel should be closed.") 131 | } 132 | case <-time.After(1 * time.Second): 133 | a.Fail("Timeout") 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /snap/snapcraft.yaml: -------------------------------------------------------------------------------- 1 | name: my-snap-name # you probably want to 'snapcraft register ' 2 | base: core18 # the base snap is the execution environment for this snap 3 | version: '0.1' # just for humans, typically '1.2+git' or '1.3.2' 4 | summary: Single-line elevator pitch for your amazing snap # 79 char long summary 5 | description: | 6 | This is my-snap's description. You have a paragraph or two to tell the 7 | most important story about your snap. Keep it under 100 words though, 8 | we live in tweetspace and your description wants to look good in the snap 9 | store. 10 | 11 | grade: devel # must be 'stable' to release into candidate/stable channels 12 | confinement: devmode # use 'strict' once you have the right plugs and slots 13 | 14 | parts: 15 | my-part: 16 | # See 'snapcraft plugins' 17 | plugin: nil 18 | 19 | 20 | name: cw-sh 21 | version: v3.2.1-next 22 | summary: The best way to tail AWS Cloudwatch Logs from your terminal 23 | description: | 24 | The best way to tail AWS Cloudwatch Logs from your terminal 25 | grade: stable 26 | confinement: strict 27 | base: core18 28 | apps: 29 | cw: 30 | command: cw-sh 31 | cw-sh: 32 | command: cw-sh 33 | plugs: 34 | personal-files: 35 | read: 36 | - $HOME/.aws -------------------------------------------------------------------------------- /versioncheck.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | "os/signal" 8 | "strings" 9 | 10 | "github.com/fatih/color" 11 | ) 12 | 13 | func fetchLatestVersion() chan string { 14 | latestVersionChannel := make(chan string, 1) 15 | go func() { 16 | r, e := http.Get("https://github.com/lucagrulla/cw/releases/latest") 17 | 18 | if e != nil { 19 | close(latestVersionChannel) 20 | } else { 21 | finalURL := r.Request.URL.String() 22 | tokens := strings.Split(finalURL, "/") 23 | latestVersionChannel <- tokens[len(tokens)-1] 24 | } 25 | }() 26 | return latestVersionChannel 27 | } 28 | 29 | func newVersionMsg(currentVersion string, latestVersionChannel chan string) { 30 | latestVersion, ok := <-latestVersionChannel 31 | //if the channel is closed we failed to fetch the latest version. Ignore version message. 32 | if !ok { 33 | if latestVersion != fmt.Sprintf("v%s", currentVersion) { 34 | msg := fmt.Sprintf("\n\n%s - %s -> %s", color.GreenString("A new version of cw is available!"), color.YellowString(currentVersion), color.GreenString(latestVersion)) 35 | fmt.Fprintln(os.Stderr, msg) 36 | } 37 | } 38 | } 39 | 40 | func versionCheckOnSigterm() { 41 | //only way to avoid print of the signal: interrupt message 42 | c := make(chan os.Signal, 1) 43 | signal.Notify(c, os.Interrupt) 44 | <-c 45 | os.Exit(0) 46 | } 47 | --------------------------------------------------------------------------------