Analyze, add, consolidate, and correct logging statements across any project. Detects the existing logging framework, applies strict log-level criteria, and follows established conventions. Language-agnostic.
Add missing logging statements, consolidate duplicates, correct log levels, and fix pattern violations. This skill is language-agnostic and works with any existing logging framework. It does NOT introduce or recommend new logging frameworks.
Follow this workflow strictly, phase by phase.
Parse $ARGUMENTS:
Scope (first positional argument):
src/services/UserService.cs) — analyze single filesrc/services/) — analyze all source files in directory--all — analyze all eligible source files in the project--allFlags:
--lang <code> — Human language for log message text in newly added statements. Default: (English). Examples: , , , , . Existing log messages in a different language are NOT translated; only new statements use the specified language.enendefresja--analyze-only — Run Phase 0 and Phase 1 only, present the report, do not modify any files.--fix-levels-only — Only correct log levels on existing statements; do not add new logging or remove duplicates.Never analyze files in these directories:
bin/, obj/, build/, dist/, target/, out/, __pycache__/node_modules/, vendor/, .venv/, packages/, Packages/// <auto-generated>, # Generated by, etc.).git/, .svn/, .hg/Never analyze these file types:
If the user explicitly requests an excluded file or directory, explain why it is excluded and ask for confirmation before proceeding.
Identify the programming language(s) in scope by examining:
.cs, .java, .py, .ts, .js, .go, .rs, .rb, .php, etc.)*.csproj, *.sln, pom.xml, build.gradle, package.json, go.mod, Cargo.toml, Gemfile, composer.json, etc.)Search the codebase for imports, usings, and instantiation patterns to detect the logging framework:
| Language | Frameworks to detect |
|---|---|
| C# / .NET | ILogger<T>, ILoggerFactory, Serilog (Log., LoggerConfiguration), NLog (LogManager), log4net (LogManager.GetLogger) |
| Java / Kotlin | SLF4J (LoggerFactory.getLogger), Log4j2 (LogManager.getLogger), java.util.logging (Logger.getLogger) |
| Python | logging module (logging.getLogger), loguru (from loguru import logger), structlog |
| TypeScript / JavaScript | winston (createLogger), pino, bunyan, console (console.log/warn/error) |
| Go | log/slog, zap (zap.NewLogger), logrus (logrus.New), zerolog |
| Rust | tracing (tracing::info!), log crate (log::info!), env_logger |
| Ruby | Logger.new, Rails.logger |
| PHP | Monolog (new Logger), PSR-3 LoggerInterface |
If NO logging framework is found: Report to the user: "No existing logging framework detected in the project. This skill works with existing logging infrastructure and does not introduce new frameworks. Please set up a logging framework first, then re-run this skill." Stop here.
If MULTIPLE frameworks are found: Report all detected frameworks with file counts for each. Identify the dominant framework (most usage). Ask the user which framework to standardize on, or proceed with the dominant one.
Analyze 5-10 representative files with existing logging to document:
Logger instantiation pattern: How is the logger created or injected?
public MyService(ILogger<MyService> logger)private static readonly ILogger Logger = LoggerFactory.Create(...)private static readonly Logger _log = LogManager.GetCurrentClassLogger()logger = logging.getLogger(__name__)Logger field/variable name: _logger, logger, log, _log, LOG, LOGGER
Message format:
_logger.LogDebug("Processing {Filename}", filename)logger.debug("Processing %s", filename)logger.debug(f"Processing {filename}")logger.debug("Processing " + filename)Parameter naming convention: PascalCase, camelCase, snake_case, UPPER_CASE
Sensitive data handling: Does the project use masking utilities, redaction functions, or no special treatment?
Context enrichment: Correlation IDs, request context, scoped properties, MDC
EventId / marker usage: Does the project use categorized event IDs or markers?
Present a brief summary of detected conventions:
Detected Logging Setup:
- Language: C# (.NET)
- Framework: ILogger<T> with Serilog
- Logger field: _logger (constructor-injected)
- Message format: Structured templates with PascalCase parameters
- Sensitive data: SensitiveDataMasker.Mask() utility
- Context: MigrationContext appended via {MigrationContext} placeholder
- EventIds: MigrationEvent.* constants used in infrastructure layer
Read every source file in scope (respecting Exclusions above). For each file, evaluate the following categories.
Identify methods, code paths, and locations that SHOULD have logging but currently do NOT. Apply the criteria from the "Criteria for New Logging Statements" section below.
For each finding, record:
--lang languageCheck every existing log statement against the Log-Level Decision Tree (below). Flag any that use the wrong level.
For each finding, record:
Identify cases where the same information is logged multiple times:
For each finding, record:
Check existing logging for violations of the project's detected conventions:
Present findings as a structured report:
## Logging Analysis Report
### Detected Setup
- Language: [detected]
- Framework: [detected]
- Conventions: [summary from Phase 0.3]
- Log message language for new statements: [--lang value]
### Summary
| Category | Count |
|-----------------------|-------|
| Missing logging | N |
| Incorrect log levels | N |
| Duplicate logging | N |
| Pattern violations | N |
| **Total issues** | **N** |
### By File/Directory
| Location | Missing | Wrong Level | Duplicates | Violations |
|----------|---------|-------------|------------|------------|
| ... | ... | ... | ... | ... |
### Detailed Findings
#### Missing Logging
[For each: file:line, what is missing, recommended level, draft message]
#### Incorrect Log Levels
[For each: file:line, current statement, current level -> recommended level, reason]
#### Duplicate Logging
[For each: both locations, which to keep, which to remove]
#### Pattern Violations
[For each: file:line, violation type, current code, recommended fix]
If --analyze-only was specified, stop here.
Present the analysis summary and ask:
Logging analysis complete. [X] issues found across [Y] files.
Breakdown:
- [N] missing logging statements to add
- [N] incorrect log levels to correct
- [N] duplicates to remove
- [N] pattern violations to fix
Options:
1. Apply all changes
2. Apply to specific file/directory only — tell me which
3. Cancel — make no changes
Wait for user response before proceeding.
Apply changes file by file, grouped by category:
Create new logging statements using:
--lang language for message textIf a class needs a logger but has none:
If --fix-levels-only was specified, only apply step 3.2.
After all files are modified, run the appropriate build/compile command:
| Language | Command |
|---|---|
| C# / .NET | dotnet build |
| Java (Maven) | mvn compile |
| Java (Gradle) | gradle build |
| TypeScript | tsc --noEmit or npx tsc --noEmit |
| Go | go build ./... |
| Python | python -m py_compile <file> or project-specific linter |
| Rust | cargo check |
| Other | Determine from project files (Makefile, package.json scripts, etc.) |
If the build fails:
Maximum 3 iterations. If build still fails after 3 attempts, stop and report remaining errors to the user.
Present a final summary:
## Logging Changes Applied
### Statistics
| Category | Count |
|-----------------------|-------|
| Statements added | N |
| Log levels corrected | N |
| Duplicates removed | N |
| Violations fixed | N |
| **Total changes** | **N** |
### Files Modified
[List each file with change counts]
### New Logger Instantiations
[List any classes/modules that received a new logger, with the instantiation pattern used]
### Build Verification
- Result: [Success / Failed with N remaining errors]
- [If failed: list remaining errors]
Apply these rules in order. Use the first matching rule.
Use when ALL of these are true:
Examples: database completely unreachable after all retries, critical infrastructure creation failed, application host cannot start, unrecoverable corruption detected
Use when ALL of these are true:
Examples: database update failed, file processing aborted with error, API call failed after all retries, hash validation found corruption, migration execution threw exception
Use when ANY of these are true:
Examples: file not found but handled, retry succeeded after transient failure, deprecated config option used, operation skipped due to filter, rollback file missing during validation
Use when ALL of these are true:
Examples: "Service started", "Migration completed: {Count} files applied", "Import finished: {RecordCount} records processed", "Configuration loaded for environment {Environment}"
Use when ALL of these are true:
Examples: method entry with parameters, configuration values loaded, state transition details, decision branch taken, DAL properties initialized, template execution results
Use when ANY of these are true:
Examples: "SQL block {Block}/{Total}:\n{SqlContent}", "File content:\n{Content}", complete configuration dumps, per-iteration processing details
| Question | If YES | If NO |
|---|---|---|
| Did the operation FAIL completely? | Error (or Critical if unrecoverable) | Warning or lower |
| Is the message about something UNEXPECTED? | Warning | Info or lower |
| Does an ops team need this in production? | Info | Debug or lower |
| Is this a summary or decision point? | Debug | Trace (full dump) |
The skill actively identifies where logging is missing and adds appropriate statements. Use these criteria to decide what new logging to add:
| What to log | Level | When to add |
|---|---|---|
| Method entry with key parameters | Debug | Public/exported methods in service, business, or infrastructure classes. Do NOT add to trivial getters/setters, pure utility functions, or simple property accessors. |
| Method exit with result summary | Debug | Methods with non-trivial return values that represent a computation, query result, or decision. Not for simple pass-through methods. |
| Exception in catch block | Error or Warning | Error if the exception is handled and NOT re-thrown (this is where it must be logged). Warning if re-thrown but additional context is added that the caller does not have. Do NOT log if the exception is simply re-thrown without added context (the caller or a global handler will log it). |
| State transition | Debug | State machine changes, status enum updates, flag toggles. Include both old and new state values. |
| External system call | Debug | Before DB queries, HTTP requests, file I/O operations, process starts, message queue operations. Include the key identifying parameter (table name, URL, file path, etc.). |
| Business operation start | Info | Beginning of a meaningful business operation (not every method, but operations like "starting migration", "beginning import", "processing batch"). |
| Business operation completion | Info | Successful end of a business operation, with summary metrics (count of items processed, duration if relevant). |
| Configuration loaded | Debug | After configuration is parsed and validated. Log relevant non-sensitive values. Use masking for sensitive data if the project supports it. |
| Retry / fallback activated | Warning | When a retry path or fallback mechanism is activated. Include attempt number, reason, and whether it succeeded. |
| Loop iteration (important loops) | Trace | In batch processing or migration loops where per-item tracking aids diagnosis. Include iteration index and item identifier. Do NOT add to tight inner loops or performance-critical paths. |
| Validation failure | Warning or Debug | Warning for business rule violations that a user or operator should notice. Debug for technical validation (type checks, null guards) that only aids development. |
| Decision point | Debug or Trace | Debug for business-relevant branching (which execution path was chosen and why). Trace for algorithmic branching with high volume. |
Before writing any new log statement, verify it follows ALL detected conventions:
--lang