logguard-cli 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Apurva Raj
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,215 @@
1
+ Metadata-Version: 2.4
2
+ Name: logguard-cli
3
+ Version: 0.1.0
4
+ Summary: A 100% local, offline CLI tool that scans log files and masks sensitive data (emails, phone numbers, API keys, IPs, credit cards) before you share them.
5
+ Author: Apurva Raj
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/apurvaraj9/log-guard
8
+ Project-URL: Repository, https://github.com/apurvaraj9/log-guard
9
+ Project-URL: Issues, https://github.com/apurvaraj9/log-guard/issues
10
+ Keywords: logs,logging,masking,redaction,privacy,security,pii,sensitive-data,cli,pre-commit
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: System :: Logging
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Dynamic: license-file
29
+
30
+ # ๐Ÿ›ก๏ธ Log Guard
31
+
32
+ [![Tests](https://github.com/apurvaraj9/log-guard/actions/workflows/tests.yml/badge.svg)](https://github.com/apurvaraj9/log-guard/actions/workflows/tests.yml)
33
+
34
+ **A local, offline tool that scans server log files and masks sensitive data before you share them for debugging.**
35
+
36
+ No uploads. No third-party servers. No enterprise pricing. Your logs never leave your machine.
37
+
38
+ ---
39
+
40
+ ## Why Log Guard?
41
+
42
+ When you're debugging with a teammate, posting to a forum, or filing a support ticket, you often need to share a log file โ€” but real logs are full of things you *shouldn't* share: customer emails, phone numbers, API keys, IP addresses, credit card numbers.
43
+
44
+ - **Online masking tools** require uploading your private logs to a third-party server โ€” a privacy risk in itself.
45
+ - **Enterprise security tools** solve this, but are expensive, complex, and overkill for an individual developer or small team.
46
+
47
+ **Log Guard** runs 100% locally, does one job well, and stays simple.
48
+
49
+ ## Features
50
+
51
+ - ๐Ÿ” **Detects and masks:** emails, phone numbers, API keys (Stripe/AWS/GitHub formats + a generic long-token fallback), IP addresses, and credit card numbers (Visa/Mastercard/Amex/Discover)
52
+ - ๐Ÿ“ **Scans whole directories**, recursively by default โ€” point it at a `logs/` folder and it finds everything inside
53
+ - ๐Ÿงฉ **Custom patterns** via a simple JSON file โ€” add your own detection rules with no code changes
54
+ - โš™๏ธ **Config file support** (`.log-guard.json`) โ€” set project-level defaults for extensions, recursion, custom patterns, and quiet mode; CLI flags always override it
55
+ - ๐Ÿšฆ **CI / pre-commit mode** (`--check`) โ€” scans without writing files and exits with status code `1` if secrets are found, so it can block a commit or fail a build. Ships with a ready-to-use `.pre-commit-hooks.yaml`
56
+ - ๐Ÿ“„ **Non-destructive** โ€” writes a new `*.masked.log` file (or a path you choose with `-o`); your original is never touched, and a clean file with nothing to mask doesn't get a redundant copy
57
+ - ๐Ÿ“Š **Summary report** โ€” see exactly how many of each type were found
58
+ - ๐Ÿงช **Fully tested** โ€” 50+ automated tests covering detection, masking, directory scanning, config parsing, and a wide range of edge cases, run automatically on every push via GitHub Actions across Python 3.9โ€“3.12
59
+ - ๐Ÿ’ป **Handles edge cases** โ€” empty files, huge files (streamed line-by-line), unusual encodings, mixed line endings, and directories with zero matching files
60
+ - ๐Ÿšซ **Smart defaults for directories** โ€” automatically skips `.git`, `node_modules`, `venv`, `.venv`, and `__pycache__` while recursing (use `--ext all` to scan every file if you really want to)
61
+ - โšก **Zero network calls, ever**
62
+
63
+ ## Installation
64
+
65
+ ```bash
66
+ pip install logguard-cli
67
+ ```
68
+
69
+ That's it โ€” this installs the `log-guard` command. (The package is named `logguard-cli` on PyPI because the name `log-guard` was already taken, but the command you run is still `log-guard`.)
70
+
71
+ Requires Python 3.9 or newer.
72
+
73
+ > **Note:** if `log-guard` isn't recognized as a command right after installing, your Python Scripts folder probably isn't on your system PATH. Either add it to PATH, or run the tool with `python -m log_guard` instead โ€” both work identically.
74
+
75
+ ### Installing from source (for development)
76
+
77
+ ```bash
78
+ git clone https://github.com/apurvaraj9/log-guard.git
79
+ cd log-guard
80
+ pip install -e .
81
+ ```
82
+
83
+ This installs Log Guard as an editable package, so any changes you make to the code take effect immediately.
84
+
85
+ ## Usage
86
+
87
+ **Scan a single file:**
88
+
89
+ ```bash
90
+ log-guard your.log
91
+ ```
92
+
93
+ Creates `your.masked.log` alongside the original (unless nothing was found โ€” then no output file is created, to avoid clutter).
94
+
95
+ **Scan an entire directory (recursive by default):**
96
+
97
+ ```bash
98
+ log-guard logs/
99
+ ```
100
+
101
+ By default this scans `.log`, `.txt`, `.csv`, `.json`, `.out`, and `.err` files, skipping `.git`/`node_modules`/`venv`/`__pycache__` automatically.
102
+
103
+ ```bash
104
+ log-guard logs/ --ext log,txt --no-recursive # only .log/.txt, top level only
105
+ log-guard logs/ --ext all # scan every file, any extension
106
+ ```
107
+
108
+ **Choose a specific output path:**
109
+
110
+ ```bash
111
+ log-guard your.log -o cleaned.log
112
+ ```
113
+
114
+ (Only valid for a single input file.)
115
+
116
+ **CI / pre-commit mode** โ€” scans without writing files, exits `1` if anything is found:
117
+
118
+ ```bash
119
+ log-guard logs/*.log --check
120
+ ```
121
+
122
+ Add `--quiet` for a condensed summary suited to CI logs. To use Log Guard as an actual [pre-commit](https://pre-commit.com) hook in any repo:
123
+
124
+ ```yaml
125
+ repos:
126
+ - repo: https://github.com/apurvaraj9/log-guard
127
+ rev: v0.1.0
128
+ hooks:
129
+ - id: log-guard
130
+ ```
131
+
132
+ **Custom detection patterns:**
133
+
134
+ ```json
135
+ // custom_patterns.json
136
+ {
137
+ "employee_id": "EMP-\\d{6}"
138
+ }
139
+ ```
140
+
141
+ ```bash
142
+ log-guard your.log --patterns custom_patterns.json
143
+ ```
144
+
145
+ **Project-level config file** โ€” create `.log-guard.json` in your project root to set defaults (CLI flags always override these):
146
+
147
+ ```json
148
+ {
149
+ "extensions": ["log", "txt"],
150
+ "recursive": false,
151
+ "patterns": "custom_patterns.json",
152
+ "quiet": false
153
+ }
154
+ ```
155
+
156
+ An example is included as `.log-guard.json.example` โ€” copy it to `.log-guard.json` and adjust as needed.
157
+
158
+ ### Example
159
+
160
+ **Before:**
161
+ ```
162
+ 2024-01-15 10:22:31 INFO User login successful for john.doe@example.com
163
+ 2024-01-15 10:23:02 DEBUG API request with key sk_live_51Hz8f92jak3ndlka9d
164
+ ```
165
+
166
+ **After:**
167
+ ```
168
+ 2024-01-15 10:22:31 INFO User login successful for [EMAIL_REDACTED]
169
+ 2024-01-15 10:23:02 DEBUG API request with key [API_KEY_REDACTED]
170
+ ```
171
+
172
+ ## Running the tests
173
+
174
+ From a source checkout (see "Installing from source" above):
175
+
176
+ ```bash
177
+ pip install pytest
178
+ pytest
179
+ ```
180
+
181
+ ## Project structure
182
+
183
+ ```
184
+ log-guard/
185
+ โ”œโ”€โ”€ .github/workflows/tests.yml # GitHub Actions: runs the test suite on every push
186
+ โ”œโ”€โ”€ log_guard.py # Core tool: detection, masking, CLI, config, directory scanning
187
+ โ”œโ”€โ”€ test_log_guard.py # Automated test suite (pytest)
188
+ โ”œโ”€โ”€ pyproject.toml # Packaging config (PyPI metadata + the `log-guard` command)
189
+ โ”œโ”€โ”€ .pre-commit-hooks.yaml # Lets others use Log Guard as a pre-commit hook
190
+ โ”œโ”€โ”€ .log-guard.json.example # Example project config file
191
+ โ”œโ”€โ”€ sample.log # Example log file for testing
192
+ โ”œโ”€โ”€ generate_samples.py # Generates edge-case sample files for manual testing
193
+ โ”œโ”€โ”€ generate_test_logs_dir.py # Generates a sample directory tree for directory-scanning tests
194
+ โ””โ”€โ”€ README.md
195
+ ```
196
+
197
+ ## Limitations
198
+
199
+ - Detection is regex-based, so like any pattern-matching approach it can occasionally miss unusual formats (false negatives) or flag something that isn't actually sensitive (false positives) โ€” especially the generic long-token API key fallback, which can flag any long run of random-looking characters.
200
+ - Currently focused on common US-style phone number and card formats.
201
+ - **Only plain-text files are read correctly.** Binary formats โ€” notably `.xlsx`/`.xls` Excel spreadsheets โ€” are not yet supported; pointing Log Guard at one won't crash, but it also won't reliably find anything inside, since it isn't plain text under the hood. Proper spreadsheet support (reading actual cell contents) is a planned future feature.
202
+ - This tool reduces the risk of accidentally sharing sensitive data, but it isn't a substitute for careful review of anything genuinely high-stakes before sharing.
203
+
204
+ ## Roadmap
205
+
206
+ - [ ] `.xlsx`/`.xls` support (via `openpyxl`)
207
+ - [x] PyPI packaging (`pip install logguard-cli`)
208
+
209
+ ## License
210
+
211
+ MIT โ€” see [LICENSE](https://github.com/apurvaraj9/log-guard/blob/main/LICENSE).
212
+
213
+ ## Author
214
+
215
+ Built by [Apurva Raj](https://github.com/apurvaraj9).
@@ -0,0 +1,186 @@
1
+ # ๐Ÿ›ก๏ธ Log Guard
2
+
3
+ [![Tests](https://github.com/apurvaraj9/log-guard/actions/workflows/tests.yml/badge.svg)](https://github.com/apurvaraj9/log-guard/actions/workflows/tests.yml)
4
+
5
+ **A local, offline tool that scans server log files and masks sensitive data before you share them for debugging.**
6
+
7
+ No uploads. No third-party servers. No enterprise pricing. Your logs never leave your machine.
8
+
9
+ ---
10
+
11
+ ## Why Log Guard?
12
+
13
+ When you're debugging with a teammate, posting to a forum, or filing a support ticket, you often need to share a log file โ€” but real logs are full of things you *shouldn't* share: customer emails, phone numbers, API keys, IP addresses, credit card numbers.
14
+
15
+ - **Online masking tools** require uploading your private logs to a third-party server โ€” a privacy risk in itself.
16
+ - **Enterprise security tools** solve this, but are expensive, complex, and overkill for an individual developer or small team.
17
+
18
+ **Log Guard** runs 100% locally, does one job well, and stays simple.
19
+
20
+ ## Features
21
+
22
+ - ๐Ÿ” **Detects and masks:** emails, phone numbers, API keys (Stripe/AWS/GitHub formats + a generic long-token fallback), IP addresses, and credit card numbers (Visa/Mastercard/Amex/Discover)
23
+ - ๐Ÿ“ **Scans whole directories**, recursively by default โ€” point it at a `logs/` folder and it finds everything inside
24
+ - ๐Ÿงฉ **Custom patterns** via a simple JSON file โ€” add your own detection rules with no code changes
25
+ - โš™๏ธ **Config file support** (`.log-guard.json`) โ€” set project-level defaults for extensions, recursion, custom patterns, and quiet mode; CLI flags always override it
26
+ - ๐Ÿšฆ **CI / pre-commit mode** (`--check`) โ€” scans without writing files and exits with status code `1` if secrets are found, so it can block a commit or fail a build. Ships with a ready-to-use `.pre-commit-hooks.yaml`
27
+ - ๐Ÿ“„ **Non-destructive** โ€” writes a new `*.masked.log` file (or a path you choose with `-o`); your original is never touched, and a clean file with nothing to mask doesn't get a redundant copy
28
+ - ๐Ÿ“Š **Summary report** โ€” see exactly how many of each type were found
29
+ - ๐Ÿงช **Fully tested** โ€” 50+ automated tests covering detection, masking, directory scanning, config parsing, and a wide range of edge cases, run automatically on every push via GitHub Actions across Python 3.9โ€“3.12
30
+ - ๐Ÿ’ป **Handles edge cases** โ€” empty files, huge files (streamed line-by-line), unusual encodings, mixed line endings, and directories with zero matching files
31
+ - ๐Ÿšซ **Smart defaults for directories** โ€” automatically skips `.git`, `node_modules`, `venv`, `.venv`, and `__pycache__` while recursing (use `--ext all` to scan every file if you really want to)
32
+ - โšก **Zero network calls, ever**
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install logguard-cli
38
+ ```
39
+
40
+ That's it โ€” this installs the `log-guard` command. (The package is named `logguard-cli` on PyPI because the name `log-guard` was already taken, but the command you run is still `log-guard`.)
41
+
42
+ Requires Python 3.9 or newer.
43
+
44
+ > **Note:** if `log-guard` isn't recognized as a command right after installing, your Python Scripts folder probably isn't on your system PATH. Either add it to PATH, or run the tool with `python -m log_guard` instead โ€” both work identically.
45
+
46
+ ### Installing from source (for development)
47
+
48
+ ```bash
49
+ git clone https://github.com/apurvaraj9/log-guard.git
50
+ cd log-guard
51
+ pip install -e .
52
+ ```
53
+
54
+ This installs Log Guard as an editable package, so any changes you make to the code take effect immediately.
55
+
56
+ ## Usage
57
+
58
+ **Scan a single file:**
59
+
60
+ ```bash
61
+ log-guard your.log
62
+ ```
63
+
64
+ Creates `your.masked.log` alongside the original (unless nothing was found โ€” then no output file is created, to avoid clutter).
65
+
66
+ **Scan an entire directory (recursive by default):**
67
+
68
+ ```bash
69
+ log-guard logs/
70
+ ```
71
+
72
+ By default this scans `.log`, `.txt`, `.csv`, `.json`, `.out`, and `.err` files, skipping `.git`/`node_modules`/`venv`/`__pycache__` automatically.
73
+
74
+ ```bash
75
+ log-guard logs/ --ext log,txt --no-recursive # only .log/.txt, top level only
76
+ log-guard logs/ --ext all # scan every file, any extension
77
+ ```
78
+
79
+ **Choose a specific output path:**
80
+
81
+ ```bash
82
+ log-guard your.log -o cleaned.log
83
+ ```
84
+
85
+ (Only valid for a single input file.)
86
+
87
+ **CI / pre-commit mode** โ€” scans without writing files, exits `1` if anything is found:
88
+
89
+ ```bash
90
+ log-guard logs/*.log --check
91
+ ```
92
+
93
+ Add `--quiet` for a condensed summary suited to CI logs. To use Log Guard as an actual [pre-commit](https://pre-commit.com) hook in any repo:
94
+
95
+ ```yaml
96
+ repos:
97
+ - repo: https://github.com/apurvaraj9/log-guard
98
+ rev: v0.1.0
99
+ hooks:
100
+ - id: log-guard
101
+ ```
102
+
103
+ **Custom detection patterns:**
104
+
105
+ ```json
106
+ // custom_patterns.json
107
+ {
108
+ "employee_id": "EMP-\\d{6}"
109
+ }
110
+ ```
111
+
112
+ ```bash
113
+ log-guard your.log --patterns custom_patterns.json
114
+ ```
115
+
116
+ **Project-level config file** โ€” create `.log-guard.json` in your project root to set defaults (CLI flags always override these):
117
+
118
+ ```json
119
+ {
120
+ "extensions": ["log", "txt"],
121
+ "recursive": false,
122
+ "patterns": "custom_patterns.json",
123
+ "quiet": false
124
+ }
125
+ ```
126
+
127
+ An example is included as `.log-guard.json.example` โ€” copy it to `.log-guard.json` and adjust as needed.
128
+
129
+ ### Example
130
+
131
+ **Before:**
132
+ ```
133
+ 2024-01-15 10:22:31 INFO User login successful for john.doe@example.com
134
+ 2024-01-15 10:23:02 DEBUG API request with key sk_live_51Hz8f92jak3ndlka9d
135
+ ```
136
+
137
+ **After:**
138
+ ```
139
+ 2024-01-15 10:22:31 INFO User login successful for [EMAIL_REDACTED]
140
+ 2024-01-15 10:23:02 DEBUG API request with key [API_KEY_REDACTED]
141
+ ```
142
+
143
+ ## Running the tests
144
+
145
+ From a source checkout (see "Installing from source" above):
146
+
147
+ ```bash
148
+ pip install pytest
149
+ pytest
150
+ ```
151
+
152
+ ## Project structure
153
+
154
+ ```
155
+ log-guard/
156
+ โ”œโ”€โ”€ .github/workflows/tests.yml # GitHub Actions: runs the test suite on every push
157
+ โ”œโ”€โ”€ log_guard.py # Core tool: detection, masking, CLI, config, directory scanning
158
+ โ”œโ”€โ”€ test_log_guard.py # Automated test suite (pytest)
159
+ โ”œโ”€โ”€ pyproject.toml # Packaging config (PyPI metadata + the `log-guard` command)
160
+ โ”œโ”€โ”€ .pre-commit-hooks.yaml # Lets others use Log Guard as a pre-commit hook
161
+ โ”œโ”€โ”€ .log-guard.json.example # Example project config file
162
+ โ”œโ”€โ”€ sample.log # Example log file for testing
163
+ โ”œโ”€โ”€ generate_samples.py # Generates edge-case sample files for manual testing
164
+ โ”œโ”€โ”€ generate_test_logs_dir.py # Generates a sample directory tree for directory-scanning tests
165
+ โ””โ”€โ”€ README.md
166
+ ```
167
+
168
+ ## Limitations
169
+
170
+ - Detection is regex-based, so like any pattern-matching approach it can occasionally miss unusual formats (false negatives) or flag something that isn't actually sensitive (false positives) โ€” especially the generic long-token API key fallback, which can flag any long run of random-looking characters.
171
+ - Currently focused on common US-style phone number and card formats.
172
+ - **Only plain-text files are read correctly.** Binary formats โ€” notably `.xlsx`/`.xls` Excel spreadsheets โ€” are not yet supported; pointing Log Guard at one won't crash, but it also won't reliably find anything inside, since it isn't plain text under the hood. Proper spreadsheet support (reading actual cell contents) is a planned future feature.
173
+ - This tool reduces the risk of accidentally sharing sensitive data, but it isn't a substitute for careful review of anything genuinely high-stakes before sharing.
174
+
175
+ ## Roadmap
176
+
177
+ - [ ] `.xlsx`/`.xls` support (via `openpyxl`)
178
+ - [x] PyPI packaging (`pip install logguard-cli`)
179
+
180
+ ## License
181
+
182
+ MIT โ€” see [LICENSE](https://github.com/apurvaraj9/log-guard/blob/main/LICENSE).
183
+
184
+ ## Author
185
+
186
+ Built by [Apurva Raj](https://github.com/apurvaraj9).
@@ -0,0 +1,552 @@
1
+ import re
2
+ import argparse
3
+ import os
4
+ import json
5
+ import sys
6
+
7
+
8
+ def read_log_file_lines(filepath):
9
+ """
10
+ A generator that yields one line at a time from the file.
11
+ """
12
+ with open(filepath, "r", encoding="utf-8", errors="replace") as file:
13
+ for line in file:
14
+ yield line
15
+
16
+
17
+ def write_log_file(filepath, lines):
18
+ """
19
+ Writes a list of lines to a new file.
20
+ """
21
+ with open(filepath, "w", encoding="utf-8") as file:
22
+ file.writelines(lines)
23
+
24
+
25
+ EMAIL_PATTERN = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
26
+ PHONE_PATTERN = r"(?:\(\d{3}\)\s?|\d{3}[-.]?)\d{3}[-.]?\d{4}"
27
+ API_KEY_PATTERN = (
28
+ r"\bsk_(?:live|test)_[A-Za-z0-9]{10,}\b"
29
+ r"|\bpk_(?:live|test)_[A-Za-z0-9]{10,}\b"
30
+ r"|\bAKIA[0-9A-Z]{16}\b"
31
+ r"|\bgh[pousr]_[A-Za-z0-9]{20,}\b"
32
+ r"|\b[A-Za-z0-9_-]{32,}\b"
33
+ )
34
+ IP_ADDRESS_PATTERN = (
35
+ r"\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}"
36
+ r"(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b"
37
+ )
38
+ CREDIT_CARD_PATTERN = (
39
+ r"\b4[0-9]{3}(?:[ -]?[0-9]{4}){3}\b"
40
+ r"|\b5[1-5][0-9]{2}(?:[ -]?[0-9]{4}){3}\b"
41
+ r"|\b3[47][0-9]{2}[ -]?[0-9]{6}[ -]?[0-9]{5}\b"
42
+ r"|\b6(?:011|5[0-9]{2})(?:[ -]?[0-9]{4}){3}\b"
43
+ )
44
+
45
+ BUILTIN_PATTERNS = {
46
+ "email": EMAIL_PATTERN,
47
+ "phone": PHONE_PATTERN,
48
+ "api_key": API_KEY_PATTERN,
49
+ "ip_address": IP_ADDRESS_PATTERN,
50
+ "credit_card": CREDIT_CARD_PATTERN,
51
+ }
52
+
53
+ DISPLAY_NAMES = {
54
+ "email": "Emails",
55
+ "phone": "Phone numbers",
56
+ "api_key": "API keys",
57
+ "ip_address": "IP addresses",
58
+ "credit_card": "Credit card numbers",
59
+ }
60
+
61
+ # Default file extensions scanned when a directory is given and no
62
+ # --ext / config "extensions" override is present. Chosen because
63
+ # these are all genuinely plain-text formats our line-by-line reader
64
+ # can handle correctly (unlike, say, .xlsx, which is a binary ZIP
65
+ # archive under the hood and needs a dedicated reader โ€” not supported
66
+ # yet).
67
+ DEFAULT_EXTENSIONS = ["log", "txt", "csv", "json", "out", "err"]
68
+
69
+ # Directories that are never worth recursing into automatically โ€”
70
+ # their contents are tooling/dependency internals, not application
71
+ # logs, and scanning them would be slow and noisy. This only applies
72
+ # when *recursing into* a subfolder; if the user points directly at
73
+ # one of these as their input path, it's still scanned.
74
+ IGNORED_DIR_NAMES = {".git", "node_modules", "venv", ".venv", "__pycache__"}
75
+
76
+
77
+ def load_custom_patterns(filepath):
78
+ """
79
+ Loads a JSON file of custom patterns and returns whatever it parses
80
+ to (validation happens in build_patterns, not here).
81
+ """
82
+ with open(filepath, "r", encoding="utf-8") as file:
83
+ return json.load(file)
84
+
85
+
86
+ def build_patterns(custom_patterns_filepath=None):
87
+ """
88
+ Combines the built-in patterns with any custom patterns loaded from
89
+ a JSON file. Validates custom patterns so a bad file produces one
90
+ clear error message instead of crashing later during scanning.
91
+ """
92
+ patterns = dict(BUILTIN_PATTERNS)
93
+
94
+ if custom_patterns_filepath:
95
+ custom_patterns = load_custom_patterns(custom_patterns_filepath)
96
+
97
+ if not isinstance(custom_patterns, dict):
98
+ raise ValueError(
99
+ "Custom patterns file must contain a JSON object mapping "
100
+ "labels to regex strings, e.g. {\"employee_id\": \"EMP-\\\\d{6}\"}"
101
+ )
102
+
103
+ for label, pattern in custom_patterns.items():
104
+ if not isinstance(pattern, str):
105
+ raise ValueError(
106
+ f"Custom pattern '{label}' must be a string, "
107
+ f"got {type(pattern).__name__} instead."
108
+ )
109
+ try:
110
+ re.compile(pattern)
111
+ except re.error as e:
112
+ raise ValueError(f"Invalid regex for custom pattern '{label}': {e}")
113
+
114
+ patterns.update(custom_patterns)
115
+
116
+ return patterns
117
+
118
+
119
+ def mask_line(line, patterns):
120
+ """
121
+ Takes a single log line and a dict of label -> regex string.
122
+ Returns a tuple of: (masked_line, counts_dict)
123
+ """
124
+ counts = {}
125
+ for label, pattern in patterns.items():
126
+ placeholder = f"[{label.upper()}_REDACTED]"
127
+ line, count = re.subn(pattern, placeholder, line)
128
+ counts[label] = count
129
+ return line, counts
130
+
131
+
132
+ def mask_log(lines, patterns):
133
+ """
134
+ Applies mask_line to every line in a log.
135
+ Returns a tuple of: (masked_lines, total_counts, line_count)
136
+ """
137
+ masked_lines = []
138
+ total_counts = {label: 0 for label in patterns}
139
+ line_count = 0
140
+
141
+ for line in lines:
142
+ line_count += 1
143
+ masked_line, counts = mask_line(line, patterns)
144
+ masked_lines.append(masked_line)
145
+ for label in total_counts:
146
+ total_counts[label] += counts[label]
147
+
148
+ return masked_lines, total_counts, line_count
149
+
150
+
151
+ def build_output_filepath(input_filepath):
152
+ """
153
+ Given "somelog.log", returns "somelog.masked.log" in the same folder.
154
+ """
155
+ base, ext = os.path.splitext(input_filepath)
156
+ return f"{base}.masked{ext}"
157
+
158
+
159
+ def print_summary(total_counts, heading="--- Summary ---", verb="masked"):
160
+ """
161
+ Prints a summary report. verb is "masked" in normal mode or "found"
162
+ in --check mode, since check mode doesn't actually mask anything.
163
+ """
164
+ total_items = sum(total_counts.values())
165
+ print(heading)
166
+ for label, count in total_counts.items():
167
+ display_name = DISPLAY_NAMES.get(label, label.replace("_", " ").title())
168
+ print(f"{display_name} {verb}: {count}")
169
+ print(f"Total items {verb}: {total_items}")
170
+
171
+
172
+ def merge_counts(counts_a, counts_b):
173
+ """
174
+ Merges two label -> count dicts by summing shared keys.
175
+ """
176
+ merged = dict(counts_a)
177
+ for label, count in counts_b.items():
178
+ merged[label] = merged.get(label, 0) + count
179
+ return merged
180
+
181
+
182
+ def _has_matching_extension(filename, pattern_exts):
183
+ """
184
+ Checks if filename's extension (lowercased, no dot) is in the
185
+ pattern_exts set.
186
+ """
187
+ if "." not in filename:
188
+ return False
189
+ ext = filename.rsplit(".", 1)[-1].lower()
190
+ return ext in pattern_exts
191
+
192
+
193
+ def expand_filepaths(filepaths, extensions, recursive):
194
+ """
195
+ Expands any directory paths in `filepaths` into the files they
196
+ contain. `extensions` is either a list like ["log", "txt"]
197
+ (case-insensitive, with or without a leading dot) to filter by,
198
+ or None to match every file regardless of extension ("scan all"
199
+ mode). Recurses into subfolders unless recursive is False, and
200
+ automatically skips IGNORED_DIR_NAMES subfolders while recursing.
201
+ Plain file paths are passed through unchanged.
202
+
203
+ Returns a tuple: (expanded_filepaths, warnings), where warnings is
204
+ a list of human-readable strings for any directory that matched
205
+ zero files.
206
+ """
207
+ pattern_exts = None if extensions is None else {ext.lower().lstrip(".") for ext in extensions}
208
+ expanded = []
209
+ warnings = []
210
+
211
+ for path in filepaths:
212
+ if os.path.isdir(path):
213
+ found = []
214
+ if recursive:
215
+ for root, dirs, files in os.walk(path):
216
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIR_NAMES]
217
+ for filename in files:
218
+ if pattern_exts is None or _has_matching_extension(filename, pattern_exts):
219
+ found.append(os.path.join(root, filename))
220
+ else:
221
+ for filename in os.listdir(path):
222
+ full_path = os.path.join(path, filename)
223
+ if os.path.isfile(full_path) and (
224
+ pattern_exts is None or _has_matching_extension(filename, pattern_exts)
225
+ ):
226
+ found.append(full_path)
227
+
228
+ if found:
229
+ expanded.extend(sorted(found))
230
+ elif pattern_exts is None:
231
+ warnings.append(f"no files found in directory: {path}")
232
+ else:
233
+ ext_display = ", ".join(f".{e}" for e in sorted(pattern_exts))
234
+ warnings.append(f"no files matching [{ext_display}] found in directory: {path}")
235
+ else:
236
+ expanded.append(path)
237
+
238
+ return expanded, warnings
239
+
240
+
241
+ def load_config(config_path):
242
+ """
243
+ Loads and validates a JSON config file. Returns a dict containing
244
+ only the keys that were present (extensions, recursive, patterns,
245
+ quiet), so main() can layer command-line flags on top of it.
246
+ """
247
+ with open(config_path, "r", encoding="utf-8") as file:
248
+ data = json.load(file)
249
+
250
+ if not isinstance(data, dict):
251
+ raise ValueError("Config file must contain a JSON object.")
252
+
253
+ allowed_keys = {"extensions", "recursive", "patterns", "quiet"}
254
+ unknown_keys = set(data.keys()) - allowed_keys
255
+ if unknown_keys:
256
+ raise ValueError(
257
+ f"Unknown config option(s): {', '.join(sorted(unknown_keys))}. "
258
+ f"Allowed options: {', '.join(sorted(allowed_keys))}"
259
+ )
260
+
261
+ if "extensions" in data:
262
+ if not isinstance(data["extensions"], list) or not all(isinstance(e, str) for e in data["extensions"]):
263
+ raise ValueError("Config option 'extensions' must be a list of strings, e.g. [\"log\", \"txt\"]")
264
+
265
+ if "recursive" in data and not isinstance(data["recursive"], bool):
266
+ raise ValueError("Config option 'recursive' must be true or false.")
267
+
268
+ if "patterns" in data and not isinstance(data["patterns"], str):
269
+ raise ValueError("Config option 'patterns' must be a string file path.")
270
+
271
+ if "quiet" in data and not isinstance(data["quiet"], bool):
272
+ raise ValueError("Config option 'quiet' must be true or false.")
273
+
274
+ return data
275
+
276
+
277
+ def process_file(filepath, patterns, check_mode, output_override=None):
278
+ """
279
+ Reads and scans a single file. In check_mode, never writes an output
280
+ file. In normal mode, writes an output file UNLESS nothing was found
281
+ AND no explicit output_override was given.
282
+ """
283
+ result = {
284
+ "filepath": filepath,
285
+ "error": None,
286
+ "empty": False,
287
+ "line_count": 0,
288
+ "counts": {label: 0 for label in patterns},
289
+ "output_filepath": None,
290
+ "skipped_write": False,
291
+ }
292
+
293
+ if not os.path.isfile(filepath):
294
+ result["error"] = f"file not found: {filepath}"
295
+ return result
296
+
297
+ try:
298
+ lines = read_log_file_lines(filepath)
299
+ masked_lines, total_counts, line_count = mask_log(lines, patterns)
300
+ except FileNotFoundError:
301
+ result["error"] = f"file not found (it may have been deleted or moved): {filepath}"
302
+ return result
303
+ except PermissionError:
304
+ result["error"] = f"permission denied when trying to read: {filepath}"
305
+ return result
306
+ except OSError as e:
307
+ result["error"] = f"could not read file: {filepath} ({e})"
308
+ return result
309
+
310
+ result["line_count"] = line_count
311
+ result["counts"] = total_counts
312
+
313
+ if line_count == 0:
314
+ result["empty"] = True
315
+ return result
316
+
317
+ if not check_mode:
318
+ total_found = sum(total_counts.values())
319
+
320
+ if total_found == 0 and output_override is None:
321
+ result["skipped_write"] = True
322
+ return result
323
+
324
+ output_filepath = output_override or build_output_filepath(filepath)
325
+ try:
326
+ write_log_file(output_filepath, masked_lines)
327
+ except PermissionError:
328
+ result["error"] = f"permission denied when trying to write: {output_filepath}"
329
+ return result
330
+ except OSError as e:
331
+ result["error"] = f"could not write file: {output_filepath} ({e})"
332
+ return result
333
+ result["output_filepath"] = output_filepath
334
+
335
+ return result
336
+
337
+
338
+ def parse_arguments():
339
+ """
340
+ Defines and parses command-line arguments for Log Guard.
341
+ """
342
+ parser = argparse.ArgumentParser(
343
+ prog="log-guard",
344
+ description=(
345
+ "Scan log files (or entire directories) and mask sensitive data "
346
+ "(emails, phone numbers, API keys, IP addresses, credit cards, "
347
+ "and custom patterns)."
348
+ ),
349
+ epilog=(
350
+ "Examples:\n"
351
+ " log-guard sample.log\n"
352
+ " log-guard sample.log -o cleaned.log\n"
353
+ " log-guard logs/ # scans log/txt/csv/json/out/err in logs/, recursively\n"
354
+ " log-guard logs/ --ext log,txt --no-recursive\n"
355
+ " log-guard logs/ --ext all # scan every file, any extension\n"
356
+ " log-guard sample.log --patterns custom_patterns.json\n"
357
+ " log-guard *.log --check # CI/pre-commit mode: pass/fail, no output files\n"
358
+ "\n"
359
+ "A .log-guard.json file in the current directory (or passed via --config)\n"
360
+ "can set default values for extensions, recursive, patterns, and quiet.\n"
361
+ "Command-line flags always override the config file."
362
+ ),
363
+ formatter_class=argparse.RawDescriptionHelpFormatter
364
+ )
365
+ parser.add_argument(
366
+ "filepaths",
367
+ nargs="+",
368
+ help="Path(s) to log file(s) and/or directories to scan"
369
+ )
370
+ parser.add_argument(
371
+ "-o", "--output",
372
+ metavar="FILE",
373
+ default=None,
374
+ help=(
375
+ "Output file path. Only valid with a single input file, and not "
376
+ "usable with --check. Defaults to <name>.masked<ext> if omitted."
377
+ )
378
+ )
379
+ parser.add_argument(
380
+ "--patterns",
381
+ metavar="FILE",
382
+ default=None,
383
+ help="Path to a JSON file of custom patterns to add (label: regex). Overrides config's 'patterns'."
384
+ )
385
+ parser.add_argument(
386
+ "--check",
387
+ action="store_true",
388
+ help=(
389
+ "Check-only mode for CI/pre-commit hooks: scans files but does NOT "
390
+ "write masked output files. Exits with status 1 if any sensitive "
391
+ "data is found, 0 if clean."
392
+ )
393
+ )
394
+ parser.add_argument(
395
+ "--quiet",
396
+ action="store_true",
397
+ help="Suppress per-file details; only print the final result. Overrides config's 'quiet' (can only force it ON)."
398
+ )
399
+ parser.add_argument(
400
+ "--config",
401
+ metavar="FILE",
402
+ default=None,
403
+ help="Path to a JSON config file (defaults to .log-guard.json in the current directory, if present)"
404
+ )
405
+ parser.add_argument(
406
+ "--ext",
407
+ metavar="EXT[,EXT...]|all",
408
+ default=None,
409
+ help=(
410
+ "Comma-separated file extensions to scan inside a directory "
411
+ f"(default: {','.join(DEFAULT_EXTENSIONS)}, or config's 'extensions'). "
412
+ "Use --ext all to scan every file regardless of extension. Example: --ext log,txt"
413
+ )
414
+ )
415
+ parser.add_argument(
416
+ "--recursive",
417
+ action="store_true",
418
+ help="Recurse into subfolders when a directory is given (this is the default; overrides config's 'recursive' to force it ON)."
419
+ )
420
+ parser.add_argument(
421
+ "--no-recursive",
422
+ action="store_true",
423
+ help="Do not recurse into subfolders when a directory is given (overrides config's 'recursive' to force it OFF)."
424
+ )
425
+ return parser.parse_args()
426
+
427
+
428
+ def main():
429
+ args = parse_arguments()
430
+
431
+ if args.recursive and args.no_recursive:
432
+ print("Error: cannot use both --recursive and --no-recursive.")
433
+ sys.exit(2)
434
+
435
+ # --- Resolve config file: explicit --config, or default .log-guard.json if present ---
436
+ config = {}
437
+ config_path = args.config
438
+ if config_path is None and os.path.isfile(".log-guard.json"):
439
+ config_path = ".log-guard.json"
440
+
441
+ if config_path:
442
+ if not os.path.isfile(config_path):
443
+ print(f"Error: config file not found: {config_path}")
444
+ sys.exit(2)
445
+ try:
446
+ config = load_config(config_path)
447
+ except json.JSONDecodeError as e:
448
+ print(f"Error: invalid JSON in config file {config_path}: {e}")
449
+ sys.exit(2)
450
+ except ValueError as e:
451
+ print(f"Error: invalid config file {config_path}: {e}")
452
+ sys.exit(2)
453
+
454
+ if args.ext:
455
+ extensions = None if args.ext.strip().lower() == "all" else [
456
+ ext.strip().lstrip(".") for ext in args.ext.split(",")
457
+ ]
458
+ else:
459
+ extensions = config.get("extensions", DEFAULT_EXTENSIONS)
460
+
461
+ if args.recursive:
462
+ recursive = True
463
+ elif args.no_recursive:
464
+ recursive = False
465
+ else:
466
+ recursive = config.get("recursive", True)
467
+
468
+ quiet = args.quiet or config.get("quiet", False)
469
+ patterns_filepath = args.patterns or config.get("patterns")
470
+
471
+ # --- Expand any directories into the files they contain ---
472
+ expanded_filepaths, dir_warnings = expand_filepaths(args.filepaths, extensions, recursive)
473
+ for warning in dir_warnings:
474
+ print(f"Warning: {warning}")
475
+
476
+ if not expanded_filepaths:
477
+ print("Error: no files to scan.")
478
+ sys.exit(2)
479
+
480
+ # --- Validate -o/--output against the FINAL (post-expansion) file list ---
481
+ if args.output and len(expanded_filepaths) > 1:
482
+ print("Error: -o/--output can only be used with a single input file.")
483
+ sys.exit(2)
484
+
485
+ if args.output and args.check:
486
+ print("Error: -o/--output cannot be used with --check (check mode does not write files).")
487
+ sys.exit(2)
488
+
489
+ if patterns_filepath and not os.path.isfile(patterns_filepath):
490
+ print(f"Error: custom patterns file not found: {patterns_filepath}")
491
+ sys.exit(2)
492
+
493
+ try:
494
+ patterns = build_patterns(patterns_filepath)
495
+ except json.JSONDecodeError as e:
496
+ print(f"Error: invalid JSON in {patterns_filepath}: {e}")
497
+ sys.exit(2)
498
+ except ValueError as e:
499
+ print(f"Error: {e}")
500
+ sys.exit(2)
501
+ except OSError as e:
502
+ print(f"Error: could not read custom patterns file {patterns_filepath}: {e}")
503
+ sys.exit(2)
504
+
505
+ combined_counts = {label: 0 for label in patterns}
506
+ had_error = False
507
+ verb = "found" if args.check else "masked"
508
+
509
+ for filepath in expanded_filepaths:
510
+ result = process_file(filepath, patterns, check_mode=args.check, output_override=args.output)
511
+
512
+ if result["error"]:
513
+ print(f"Error: {result['error']}")
514
+ had_error = True
515
+ continue
516
+
517
+ if result["empty"]:
518
+ if not quiet:
519
+ print(f"Warning: {filepath} is empty. Nothing to scan.")
520
+ continue
521
+
522
+ if not quiet:
523
+ print(f"Scanned {result['line_count']} lines in {filepath}")
524
+ if result["output_filepath"]:
525
+ print(f"Masked log written to {result['output_filepath']}")
526
+ elif result["skipped_write"]:
527
+ print(f"No sensitive data found in {filepath}; masked file not created.")
528
+ print_summary(result["counts"], heading=f"--- Summary for {filepath} ---", verb=verb)
529
+ print()
530
+
531
+ combined_counts = merge_counts(combined_counts, result["counts"])
532
+
533
+ if had_error:
534
+ sys.exit(2)
535
+
536
+ if args.check:
537
+ total_found = sum(combined_counts.values())
538
+ if total_found > 0:
539
+ print(f"FAILED: found {total_found} potential secret(s) across {len(expanded_filepaths)} file(s).")
540
+ if quiet:
541
+ print_summary(combined_counts, verb="found")
542
+ sys.exit(1)
543
+ else:
544
+ print(f"PASSED: no sensitive data found across {len(expanded_filepaths)} file(s).")
545
+ sys.exit(0)
546
+ else:
547
+ if len(expanded_filepaths) > 1:
548
+ print_summary(combined_counts, heading="--- Combined Summary (all files) ---")
549
+
550
+
551
+ if __name__ == "__main__":
552
+ main()
@@ -0,0 +1,215 @@
1
+ Metadata-Version: 2.4
2
+ Name: logguard-cli
3
+ Version: 0.1.0
4
+ Summary: A 100% local, offline CLI tool that scans log files and masks sensitive data (emails, phone numbers, API keys, IPs, credit cards) before you share them.
5
+ Author: Apurva Raj
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/apurvaraj9/log-guard
8
+ Project-URL: Repository, https://github.com/apurvaraj9/log-guard
9
+ Project-URL: Issues, https://github.com/apurvaraj9/log-guard/issues
10
+ Keywords: logs,logging,masking,redaction,privacy,security,pii,sensitive-data,cli,pre-commit
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: System :: Logging
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Dynamic: license-file
29
+
30
+ # ๐Ÿ›ก๏ธ Log Guard
31
+
32
+ [![Tests](https://github.com/apurvaraj9/log-guard/actions/workflows/tests.yml/badge.svg)](https://github.com/apurvaraj9/log-guard/actions/workflows/tests.yml)
33
+
34
+ **A local, offline tool that scans server log files and masks sensitive data before you share them for debugging.**
35
+
36
+ No uploads. No third-party servers. No enterprise pricing. Your logs never leave your machine.
37
+
38
+ ---
39
+
40
+ ## Why Log Guard?
41
+
42
+ When you're debugging with a teammate, posting to a forum, or filing a support ticket, you often need to share a log file โ€” but real logs are full of things you *shouldn't* share: customer emails, phone numbers, API keys, IP addresses, credit card numbers.
43
+
44
+ - **Online masking tools** require uploading your private logs to a third-party server โ€” a privacy risk in itself.
45
+ - **Enterprise security tools** solve this, but are expensive, complex, and overkill for an individual developer or small team.
46
+
47
+ **Log Guard** runs 100% locally, does one job well, and stays simple.
48
+
49
+ ## Features
50
+
51
+ - ๐Ÿ” **Detects and masks:** emails, phone numbers, API keys (Stripe/AWS/GitHub formats + a generic long-token fallback), IP addresses, and credit card numbers (Visa/Mastercard/Amex/Discover)
52
+ - ๐Ÿ“ **Scans whole directories**, recursively by default โ€” point it at a `logs/` folder and it finds everything inside
53
+ - ๐Ÿงฉ **Custom patterns** via a simple JSON file โ€” add your own detection rules with no code changes
54
+ - โš™๏ธ **Config file support** (`.log-guard.json`) โ€” set project-level defaults for extensions, recursion, custom patterns, and quiet mode; CLI flags always override it
55
+ - ๐Ÿšฆ **CI / pre-commit mode** (`--check`) โ€” scans without writing files and exits with status code `1` if secrets are found, so it can block a commit or fail a build. Ships with a ready-to-use `.pre-commit-hooks.yaml`
56
+ - ๐Ÿ“„ **Non-destructive** โ€” writes a new `*.masked.log` file (or a path you choose with `-o`); your original is never touched, and a clean file with nothing to mask doesn't get a redundant copy
57
+ - ๐Ÿ“Š **Summary report** โ€” see exactly how many of each type were found
58
+ - ๐Ÿงช **Fully tested** โ€” 50+ automated tests covering detection, masking, directory scanning, config parsing, and a wide range of edge cases, run automatically on every push via GitHub Actions across Python 3.9โ€“3.12
59
+ - ๐Ÿ’ป **Handles edge cases** โ€” empty files, huge files (streamed line-by-line), unusual encodings, mixed line endings, and directories with zero matching files
60
+ - ๐Ÿšซ **Smart defaults for directories** โ€” automatically skips `.git`, `node_modules`, `venv`, `.venv`, and `__pycache__` while recursing (use `--ext all` to scan every file if you really want to)
61
+ - โšก **Zero network calls, ever**
62
+
63
+ ## Installation
64
+
65
+ ```bash
66
+ pip install logguard-cli
67
+ ```
68
+
69
+ That's it โ€” this installs the `log-guard` command. (The package is named `logguard-cli` on PyPI because the name `log-guard` was already taken, but the command you run is still `log-guard`.)
70
+
71
+ Requires Python 3.9 or newer.
72
+
73
+ > **Note:** if `log-guard` isn't recognized as a command right after installing, your Python Scripts folder probably isn't on your system PATH. Either add it to PATH, or run the tool with `python -m log_guard` instead โ€” both work identically.
74
+
75
+ ### Installing from source (for development)
76
+
77
+ ```bash
78
+ git clone https://github.com/apurvaraj9/log-guard.git
79
+ cd log-guard
80
+ pip install -e .
81
+ ```
82
+
83
+ This installs Log Guard as an editable package, so any changes you make to the code take effect immediately.
84
+
85
+ ## Usage
86
+
87
+ **Scan a single file:**
88
+
89
+ ```bash
90
+ log-guard your.log
91
+ ```
92
+
93
+ Creates `your.masked.log` alongside the original (unless nothing was found โ€” then no output file is created, to avoid clutter).
94
+
95
+ **Scan an entire directory (recursive by default):**
96
+
97
+ ```bash
98
+ log-guard logs/
99
+ ```
100
+
101
+ By default this scans `.log`, `.txt`, `.csv`, `.json`, `.out`, and `.err` files, skipping `.git`/`node_modules`/`venv`/`__pycache__` automatically.
102
+
103
+ ```bash
104
+ log-guard logs/ --ext log,txt --no-recursive # only .log/.txt, top level only
105
+ log-guard logs/ --ext all # scan every file, any extension
106
+ ```
107
+
108
+ **Choose a specific output path:**
109
+
110
+ ```bash
111
+ log-guard your.log -o cleaned.log
112
+ ```
113
+
114
+ (Only valid for a single input file.)
115
+
116
+ **CI / pre-commit mode** โ€” scans without writing files, exits `1` if anything is found:
117
+
118
+ ```bash
119
+ log-guard logs/*.log --check
120
+ ```
121
+
122
+ Add `--quiet` for a condensed summary suited to CI logs. To use Log Guard as an actual [pre-commit](https://pre-commit.com) hook in any repo:
123
+
124
+ ```yaml
125
+ repos:
126
+ - repo: https://github.com/apurvaraj9/log-guard
127
+ rev: v0.1.0
128
+ hooks:
129
+ - id: log-guard
130
+ ```
131
+
132
+ **Custom detection patterns:**
133
+
134
+ ```json
135
+ // custom_patterns.json
136
+ {
137
+ "employee_id": "EMP-\\d{6}"
138
+ }
139
+ ```
140
+
141
+ ```bash
142
+ log-guard your.log --patterns custom_patterns.json
143
+ ```
144
+
145
+ **Project-level config file** โ€” create `.log-guard.json` in your project root to set defaults (CLI flags always override these):
146
+
147
+ ```json
148
+ {
149
+ "extensions": ["log", "txt"],
150
+ "recursive": false,
151
+ "patterns": "custom_patterns.json",
152
+ "quiet": false
153
+ }
154
+ ```
155
+
156
+ An example is included as `.log-guard.json.example` โ€” copy it to `.log-guard.json` and adjust as needed.
157
+
158
+ ### Example
159
+
160
+ **Before:**
161
+ ```
162
+ 2024-01-15 10:22:31 INFO User login successful for john.doe@example.com
163
+ 2024-01-15 10:23:02 DEBUG API request with key sk_live_51Hz8f92jak3ndlka9d
164
+ ```
165
+
166
+ **After:**
167
+ ```
168
+ 2024-01-15 10:22:31 INFO User login successful for [EMAIL_REDACTED]
169
+ 2024-01-15 10:23:02 DEBUG API request with key [API_KEY_REDACTED]
170
+ ```
171
+
172
+ ## Running the tests
173
+
174
+ From a source checkout (see "Installing from source" above):
175
+
176
+ ```bash
177
+ pip install pytest
178
+ pytest
179
+ ```
180
+
181
+ ## Project structure
182
+
183
+ ```
184
+ log-guard/
185
+ โ”œโ”€โ”€ .github/workflows/tests.yml # GitHub Actions: runs the test suite on every push
186
+ โ”œโ”€โ”€ log_guard.py # Core tool: detection, masking, CLI, config, directory scanning
187
+ โ”œโ”€โ”€ test_log_guard.py # Automated test suite (pytest)
188
+ โ”œโ”€โ”€ pyproject.toml # Packaging config (PyPI metadata + the `log-guard` command)
189
+ โ”œโ”€โ”€ .pre-commit-hooks.yaml # Lets others use Log Guard as a pre-commit hook
190
+ โ”œโ”€โ”€ .log-guard.json.example # Example project config file
191
+ โ”œโ”€โ”€ sample.log # Example log file for testing
192
+ โ”œโ”€โ”€ generate_samples.py # Generates edge-case sample files for manual testing
193
+ โ”œโ”€โ”€ generate_test_logs_dir.py # Generates a sample directory tree for directory-scanning tests
194
+ โ””โ”€โ”€ README.md
195
+ ```
196
+
197
+ ## Limitations
198
+
199
+ - Detection is regex-based, so like any pattern-matching approach it can occasionally miss unusual formats (false negatives) or flag something that isn't actually sensitive (false positives) โ€” especially the generic long-token API key fallback, which can flag any long run of random-looking characters.
200
+ - Currently focused on common US-style phone number and card formats.
201
+ - **Only plain-text files are read correctly.** Binary formats โ€” notably `.xlsx`/`.xls` Excel spreadsheets โ€” are not yet supported; pointing Log Guard at one won't crash, but it also won't reliably find anything inside, since it isn't plain text under the hood. Proper spreadsheet support (reading actual cell contents) is a planned future feature.
202
+ - This tool reduces the risk of accidentally sharing sensitive data, but it isn't a substitute for careful review of anything genuinely high-stakes before sharing.
203
+
204
+ ## Roadmap
205
+
206
+ - [ ] `.xlsx`/`.xls` support (via `openpyxl`)
207
+ - [x] PyPI packaging (`pip install logguard-cli`)
208
+
209
+ ## License
210
+
211
+ MIT โ€” see [LICENSE](https://github.com/apurvaraj9/log-guard/blob/main/LICENSE).
212
+
213
+ ## Author
214
+
215
+ Built by [Apurva Raj](https://github.com/apurvaraj9).
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ README.md
3
+ log_guard.py
4
+ pyproject.toml
5
+ logguard_cli.egg-info/PKG-INFO
6
+ logguard_cli.egg-info/SOURCES.txt
7
+ logguard_cli.egg-info/dependency_links.txt
8
+ logguard_cli.egg-info/entry_points.txt
9
+ logguard_cli.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ log-guard = log_guard:main
@@ -0,0 +1 @@
1
+ log_guard
@@ -0,0 +1,54 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "logguard-cli"
7
+ version = "0.1.0"
8
+ description = "A 100% local, offline CLI tool that scans log files and masks sensitive data (emails, phone numbers, API keys, IPs, credit cards) before you share them."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "Apurva Raj" }
15
+ ]
16
+ keywords = [
17
+ "logs",
18
+ "logging",
19
+ "masking",
20
+ "redaction",
21
+ "privacy",
22
+ "security",
23
+ "pii",
24
+ "sensitive-data",
25
+ "cli",
26
+ "pre-commit",
27
+ ]
28
+ classifiers = [
29
+ "Development Status :: 4 - Beta",
30
+ "Environment :: Console",
31
+ "Intended Audience :: Developers",
32
+ "Intended Audience :: System Administrators",
33
+ "Operating System :: OS Independent",
34
+ "Programming Language :: Python :: 3",
35
+ "Programming Language :: Python :: 3 :: Only",
36
+ "Programming Language :: Python :: 3.9",
37
+ "Programming Language :: Python :: 3.10",
38
+ "Programming Language :: Python :: 3.11",
39
+ "Programming Language :: Python :: 3.12",
40
+ "Topic :: Security",
41
+ "Topic :: System :: Logging",
42
+ "Topic :: Utilities",
43
+ ]
44
+
45
+ [project.urls]
46
+ Homepage = "https://github.com/apurvaraj9/log-guard"
47
+ Repository = "https://github.com/apurvaraj9/log-guard"
48
+ Issues = "https://github.com/apurvaraj9/log-guard/issues"
49
+
50
+ [project.scripts]
51
+ log-guard = "log_guard:main"
52
+
53
+ [tool.setuptools]
54
+ py-modules = ["log_guard"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+