Console to Logger Codemod
This codemod transforms console.log and console.debug calls to use a custom logger instead. It's built using the Codemod platform with ast-grep's JavaScript (JSSG) codemod engine.
What it does
This codemod automatically transforms:
- console.log(...) → logger.log(...)
- console.debug(...) → logger.debug(...)
Examples
Before
typescript
After
typescript
Note that string literals containing console.log are not transformed - only actual function calls.
Project Structure
plaintext
Files Targeted
The codemod processes the following file types:
- .tsx - TypeScript React components
- .jsx - JavaScript React components
- .js - JavaScript files
- .ts - TypeScript files
- .cts - CommonJS TypeScript files
- .mts - ES Module TypeScript files
It excludes node_modules directories.
Technology
This codemod uses:
- Codemod Platform: Multi-file workflow engine for large-scale code transformations
- ast-grep JSSG: JavaScript/TypeScript codemod engine for precise AST transformations
- TypeScript: The transformation logic is written in TypeScript
How it works
- The workflow engine (workflow.yaml) defines which files to process and how to run the transformation
- The JSSG codemod (codemod/main-codemod.ts) uses ast-grep to:
- Find all console.log($ARG) patterns in the code
- Find all console.debug($ARG) patterns in the code
- Replace them with logger.log($ARG) and logger.debug($ARG) respectively
- Preserve the original arguments and formatting
Running the Codemod
This codemod is designed to run on the Codemod platform. The workflow configuration handles:
- File discovery and filtering
- Running the transformation across multiple files
- Applying changes safely with proper error handling
Prerequisites
Before running this codemod, ensure your codebase:
- Has a logger object available in scope where console.log and console.debug are used
- The logger object has log and debug methods with compatible signatures
You may need to add logger imports or configure your logging infrastructure before applying this transformation.
Limitations
- Only transforms direct console.log and console.debug calls
- Does not transform other console methods like console.error, console.warn, etc.
- Assumes a logger object is available in scope
- String literals containing "console.log" are not transformed (by design)
Extending the Codemod
To add support for additional console methods, modify codemod/main-codemod.ts:
typescript