diff --git a/.github/workflows/tlogs-test.yml b/.github/workflows/tlogs-test.yml new file mode 100644 index 0000000..397f63c --- /dev/null +++ b/.github/workflows/tlogs-test.yml @@ -0,0 +1,31 @@ +# Lives at /.github/workflows/ ; tests the tlogs/ folder. +name: tlogs tests +on: + push: + paths: ['tlogs/**', '.github/workflows/tlogs-test.yml'] + pull_request: + paths: ['tlogs/**', '.github/workflows/tlogs-test.yml'] + workflow_dispatch: +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + defaults: + run: + working-directory: tlogs + steps: + - uses: actions/checkout@v4 + - name: install tmux + run: | + if [ "$RUNNER_OS" = macOS ]; then brew install tmux; else sudo apt-get update && sudo apt-get install -y tmux shellcheck; fi + - name: shellcheck + if: runner.os == 'Linux' + run: shellcheck -S warning tlogs install.sh tests/test.sh + - name: tests (default bash) + run: bash tests/test.sh + - name: tests (macOS system bash 3.2) + if: runner.os == 'macOS' + run: SH=/bin/bash /bin/bash tests/test.sh diff --git a/tlogs/CHANGELOG.md b/tlogs/CHANGELOG.md new file mode 100644 index 0000000..0b06e47 --- /dev/null +++ b/tlogs/CHANGELOG.md @@ -0,0 +1,18 @@ +# Changelog + +## 2.1.2 +- Pane labels always keep their state colour (a FAILED pane stays red when you select it); the active pane is marked with `>`. +- README: animated demo (`docs/demo.gif`), recorded from a real tlogs run. + +## 2.1.1 +- The watch window's pane is titled `tl-watch` (was the host name). +- Status bar shows the full session name instead of cutting it at 10 characters. + +## 2.1.0 +- Mouse support in tlogs sessions only (`TL_MOUSE=1`, default): click a pane, scroll back, drag borders, right-click menu with Zoom. Other tmux sessions and `~/.tmux.conf` are not changed. `TL_MOUSE=0` for keyboard only. +- CI workflow now lives at the repo root and tests the `tlogs/` folder on Ubuntu and macOS (system bash 3.2). +- 36 tests. + +## 2.0.0 +- Standalone public release: one script, user-defined colour rules (red / amber / yellow / green / blue / dim), log states (RUNNING / DONE / WARN / FAILED), presets for PostgreSQL, pg_upgrade, RDS/Aurora downloads and batch jobs. +- Config files are parsed as data, never executed. diff --git a/tlogs/LICENSE b/tlogs/LICENSE new file mode 100644 index 0000000..de2e1c7 --- /dev/null +++ b/tlogs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Pavanteja Achanta + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tlogs/README.md b/tlogs/README.md new file mode 100644 index 0000000..7295b25 --- /dev/null +++ b/tlogs/README.md @@ -0,0 +1,268 @@ +# tlogs + +**Watch a whole folder of log files in one terminal.** tlogs opens one tmux pane per log, colours each line by keywords you choose, and labels every pane with the log's state: running, done, warn or failed. + +``` +cd /var/log/batch && tlogs -rw +``` + +![tlogs: four job logs open in tmux panes, a new log gets its own pane, a failed job is zoomed, and a clean finish closes itself](docs/demo.gif) + +*Label colours: blue = running, green = done (closes itself in watch mode), amber = warn, red = failed. `>` marks the pane you're on.* + +It's one bash script on top of tmux. Nothing runs on your servers except `tail`, and there's no agent, daemon or database. + +**What tlogs adds to plain tmux:** +- **One command, one pane per log.** Panes are tiled, labelled and coloured for you. +- **Your keywords, your colours.** Six colour rules (red, amber, yellow, green, blue, dim), each a regex. They work out of the box for PostgreSQL `ERROR / WARNING / NOTICE / LOG`, pg_upgrade and typical job logs. +- **A state for every log.** tlogs reads the last lines of each log for markers you define and labels it RUNNING, DONE, WARN or FAILED. +- **`-r` / `-e`** open only the logs still running, or only the ones that need a look. +- **`-w` (watch)** adds a pane when a new log appears and closes a pane a minute after its log finishes cleanly. Failures and warnings stay up. +- **Your terminal can drop safely.** tmux keeps the panes running, so if your SSH or SSM session times out, run `tlogs attach NAME` to get back. + +--- + +## 1. Install + +You need **bash 3.2+** (macOS's built-in bash is fine) and **tmux 3.0+**. + +### Install tmux + +| System | Command | +|---|---| +| macOS | `brew install tmux` | +| Ubuntu / Debian / WSL | `sudo apt-get install -y tmux` | +| Amazon Linux 2023, RHEL / Rocky / Alma 8+, Fedora | `sudo dnf install -y tmux` | +| Alpine | `sudo apk add bash tmux` | +| Amazon Linux 2, CentOS 7 | The packaged tmux is 1.8, which is too old. See [Older systems](#older-systems). | + +Check the version with `tmux -V`. It should print 3.0 or higher. + +### Install tlogs (pick one) + +**A. With git.** Installs to `~/.local/bin`; no sudo needed. +```bash +git clone https://github.com/pavan-postgres/pavanpostgres.git && cd pavanpostgres/tlogs && bash install.sh +``` + +**B. Download just the script.** +```bash +mkdir -p ~/.local/bin && curl -fsSL https://raw.githubusercontent.com/pavan-postgres/pavanpostgres/main/tlogs/tlogs -o ~/.local/bin/tlogs && chmod +x ~/.local/bin/tlogs && ~/.local/bin/tlogs init +``` + +**C. No internet on the box** (e.g. a private EC2 jumpbox). Paste the script in directly: +```bash +mkdir -p ~/.local/bin && cat > ~/.local/bin/tlogs +# now paste the whole contents of the tlogs file, press Enter, then Ctrl-D +chmod +x ~/.local/bin/tlogs && ~/.local/bin/tlogs init +``` + +If `tlogs` isn't found afterwards, add `export PATH="$HOME/.local/bin:$PATH"` to `~/.bashrc` or `~/.zshrc`, then open a new shell. + +`install.sh` never overwrites silently. If a different `tlogs` is already installed, it keeps it as `tlogs.bak.`. `tlogs init` writes `~/.config/tlogs/config` only when that file doesn't exist yet. + +--- + +## 2. Use it + +```bash +cd /path/to/logs +tlogs -l # list every log with its state; opens nothing, safe first step +tlogs # one pane per log +tlogs -r # only logs still running +tlogs -e # only logs that need a look (FAILED or WARN) +tlogs -rw # running logs + watch for new ones (the batch-night mode) +tlogs -g 'postgresql-*.log' # pick files (default '*.log') +tlogs -c ~/pg.conf # use a config file for this run +tlogs /var/log/postgresql # a folder instead of cd +``` + +Other commands: +```bash +tlogs ls # tmux sessions +tlogs attach NAME # back into a session (after a dropped connection, too) +tlogs kill NAME # close a session; asks twice, never touches log files +tlogs color FILE # just colour one file, no tmux: tlogs color app.log +tail -f x.log | tlogs color +tlogs config # the settings in effect in this folder +``` + +**Inside tmux:** + +| Keys | What it does | +|---|---| +| `Ctrl-b z` | Zoom the current pane full screen; press again to go back | +| `Ctrl-b` + arrows | Move between panes | +| `Ctrl-b n` | Open the `tl-watch` window (what `-w` added or closed) | +| `Ctrl-b d` | Detach; everything keeps running | +| `Ctrl-b [` | Scroll; `q` to leave | +| `Ctrl-b q`, then a number | Jump to that pane (the number is in its label) | + +**With the mouse** (on by default, for tlogs sessions only): + +| Mouse | What it does | +|---|---| +| Click a pane | Switch to it | +| Scroll up | Read back through that log; scroll to the bottom to go live again | +| Drag a pane border | Resize | +| Right-click a pane | Menu with **Zoom**, Kill, Swap and more | +| Click `logs` / `tl-watch` in the status bar | Switch window | + +To copy text with the mouse on, hold **Option** (iTerm2) or **Fn** (Terminal.app) while you drag, then `Cmd-C`. Prefer keyboard only? Set `TL_MOUSE=0`. tlogs sets the mouse per session, so your other tmux sessions and `~/.tmux.conf` are not changed. + +--- + +## 3. Make it yours: keywords and colours + +Settings are plain `KEY=VALUE` lines. tlogs reads them as data and **never executes** them, so a config file left in a shared folder can't run code. Each colour rule is an extended regex (`grep -E` style). + +A line is coloured by the **first rule that matches**, in this order: + +| Setting | Colour | Default matches | +|---|---|---| +| `TL_RED_RE` | red | `PANIC: FATAL: ERROR:`, `Failure, exiting`, exception, Traceback, aborted, FAILED | +| `TL_AMBER_RE` | amber | `WARNING:`, `WARN` | +| `TL_YELLOW_RE` | yellow | `NOTICE:`, `HINT:` | +| `TL_GREEN_RE` | green | `Upgrade Complete`, completed successfully, SUCCESS | +| `TL_BLUE_RE` | cyan | (off) | +| `TL_DIM_RE` | dim | `DEBUG1-5:`, `STATEMENT:`, `CONTEXT:` | + +Other display settings: +- `TL_HIGHLIGHT=word` colours only the matched keyword instead of the whole line. +- `TL_ICASE=1` makes every pattern case-insensitive. +- An empty value turns a rule off. +- `NO_COLOR=1` or `TL_NO_COLOR=1` turns colour off entirely. +- `TL_MOUSE=0` turns the mouse off for tlogs sessions (default `1`). + +Some examples: +```bash +TL_BLUE_RE='duration: [0-9]{4,}\.' # PostgreSQL queries slower than 1 s, in cyan +TL_RED_RE='ERROR|OOMKilled|CrashLoop' # your own failure words +TL_GREEN_RE='deploy (done|succeeded)' +TL_BLUE_RE='LOG:' # if you want every LOG: line visible as cyan +``` + +### Log state: what "finished" means + +| State | Rule | +|---|---| +| **DONE** | `TL_OK_RE` appears in the last `TL_TAIL_LINES` lines (default 10) | +| **WARN** | DONE, and `TL_WARN_RE` appears anywhere in the log | +| **FAILED** | `TL_FAIL_RE` appears in the last lines | +| **RUNNING** | anything else | + +If your job prints a clear last line ("job finished", "exit code 0"), tlogs can track it. For logs that never end, like a database server log, set the three state patterns to empty so every log just shows as running. + +### Where settings come from (highest wins) + +1. Environment variables, e.g. `TL_ICASE=1 tlogs` +2. `-c FILE` +3. `.tlogs.conf` in the log folder, so each folder can have its own rules +4. `~/.config/tlogs/config`, created by `tlogs init` and fully commented +5. Built-in defaults + +### Ready-made presets ([`examples/`](examples)) + +| File | For | +|---|---| +| `postgres-server.conf` | PostgreSQL server logs in stderr, csvlog or jsonlog format: `PANIC/FATAL/ERROR` red, `WARNING` amber, `NOTICE/HINT` yellow, `STATEMENT/DETAIL` dim | +| `pg_upgrade.conf` | One log per pg_upgrade run: `Upgrade Complete` = DONE, `Failure, exiting` = FAILED | +| `aurora-rds-downloaded.conf` | Logs pulled from Amazon RDS / Aurora with the AWS CLI | +| `batch-jobs.conf` | Migrations, backfills, deploys, ansible, cron: anything with "error / warn / done" | + +Use a preset for one run, or copy it into a folder so that folder always uses it: +```bash +tlogs -c examples/postgres-server.conf /var/log/postgresql +cp examples/pg_upgrade.conf /data/upgrade-logs/.tlogs.conf +``` + +--- + +## 4. Recipes + +**PostgreSQL server logs on a VM.** Logs are usually `/var/log/postgresql/` on Debian/Ubuntu, or `$PGDATA/log/` on RHEL-family systems. They're often readable only by the `postgres` user: +```bash +sudo -u postgres -i +tlogs -c ~/pg.conf "$PGDATA/log" +``` + +**Several pg_upgrade runs at once.** pg_upgrade prints its result to the terminal, so `tee` each run into its own file. Then watch the folder: +```bash +mkdir -p ~/upg && cd ~/upg && cp /path/to/tlogs/examples/pg_upgrade.conf .tlogs.conf +pg_upgrade ... 2>&1 | tee ~/upg/cluster-a.log & +pg_upgrade ... 2>&1 | tee ~/upg/cluster-b.log & +tlogs -rw +``` + +**EC2 through SSM Session Manager.** No SSH or open ports needed. +```bash +aws ssm start-session --target i-0123456789abcdef0 +bash -l # SSM starts you in sh; switch to bash +cd /var/log/myjobs && tlogs -rw +# connection dropped or idle timeout? start a new session, then: +tlogs ls && tlogs attach tlogs-myjobs-running +``` + +**EC2 over SSH.** Same idea; tmux survives the disconnect: +```bash +ssh ec2-user@host -t 'cd /var/log/myjobs && ~/.local/bin/tlogs -rw' +``` + +**Copying the script to a private instance.** Use option C above (paste), or one of these: +```bash +aws s3 cp tlogs s3://my-bucket/tools/tlogs # from your laptop +aws s3 cp s3://my-bucket/tools/tlogs ~/.local/bin/tlogs && chmod +x ~/.local/bin/tlogs # on the box +``` + +**Amazon RDS / Aurora logs.** You can't log in to the host, so download the logs and watch them locally: +```bash +mkdir -p ~/rds && cd ~/rds && cp /path/to/tlogs/examples/aurora-rds-downloaded.conf .tlogs.conf +for db in db-1 db-2 db-3; do + aws rds download-db-log-file-portion --db-instance-identifier "$db" \ + --log-file-name "$(aws rds describe-db-log-files --db-instance-identifier "$db" \ + --query 'DescribeDBLogFiles[-1].LogFileName' --output text)" \ + --starting-token 0 --output text > "$db.log" & +done; wait +tlogs +``` + +**Kubernetes pods.** Write each pod's logs to a file, then watch the folder: +```bash +mkdir -p ~/k && cd ~/k +for p in $(kubectl get pods -l app=myjob -o name); do kubectl logs -f "$p" > "${p#pod/}.log" & done +tlogs -w +``` + +**Just colour, no tmux.** +```bash +tail -f /var/log/postgresql/postgresql-16-main.log | tlogs color +``` + +--- + +## Older systems + +- **Amazon Linux 2 / CentOS 7** ship tmux 1.8. Amazon Linux 2 reached end of standard support on 30 June 2026, so the cleanest fix is moving the jumpbox to Amazon Linux 2023 (`dnf install tmux`). Other options: + - Run tlogs from any newer machine that can read the logs (over NFS, `aws s3 sync`, or downloaded with the AWS CLI). + - Build tmux 3.x from source. +- **Container-only hosts** (Bottlerocket, Flatcar): run tlogs inside a shell or admin container that has bash and tmux and can see the log folder. +- **No tmux at all?** `tlogs -l` (states) and `tlogs color` (colours) work without tmux. + +## Troubleshooting + +| Problem | Fix | +|---|---| +| `tmux 3.0+ needed` | Upgrade tmux (see the table above). | +| `no room for another pane` | Your terminal is too small for that many panes. Make the window bigger, or use `-r` / `-e` to open fewer. | +| No colours | Your terminal or `TERM` needs 256-colour support (most do). Check you haven't set `NO_COLOR` or `TL_NO_COLOR=1`. | +| Everything shows FAILED for server logs | Server logs contain `FATAL:` lines in normal operation. Use `postgres-server.conf`, which turns state checks off. | +| Session already exists | `tlogs attach NAME` to reuse it, or `tlogs kill NAME` and run again for a fresh list. | + +## Test + +```bash +bash tests/test.sh # 38 checks: colours, states, config safety, tmux panes, mouse scope, watch mode +``` +CI runs the same tests on Ubuntu and on macOS, including macOS's built-in bash 3.2. + +MIT licensed. diff --git a/tlogs/docs/demo.gif b/tlogs/docs/demo.gif new file mode 100644 index 0000000..a6ef249 Binary files /dev/null and b/tlogs/docs/demo.gif differ diff --git a/tlogs/examples/aurora-rds-downloaded.conf b/tlogs/examples/aurora-rds-downloaded.conf new file mode 100644 index 0000000..5b7e790 --- /dev/null +++ b/tlogs/examples/aurora-rds-downloaded.conf @@ -0,0 +1,14 @@ +# Logs downloaded from Amazon RDS / Aurora PostgreSQL, e.g.: +# aws rds download-db-log-file-portion --db-instance-identifier mydb \ +# --log-file-name error/postgresql.log.2026-10-12-10 --output text > mydb.log +# (one file per instance; re-run the download in a loop to keep it growing) +TL_GLOB='*.log' +TL_HIGHLIGHT=word +TL_RED_RE='PANIC:|FATAL:|ERROR:' +TL_AMBER_RE='WARNING:' +TL_YELLOW_RE='NOTICE:' +TL_GREEN_RE='database system is ready' +TL_DIM_RE='STATEMENT:|CONTEXT:|DETAIL:' +TL_OK_RE='' +TL_FAIL_RE='' +TL_WARN_RE='' diff --git a/tlogs/examples/batch-jobs.conf b/tlogs/examples/batch-jobs.conf new file mode 100644 index 0000000..a5aa188 --- /dev/null +++ b/tlogs/examples/batch-jobs.conf @@ -0,0 +1,12 @@ +# Any script/job that writes one log per run (migrations, backfills, deploys, ansible, cron). +# Make your jobs print a clear last line - tlogs only needs that. +TL_GLOB='*.log *.out' +TL_ICASE=1 +TL_RED_RE='error|exception|traceback|failed|fatal' +TL_AMBER_RE='warn|retry|timeout' +TL_YELLOW_RE='notice|skipp' +TL_GREEN_RE='success|completed|done' +TL_DIM_RE='debug' +TL_OK_RE='job (finished|completed)|exit(ed)? (code|status)[ :=]*0$' +TL_FAIL_RE='job failed|aborted|exit(ed)? (code|status)[ :=]*[1-9]' +TL_WARN_RE='warn' diff --git a/tlogs/examples/pg_upgrade.conf b/tlogs/examples/pg_upgrade.conf new file mode 100644 index 0000000..f4205ca --- /dev/null +++ b/tlogs/examples/pg_upgrade.conf @@ -0,0 +1,12 @@ +# pg_upgrade / pg_upgradecluster runs: one log per cluster being upgraded. +# pg_upgrade prints "Upgrade Complete" on success and "Failure, exiting" on failure. +TL_GLOB='*.log *.txt' +TL_RED_RE='Failure, exiting|fatal|FATAL|ERROR|could not' +TL_AMBER_RE='WARNING|warning' +TL_YELLOW_RE='NOTICE|Consult the last few lines' +TL_GREEN_RE='Upgrade Complete| ok$' +TL_DIM_RE='' +TL_OK_RE='Upgrade Complete' +TL_FAIL_RE='Failure, exiting' +TL_WARN_RE='WARNING|warning' +TL_TAIL_LINES=15 diff --git a/tlogs/examples/postgres-server.conf b/tlogs/examples/postgres-server.conf new file mode 100644 index 0000000..32d118d --- /dev/null +++ b/tlogs/examples/postgres-server.conf @@ -0,0 +1,14 @@ +# PostgreSQL server logs (postgresql-*.log, log_line_prefix of any shape). +# Server logs never "finish", so state checks are off: every log shows as RUNNING. +TL_GLOB='*.log *.csv *.json' +TL_HIGHLIGHT=word +# stderr / csvlog / jsonlog formats all covered +TL_RED_RE='PANIC:|FATAL:|ERROR:|,(PANIC|FATAL|ERROR),|"error_severity":"(PANIC|FATAL|ERROR)"' +TL_AMBER_RE='WARNING:|,WARNING,|"error_severity":"WARNING"' +TL_YELLOW_RE='NOTICE:|HINT:|,NOTICE,|"error_severity":"NOTICE"' +TL_GREEN_RE='database system is ready to accept connections|checkpoint complete' +TL_BLUE_RE='LOG: duration:|LOG: process [0-9]+ (still waiting|acquired)|deadlock' +TL_DIM_RE='DEBUG[1-5]?:|STATEMENT:|CONTEXT:|DETAIL:' +TL_OK_RE='' +TL_FAIL_RE='' +TL_WARN_RE='' diff --git a/tlogs/install.sh b/tlogs/install.sh new file mode 100755 index 0000000..4a7048d --- /dev/null +++ b/tlogs/install.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# install.sh - installs tlogs for the current user (no sudo needed). +# bash install.sh -> ~/.local/bin/tlogs +# PREFIX=/usr/local bash install.sh (needs write access there) +# Never overwrites silently: an existing different tlogs is kept as tlogs.bak.. +set -eu +here=$(cd "$(dirname "$0")" && pwd) +src="$here/tlogs" +[ -f "$src" ] || { echo "run this from the tlogs folder (tlogs script not found next to install.sh)"; exit 1; } +bin="${PREFIX:-$HOME/.local}/bin" +mkdir -p "$bin" +if [ -e "$bin/tlogs" ] && ! cmp -s "$src" "$bin/tlogs"; then + bak="$bin/tlogs.bak.$(date +%Y%m%d%H%M%S)"; cp -p "$bin/tlogs" "$bak"; echo "kept previous version: $bak" +fi +cp "$src" "$bin/tlogs.new" && chmod 755 "$bin/tlogs.new" && mv "$bin/tlogs.new" "$bin/tlogs" +echo "installed: $bin/tlogs ($("$bin/tlogs" version))" +# checks, no changes +command -v tmux >/dev/null 2>&1 && echo "tmux: $(tmux -V)" || echo "tmux: NOT FOUND - install it (see README: Install tmux)" +case ":$PATH:" in *":$bin:"*) ;; *) echo "note: $bin is not on your PATH. Add this to ~/.bashrc or ~/.zshrc:"; echo " export PATH=\"$bin:\$PATH\"" ;; esac +"$bin/tlogs" init +echo "done. try: cd /path/to/logs && tlogs -l" diff --git a/tlogs/tests/test.sh b/tlogs/tests/test.sh new file mode 100644 index 0000000..f0b9c11 --- /dev/null +++ b/tlogs/tests/test.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# tests/test.sh - run: bash tests/test.sh (SH=/bin/bash bash tests/test.sh to pick the shell under test) +# Uses a private tmux socket and a temp folder; touches nothing else. +set -u +ROOT=$(cd "$(dirname "$0")/.." && pwd); SH="${SH:-bash}"; T="$ROOT/tlogs" +W=$(mktemp -d "${TMPDIR:-/tmp}/tlogs-test.XXXXXX"); cd "$W" || exit 1 +export TL_NO_ATTACH=1 TMUX_TMPDIR="$W" XDG_CONFIG_HOME="$W/cfg" HOME="$W"; unset TMUX +pass=0; fail=0 +ok() { pass=$((pass+1)); echo "ok $1"; } +bad() { fail=$((fail+1)); echo "FAIL $1"; [ -n "${2:-}" ] && printf ' %s\n' "$2"; } +check() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected [$3] got [$2]"; fi; } +ESC=$(printf '\033') +echo "shell: $("$SH" -c 'echo $BASH_VERSION') tmux: $(tmux -V 2>/dev/null || echo none)" + +# --- colours (postgres levels) +c() { printf '%s\n' "$1" | "$SH" "$T" color; } +check "ERROR red" "$(c '2026-10-12 10:00:03 UTC [1]: ERROR: boom')" "${ESC}[1;31m2026-10-12 10:00:03 UTC [1]: ERROR: boom${ESC}[0m" +check "FATAL red" "$(c 'x FATAL: y' | cut -c1-8)" "${ESC}[1;31mx" +check "WARNING amber" "$(c 'x WARNING: y')" "${ESC}[38;5;214mx WARNING: y${ESC}[0m" +check "NOTICE yellow" "$(c 'x NOTICE: y')" "${ESC}[33mx NOTICE: y${ESC}[0m" +check "LOG plain" "$(c 'x LOG: checkpoint starting')" "x LOG: checkpoint starting" +check "pg_upgrade ok" "$(c 'Upgrade Complete')" "${ESC}[32mUpgrade Complete${ESC}[0m" +check "word highlight" "$(printf 'a ERROR: b\n' | TL_HIGHLIGHT=word "$SH" "$T" color)" "a ${ESC}[1;31mERROR:${ESC}[0m b" +check "user rule" "$(printf 'disk 91%%\n' | TL_RED_RE='disk 9[0-9]%' "$SH" "$T" color)" "${ESC}[1;31mdisk 91%${ESC}[0m" +check "rule off" "$(printf 'x ERROR: y\n' | TL_RED_RE='' "$SH" "$T" color)" "x ERROR: y" +check "icase" "$(printf 'oops error\n' | TL_ICASE=1 TL_RED_RE='ERROR' "$SH" "$T" color)" "${ESC}[1;31moops error${ESC}[0m" +check "NO_COLOR" "$(printf 'x ERROR: y\n' | NO_COLOR=1 "$SH" "$T" color)" "x ERROR: y" +check "special chars" "$(printf 'a & b \\ c ERROR: d\n' | TL_HIGHLIGHT=word "$SH" "$T" color)" "a & b \\ c ${ESC}[1;31mERROR:${ESC}[0m d" + +# --- states +printf 'Checking ok\nUpgrade Complete\n' > a-ok.log +printf 'WARNING: x\nUpgrade Complete\n' > b-warn.log +printf 'check fatal\nFailure, exiting\n' > c-fail.log +printf 'Copying files\n' > d-run.log +printf 'name with space\n' > 'e run.log' +out=$("$SH" "$T" -l | sed "s/${ESC}\[[0-9;]*m//g") +check "list" "$(printf '%s\n' "$out" | awk '{print $1}' | tr '\n' ' ')" "DONE WARN FAILED RUNNING RUNNING running: " +check "counts" "$(printf '%s\n' "$out" | tail -1)" "running: 2 done: 1 warn: 1 failed: 1 (of 5)" + +# --- config file: parsed, never executed; env wins over file +printf "TL_GLOB='*.txt'\nTL_RED_RE=\$(touch PWNED)\nEVIL=\$(touch PWNED2)\nexport TL_DONE_GRACE=7\n" > .tlogs.conf +cfg=$("$SH" "$T" config 2>/dev/null) +check "no exec" "$(ls PWNED PWNED2 2>/dev/null | wc -l | tr -d ' ')" "0" +check "file value" "$(printf '%s\n' "$cfg" | grep '^TL_GLOB=')" "TL_GLOB=*.txt" +check "export form" "$(printf '%s\n' "$cfg" | grep '^TL_DONE_GRACE=')" "TL_DONE_GRACE=7" +check "env wins" "$(TL_GLOB='*.log' "$SH" "$T" config 2>/dev/null | grep '^TL_GLOB=')" "TL_GLOB=*.log" +rm -f .tlogs.conf +"$SH" "$T" init >/dev/null; [ -s "$W/cfg/tlogs/config" ] && ok "init writes config" || bad "init writes config" +cp "$W/cfg/tlogs/config" k; "$SH" "$T" init >/dev/null; cmp -s k "$W/cfg/tlogs/config" && ok "init never overwrites" || bad "init never overwrites" +a=$("$SH" "$T" config); rm -rf "$W/cfg"; check "init config round-trips" "$a" "$("$SH" "$T" config)" + +# --- tmux +if command -v tmux >/dev/null 2>&1; then + tmux new-session -d -s other 'sleep 120' # an unrelated session, started first + g0=$(tmux show -g -v mouse) # global value before tlogs (may be on via a system tmux.conf) + "$SH" "$T" -n s1 >/dev/null 2>&1 + check "one pane per log" "$(tmux list-panes -t s1:logs | wc -l | tr -d ' ')" "5" + check "pane state marks" "$(tmux list-panes -t s1:logs -F '#{@st}' | sort | tr '\n' ' ')" "DONE FAILED RUNNING RUNNING WARN " + check "mouse on in tlogs session" "$(tmux show -t s1 -v mouse)" "on" + check "other sessions untouched" "$(tmux show -t other mouse)" "" + check "global mouse unchanged" "$(tmux show -g -v mouse)" "$g0" + TL_MOUSE=0 "$SH" "$T" -n s4 >/dev/null 2>&1 + check "TL_MOUSE=0 keeps it off" "$(tmux show -t s4 -v mouse)" "off" + "$SH" "$T" -e -n s2 >/dev/null 2>&1 + check "-e issues only" "$(tmux list-panes -t s2:logs -F '#{@tl_file}' | sort | tr '\n' ' ')" "b-warn.log c-fail.log " + TL_WATCH_SEC=1 TL_DONE_GRACE=1 "$SH" "$T" -rw -n s3 >/dev/null 2>&1; s3name=s3 + check "watch pane titled" "$(tmux list-panes -t s3:tl-watch -F '#{pane_title}')" "tl-watch" + check "full session name in status" "$(tmux show -t s3 -v status-left-length)" "$(( ${#s3name} + 4 ))" + check "-r running only" "$(tmux list-panes -t s3:logs | wc -l | tr -d ' ')" "2" + printf 'started\n' > f-new.log; sleep 3 + check "-w adds new log" "$(tmux list-panes -t s3:logs -F '#{@tl_file}' | grep -c f-new.log)" "1" + printf 'Upgrade Complete\n' >> d-run.log; sleep 5 + check "-w closes DONE" "$(tmux list-panes -t s3:logs -F '#{@tl_file}' | grep -c d-run.log)" "0" + check "-w keeps others" "$(tmux list-panes -t s3:logs | wc -l | tr -d ' ')" "2" + sleep 1; fp=$(tmux list-panes -t s1:logs -F '#{pane_id} #{@tl_file}' | awk '$2=="c-fail.log"{print $1}') + tmux capture-pane -p -e -t "$fp" | grep -q "31mFailure, exiting" && ok "pane lines coloured" || bad "pane lines coloured" + printf 'n\n' | "$SH" "$T" kill s1 >/dev/null 2>&1; tmux has-session -t s1 2>/dev/null && ok "kill asks first" || bad "kill asks first" + printf 'y\ns1\n' | "$SH" "$T" kill s1 >/dev/null 2>&1; tmux has-session -t s1 2>/dev/null && bad "kill after 2 confirmations" || ok "kill after 2 confirmations" + [ -f a-ok.log ] && ok "logs untouched" || bad "logs untouched" + tmux kill-server 2>/dev/null +else echo "skip tmux tests (tmux not installed)"; fi + +cd / && rm -rf "$W" +echo "passed: $pass failed: $fail"; [ "$fail" = 0 ] diff --git a/tlogs/tlogs b/tlogs/tlogs new file mode 100755 index 0000000..4543149 --- /dev/null +++ b/tlogs/tlogs @@ -0,0 +1,410 @@ +#!/usr/bin/env bash +# tlogs - watch a folder of log files in tmux: one pane per log, coloured lines, +# live state per log (RUNNING / DONE / WARN / FAILED). +# Needs: bash 3.2+, tmux 3.0+, tail, grep. Works on macOS, Linux, WSL, EC2. +# Docs: tlogs help License: MIT +TL_VERSION=2.1.2 + +# ---------------------------------------------------------------- settings --- +# Every setting can come from (highest wins): +# 1. environment variable TL_RED_RE='ERROR' tlogs +# 2. -c FILE tlogs -c ~/pg.conf +# 3. .tlogs.conf in the log folder +# 4. ~/.config/tlogs/config (tlogs init writes a commented one) +# 5. the defaults below (tuned for PostgreSQL server logs and pg_upgrade) +TL_KEYS="TL_GLOB TL_PREFIX TL_HISTORY TL_ICASE TL_HIGHLIGHT TL_NO_COLOR +TL_RED_RE TL_AMBER_RE TL_YELLOW_RE TL_GREEN_RE TL_BLUE_RE TL_DIM_RE +TL_OK_RE TL_WARN_RE TL_FAIL_RE TL_TAIL_LINES TL_WATCH_SEC TL_DONE_GRACE TL_KEEP_DONE TL_MOUSE" + +tl_defaults() { + : "${TL_GLOB:=*.log}" # which files; space-separated globs, e.g. '*.log *.out' + : "${TL_PREFIX:=}" # common prefix trimmed from pane labels + : "${TL_HISTORY:=50}" # lines of history each pane starts with + : "${TL_ICASE:=0}" # 1 = all patterns are case-insensitive + : "${TL_HIGHLIGHT:=line}" # line = colour the whole line, word = colour only the match + : "${TL_NO_COLOR:=${NO_COLOR:+1}}"; : "${TL_NO_COLOR:=0}" + # line colours: extended regex; first match wins in this order. Empty = rule off. + : "${TL_RED_RE=PANIC:|FATAL:|ERROR:|Failure, exiting|[Ee]xception|Traceback|[Aa]borted|FAILED}" + : "${TL_AMBER_RE=WARNING:|WARN}" + : "${TL_YELLOW_RE=NOTICE:|HINT:}" + : "${TL_GREEN_RE=Upgrade Complete|completed successfully|finished successfully|SUCCESS}" + : "${TL_BLUE_RE=}" + : "${TL_DIM_RE=DEBUG[1-5]?:|STATEMENT:|CONTEXT:}" + # log state, from the last TL_TAIL_LINES lines (only meaningful for logs that end) + : "${TL_OK_RE=Upgrade Complete|completed successfully|finished successfully}" + : "${TL_FAIL_RE=Failure, exiting|PANIC:|FATAL:|[Aa]borted|Traceback}" + : "${TL_WARN_RE=WARNING:}" # searched in the whole log, only once it is OK -> WARN + : "${TL_TAIL_LINES:=10}" + : "${TL_WATCH_SEC:=15}" # -w: how often to look for new / finished logs + : "${TL_DONE_GRACE:=60}" # -w: seconds a DONE pane stays before it closes + : "${TL_KEEP_DONE:=0}" # -w: 1 = never close panes + : "${TL_MOUSE:=1}" # 1 = mouse on in tlogs sessions only (click a pane, scroll); 0 = keyboard only +} + +# Config files are parsed, never executed: only KEY=VALUE lines with known TL_ keys. +tl_load() { + local file="$1" line k v + [ -f "$file" ] && [ -r "$file" ] || return 0 + while IFS= read -r line || [ -n "$line" ]; do + line="${line#"${line%%[![:space:]]*}"}" # trim leading space + case "$line" in ''|'#'*) continue ;; esac + line="${line#export }" + k="${line%%=*}"; v="${line#*=}" + [ "$k" != "$line" ] || continue + case " $(echo $TL_KEYS) " in *" $k "*) ;; *) echo "tlogs: ignoring unknown key '$k' in $file" >&2; continue ;; esac + case " $TL_ENV_KEYS " in *" $k "*) continue ;; esac # environment wins + v="${v%"${v##*[![:space:]]}"}" # trim trailing space + if [ ${#v} -ge 2 ]; then + case "$v" in \'*\') v="${v:1:${#v}-2}" ;; \"*\") v="${v:1:${#v}-2}" ;; esac + fi + printf -v "$k" '%s' "$v" + done < "$file" +} + +tl_config() { # tl_config [explicit-file] + TL_ENV_KEYS="" + local k; for k in $TL_KEYS; do [ -n "${!k+x}" ] && TL_ENV_KEYS="$TL_ENV_KEYS $k"; done + # later files override earlier ones, so load lowest priority first + tl_load "${XDG_CONFIG_HOME:-$HOME/.config}/tlogs/config" + tl_load "./.tlogs.conf" + [ -n "${1:-}" ] && tl_load "$1" + tl_defaults +} + +tl_dump() { local k; for k in $TL_KEYS; do printf '%s=%s\n' "$k" "${!k}"; done; } + +# ---------------------------------------------------------------- helpers --- +C_RED=$'\033[1;31m'; C_AMBER=$'\033[38;5;214m'; C_YELLOW=$'\033[33m'; C_GREEN=$'\033[32m' +C_BLUE=$'\033[36m'; C_DIM=$'\033[2m'; C_OFF=$'\033[0m' + +die() { echo "tlogs: $*" >&2; exit 1; } + +tl_self() { # absolute path of this script, for the commands tmux runs + case "$0" in /*) printf '%s' "$0" ;; */*) printf '%s/%s' "$(cd "${0%/*}" && pwd)" "${0##*/}" ;; *) command -v "$0" ;; esac +} + +tl_need_tmux() { + command -v tmux >/dev/null 2>&1 || die "tmux not found - install it first (see: tlogs help)" + local v; v=$(tmux -V 2>/dev/null); v=${v#* }; v=${v%%[!0-9.]*} + [ "${v%%.*}" -ge 3 ] 2>/dev/null || die "tmux 3.0+ needed (found ${v:-unknown}) - see 'Older systems' in the README" +} + +tl_grep() { # tl_grep REGEX (stdin) - honours TL_ICASE, empty regex never matches + [ -n "$1" ] || return 1 + if [ "$TL_ICASE" = 1 ]; then grep -Eqi -- "$1"; else grep -Eq -- "$1"; fi +} + +# state of one log: DONE | WARN | FAILED | RUNNING +tl_state() { + local f="$1" t + t=$(tail -n "$TL_TAIL_LINES" "$f" 2>/dev/null) + if printf '%s\n' "$t" | tl_grep "$TL_OK_RE"; then + if tl_grep "$TL_WARN_RE" < "$f"; then echo WARN; else echo DONE; fi + elif printf '%s\n' "$t" | tl_grep "$TL_FAIL_RE"; then echo FAILED + else echo RUNNING; fi +} + +tl_files() { # prints matching files, one per line, sorted, unique + local g f seen=$'\n' + local ng; ng=$(shopt -p nullglob); shopt -s nullglob + local globs; set -f # split the pattern list without expanding it yet + # shellcheck disable=SC2206 + globs=($TL_GLOB); set +f + for g in "${globs[@]}"; do + for f in $g; do + [ -f "$f" ] || continue + case "$seen" in *$'\n'"$f"$'\n'*) continue ;; esac + seen="$seen$f"$'\n'; printf '%s\n' "$f" + done + done | LC_ALL=C sort + eval "$ng" +} + +tl_label() { printf '%s' "${1#"$TL_PREFIX"}"; } + +# colour stdin line by line using the TL_*_RE rules (pure bash, unbuffered) +tl_colorize() { + local line c m pre post + if [ "$TL_NO_COLOR" = 1 ]; then cat; return; fi + [ "$TL_ICASE" = 1 ] && shopt -s nocasematch + while IFS= read -r line || [ -n "$line" ]; do + c="" + if [ -n "$TL_RED_RE" ] && [[ $line =~ $TL_RED_RE ]]; then c=$C_RED + elif [ -n "$TL_AMBER_RE" ] && [[ $line =~ $TL_AMBER_RE ]]; then c=$C_AMBER + elif [ -n "$TL_YELLOW_RE" ] && [[ $line =~ $TL_YELLOW_RE ]]; then c=$C_YELLOW + elif [ -n "$TL_GREEN_RE" ] && [[ $line =~ $TL_GREEN_RE ]]; then c=$C_GREEN + elif [ -n "$TL_BLUE_RE" ] && [[ $line =~ $TL_BLUE_RE ]]; then c=$C_BLUE + elif [ -n "$TL_DIM_RE" ] && [[ $line =~ $TL_DIM_RE ]]; then c=$C_DIM + fi + if [ -z "$c" ]; then printf '%s\n' "$line" + elif [ "$TL_HIGHLIGHT" = word ] && [ -n "${BASH_REMATCH[0]}" ]; then + m=${BASH_REMATCH[0]}; pre=${line%%"$m"*}; post=${line#*"$m"} + printf '%s%s%s%s%s\n' "$pre" "$c" "$m" "$C_OFF" "$post" + else printf '%s%s%s\n' "$c" "$line" "$C_OFF"; fi + done +} + +# ------------------------------------------------------------ tmux panes --- +TL_FMT='#{?#{==:#{@st},FAILED},#[bg=red#,fg=white#,bold],#{?#{==:#{@st},WARN},#[bg=colour214#,fg=black#,bold],#{?#{==:#{@st},DONE},#[bg=green#,fg=black#,bold],#[bg=blue#,fg=white#,bold]}}} #{?pane_active,> ,}#{pane_index}: #{pane_title}#{?#{@st}, [#{@st}],} #[default]' + +tl_pane_cmd() { # command a pane runs for one file + printf 'exec %q _pane %q %q' "$TL_SELF" "$TL_SESSION_CONF" "$1" +} + +tl_mark() { tmux set -p -t "$1" @st "$2" >/dev/null 2>&1; tmux set -p -t "$1" @tl_file "$3" >/dev/null 2>&1; } + +tl_attach() { + local s="$1" + if [ -n "${TMUX:-}" ]; then tmux switch-client -t "=$s" + elif [ -t 0 ] && [ -t 1 ] && [ "${TL_NO_ATTACH:-0}" != 1 ]; then tmux attach -t "=$s" + else echo "session '$s' is ready: tmux attach -t '$s'"; fi +} + +usage() { + cat <) + + tlogs color [FILE] colour a file (follows it) or stdin: tail -f x.log | tlogs color + tlogs ls list tmux sessions + tlogs attach NAME re-attach to a session + tlogs kill NAME close a session (asks twice; log files are never touched) + tlogs init write a commented config to ~/.config/tlogs/config + tlogs config show the settings in effect here + tlogs version + +Pane labels: blue running, green DONE, amber WARN, red FAILED; '>' marks the pane you are on. +In tmux: Ctrl-b z zoom a pane (again to unzoom), Ctrl-b d detach, Ctrl-b arrows move. +Mouse (TL_MOUSE=1): click a pane, scroll to read back, drag borders, right-click for a menu. +To copy text with the mouse on: hold Option (iTerm2) or Fn (Terminal.app) while dragging. +EOF +} + +tl_main() { + local mode=all watch=0 conf="" name="" dir="" + while [ $# -gt 0 ]; do + case "$1" in + -r|--running) mode=running ;; + -e|--issues) mode=issues ;; + -w|--watch) watch=1 ;; + -rw|-wr) mode=running; watch=1 ;; + -ew|-we) mode=issues; watch=1 ;; + -l|--list) mode=list ;; + -g|--glob) shift; [ $# -gt 0 ] || die "-g needs a value"; TL_GLOB="$1" ;; + -c|--config) shift; [ $# -gt 0 ] || die "-c needs a file"; [ -f "$1" ] || die "no such config: $1"; conf="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")" ;; + -n|--name) shift; [ $# -gt 0 ] || die "-n needs a name"; name="$1" ;; + -h|--help) tl_config; usage; exit 0 ;; + -*) die "unknown option: $1 (see: tlogs help)" ;; + *) [ -z "$dir" ] || die "only one folder at a time"; dir="$1" ;; + esac; shift + done + if [ -n "$dir" ]; then cd "$dir" || die "cannot open folder: $dir"; fi + tl_config "$conf" + + local files=() f st n_run=0 n_ok=0 n_warn=0 n_fail=0 total=0 col + while IFS= read -r f; do + [ -n "$f" ] || continue; total=$((total+1)) + st=$(tl_state "$f") + case "$st" in RUNNING) n_run=$((n_run+1)) ;; DONE) n_ok=$((n_ok+1)) ;; WARN) n_warn=$((n_warn+1)) ;; FAILED) n_fail=$((n_fail+1)) ;; esac + if [ "$mode" = list ]; then + case "$st" in RUNNING) col=$C_BLUE ;; DONE) col=$C_GREEN ;; WARN) col=$C_AMBER ;; FAILED) col=$C_RED ;; esac + [ "$TL_NO_COLOR" = 1 ] || [ ! -t 1 ] && col="" + printf '%s%-8s%s %s\n' "$col" "$st" "${col:+$C_OFF}" "$(tl_label "$f")" + fi + case "$mode:$st" in all:*|running:RUNNING|issues:FAILED|issues:WARN) files+=("$f") ;; esac + done < <(tl_files) + [ "$total" -gt 0 ] || [ "$watch" = 1 ] || die "no files matching '$TL_GLOB' in $PWD" + echo "running: $n_run done: $n_ok warn: $n_warn failed: $n_fail (of $total)" + [ "$mode" = list ] && exit 0 + + tl_need_tmux + if [ ${#files[@]} -eq 0 ] && [ "$watch" = 0 ]; then + [ "$mode" = issues ] && echo "nothing FAILED or WARN here" || echo "nothing running here"; exit 0 + fi + local s="${name:-tlogs-${PWD##*/}}" + [ -z "$name" ] && case "$mode" in running) s="$s-running" ;; issues) s="$s-issues" ;; esac + s=$(printf '%s' "$s" | tr -c 'A-Za-z0-9_-' '_') + if tmux has-session -t "=$s" 2>/dev/null; then + echo "session '$s' already exists - attaching (to rebuild it: tlogs kill $s, then run again)"; tl_attach "$s"; exit 0 + fi + + # snapshot of the settings for the panes and the watcher + TL_SELF=$(tl_self) + local rt="${TMPDIR:-/tmp}"; rt="${rt%/}/tlogs-$(id -u)" + mkdir -p "$rt" && chmod 700 "$rt" || die "cannot create $rt" + TL_SESSION_CONF="$rt/$s.conf"; tl_dump > "$TL_SESSION_CONF" + + local cols lines pid first=1 + cols=$(tput cols 2>/dev/null || echo 200); lines=$(tput lines 2>/dev/null || echo 50) + if [ ${#files[@]} -eq 0 ]; then + pid=$(tmux new-session -d -P -F '#{pane_id}' -s "$s" -x "$cols" -y "$lines" -c "$PWD" \ + "echo 'tl-waiting: no matching logs yet in $PWD - new ones will appear here'; exec tail -f /dev/null") || die "could not start tmux" + tmux select-pane -t "$pid" -T "waiting for new logs"; tmux set -p -t "$pid" @tl_wait 1; first=0 + fi + for f in "${files[@]}"; do + if [ $first = 1 ]; then + pid=$(tmux new-session -d -P -F '#{pane_id}' -s "$s" -x "$cols" -y "$lines" -c "$PWD" "$(tl_pane_cmd "$f")") || die "could not start tmux"; first=0 + else + pid=$(tmux split-window -P -F '#{pane_id}' -t "=$s:" -c "$PWD" "$(tl_pane_cmd "$f")") || { echo "no room for another pane: $f (make the terminal bigger, or use -r / -e)"; continue; } + tmux select-layout -t "=$s:" tiled >/dev/null + fi + tmux select-pane -t "$pid" -T "$(tl_label "$f")"; tl_mark "$pid" "$(tl_state "$f")" "$f" + done + tmux rename-window -t "=$s:" logs >/dev/null 2>&1 + tmux set -w -t "=$s:" automatic-rename off >/dev/null 2>&1 + tmux set -w -t "=$s:" pane-border-status top >/dev/null + tmux set -w -t "=$s:" pane-border-format "$TL_FMT" >/dev/null + tmux set -w -t "=$s:" remain-on-exit off >/dev/null + # mouse: session option, so other tmux sessions and ~/.tmux.conf are not affected + tmux set -t "=$s:" status-left-length $(( ${#s} + 4 )) >/dev/null # show the full session name + if [ "$TL_MOUSE" = 1 ]; then tmux set -t "=$s:" mouse on >/dev/null; else tmux set -t "=$s:" mouse off >/dev/null; fi + if [ "$watch" = 1 ]; then + local wid; wid=$(tmux display -p -t "=$s:" '#{window_id}') + local wpid + wpid=$(tmux new-window -d -P -F '#{pane_id}' -t "=$s:" -n tl-watch -c "$PWD" \ + "$(printf 'exec %q _watch %q %q %q' "$TL_SELF" "$TL_SESSION_CONF" "$wid" "$mode")") \ + && tmux select-pane -t "$wpid" -T tl-watch \ + && echo "watching every ${TL_WATCH_SEC}s - window 'tl-watch' (Ctrl-b n) shows what changed" + fi + echo "session '$s': ${#files[@]} panes" + tl_attach "$s" +} + +# runs inside each pane +tl_pane() { + tl_load "$1"; tl_defaults + tail -n "$TL_HISTORY" -F "$2" 2>/dev/null | tl_colorize +} + +# runs in the tl-watch window for -w +tl_watch() { + tl_load "$1"; tl_defaults; TL_SESSION_CONF="$1"; TL_SELF=$(tl_self) + local wid="$2" mode="$3" f have pid act st now n flist done_at=" " entry since + echo "tl-watch: $PWD every ${TL_WATCH_SEC}s (mode: $mode). Stops when the session closes." + [ "$TL_KEEP_DONE" = 1 ] || echo "tl-watch: DONE panes close ${TL_DONE_GRACE}s after finishing; FAILED and WARN stay." + while tmux list-panes -t "$wid" >/dev/null 2>&1; do + sleep "$TL_WATCH_SEC" + have=$(tmux list-panes -t "$wid" -F '#{@tl_file}' 2>/dev/null) || break + have=$'\n'"$have"$'\n' + # 1. new logs + flist=$(tl_files) + while IFS= read -r f; do + [ -n "$f" ] || continue + case "$have" in *$'\n'"$f"$'\n'*) continue ;; esac + st=$(tl_state "$f") + case "$mode:$st" in all:*|running:RUNNING|issues:FAILED|issues:WARN) ;; *) continue ;; esac + act=$(tmux display -p -t "$wid" '#{pane_id}') + pid=$(tmux split-window -d -P -F '#{pane_id}' -t "$wid" -c "$PWD" "$(tl_pane_cmd "$f")" 2>/dev/null) \ + || { echo "$(date +%T) no room for $f"; continue; } + tmux select-layout -t "$wid" tiled >/dev/null + tmux select-pane -t "$pid" -T "$(tl_label "$f")"; tmux select-pane -t "$act"; tl_mark "$pid" "$st" "$f" + have="$have$f"$'\n'; echo "$(date +%T) added $f" + done </dev/null | wc -l) )) + [ "$n" -gt 1 ] && tmux kill-pane -t "$pid" && tmux select-layout -t "$wid" tiled >/dev/null + continue + fi + [ -n "$f" ] && [ -e "$f" ] || continue + st=$(tl_state "$f"); tmux set -p -t "$pid" @st "$st" >/dev/null 2>&1 + [ "$TL_KEEP_DONE" = 1 ] && continue + entry=" $pid:" + if [ "$st" != DONE ]; then done_at=$(printf '%s' "$done_at" | sed "s/ $pid:[0-9]*//"); continue; fi + case "$done_at" in *"$entry"*) ;; *) done_at="$done_at$pid:$now "; continue ;; esac + since=${done_at#*"$entry"}; since=${since%% *} + [ $((now - since)) -ge "$TL_DONE_GRACE" ] || continue + n=$(( $(tmux list-panes -t "$wid" 2>/dev/null | wc -l) )); [ "$n" -gt 1 ] || continue + tmux kill-pane -t "$pid" && tmux select-layout -t "$wid" tiled >/dev/null + done_at=$(printf '%s' "$done_at" | sed "s/ $pid:[0-9]*//") + echo "$(date +%T) closed $f (DONE)" + done </dev/null) +EOF + done +} + +tl_kill() { + local s="$1" a + [ -n "$s" ] || { echo "usage: tlogs kill NAME"; tmux ls 2>/dev/null; exit 1; } + tmux has-session -t "=$s" 2>/dev/null || die "no session named exactly '$s'" + echo "Session '$s':"; tmux list-panes -s -t "=$s" -F ' #{pane_index}: #{pane_title}' + read -r -p "1/2 Close session '$s'? Log files are NOT touched. (y/N): " a; [ "$a" = y ] || { echo aborted; exit 1; } + read -r -p "2/2 Type the session name to confirm: " a; [ "$a" = "$s" ] || { echo "name mismatch - aborted"; exit 1; } + tmux kill-session -t "=$s" && echo "closed '$s'" + rm -f "${TMPDIR:-/tmp}/tlogs-$(id -u)/$s.conf" 2>/dev/null +} + +tl_init() { + local d="${XDG_CONFIG_HOME:-$HOME/.config}/tlogs" f + f="$d/config" + if [ -e "$f" ]; then echo "$f already exists - left unchanged (edit it, or delete it and run tlogs init again)"; return 0; fi + mkdir -p "$d" || die "cannot create $d" + ( unset $TL_KEYS; tl_defaults; cat < "$f" && echo "wrote $f" +} + +# ---------------------------------------------------------------- dispatch --- +case "${1:-}" in + _pane) shift; tl_pane "$@" ;; + _watch) shift; tl_watch "$@" ;; + color|colour) + shift; tl_config + if [ -n "${1:-}" ]; then tail -n "$TL_HISTORY" -F "$1" | tl_colorize; else tl_colorize; fi ;; + ls) tmux ls 2>/dev/null || echo "no tmux sessions" ;; + attach) shift; [ -n "${1:-}" ] || { tmux ls 2>/dev/null; die "usage: tlogs attach NAME"; } + tmux has-session -t "=$1" 2>/dev/null || die "no session named exactly '$1'"; tl_attach "$1" ;; + kill) shift; tl_kill "${1:-}" ;; + init) tl_init ;; + config) shift; tl_config "${1:-}"; tl_dump ;; + version|--version) echo "tlogs $TL_VERSION" ;; + help) tl_config; usage ;; + *) tl_main "$@" ;; +esac