Logging git commits with a git hook
git logging scripts howto
2024-09-09
Similar to my previous post (more than a year ago!) about using Git hooks to enforce conventional commits, I wanted to start logging all of my commits. This is part of a larger project to keep a better work diary, but I wanted to start with something simple and unobtrustive, and this seemed like a simple place to start.
We need to create a global hooks folder, and enable it.
$ mkdir $HOME/.git_hooks
$ git config --global core.hooksPath ~/.git_hooks
Using the post-commit
hook is the most sensible place for this, so we'll create the hook and make it executable:
$ touch $HOME/.git_hooks/post-commit
$ chmod +x $HOME/.git_hooks/post-commit
The contents of that script:
#!/bin/bash
# Get the commit message.
commit_message=$(git log -1 --pretty=%B)
# Get the repository name using git rev-parse.
repo_name=$(git rev-parse --show-toplevel | xargs basename)
# Get the current datestamp.
datestamp=$(date +"%Y-%m-%d %H:%M:%S")
# Log the information to the .git_log file in the home directory.
echo "$datestamp | $repo_name | $commit_message" >> "$HOME/.git_log"
# Some positive output.
echo "Logged commit."
exit 0
The code is also available from this gist. Here's the copy/paste installer:
$ curl https://gist.githubusercontent.com/jonatkinson/71db4672fc74c98a66cf7163fc38706b/raw/2dd8b0a583a1fddb203af43f09edeb3193f1d8fb/commit-log > $HOME/.git_hooks/post-commit && chmod +x $HOME/.git_hooks/post-commit