DEV Community

Cover image for Console check before commit
Mitesh Kamat
Mitesh Kamat

Posted on

Console check before commit


This post is about adding a git hook to check for console.log statements before code commit.

Developers tend to log variables, objects, api response, etc while writing our code. And yes it is fair enough but once we are done with our piece of code we often forget to remove those statements while committing our code.

But Git hooks helps us here.

I faced the same issue of getting rid of all the log statements in my code. so, I decided to use git hooks.
There are various options , but I chose pre-git

You can go through the link to explore about it.

To start off with pre-git, once you install the npm package you would have a .git folder in root of your project directory. Now navigate to hooks folder and locate pre-commit file and copy the below mentioned script and save.



echo -e "\n${yellow}Executing pre-commit hook...${no_color}\n"


#check for console. references in your code

if git diff --cached --name-only | \
    grep -E $FILES_PATTERN | \
    xargs grep --with-filename -n $FORBIDDEN | \
    grep -v '//';
    echo -e "\n${red}COMMIT REJECTED!  Found console. references. Please remove them before committing.\n${no_color}"
    exit 1;
echo -e "${green}No console. references found!${no_color}\n"
echo -e "${green}Git pre-commit hook was successful!${no_color}\n"
exit 0;

This script just checks for console. statements present in your project and prompts with appropriate message.

Commit would be rejected if it encounters any console statements.

I hope you find this useful.

Cheers !!

Top comments (3)

rubenyebran profile image
Ruben Yebran

I have a question!
Should I replace the existing code with this one?
Or should I add it without removing the existing code?

miteshkamat27 profile image
Mitesh Kamat

If you have any other checks apart from console, then you should add this else you can replace.

nahukas profile image
Nahuel Castro

Hi! How can change the file extension to check js and jsx files?