Git: Visualizando os registros do Git e acompanhando o…

O histórico de commits registra todas as alterações feitas em um projeto e é o principal valor do controle de versão. Ao examinar esse histórico, é possível compreender a evolução do projeto, rastrear a origem dos problemas e analisar a trajetória do desenvolvimento.

1. Conceitos básicos de registro em log

(1) O que é o histórico de commits?

O histórico de commits é um registro cronológico de todos os commits e inclui:

100%
graph TB
    A[Latest Submissions<br/>HEAD] --> B[SubmitC3<br/>a1b2c3d]
    B --> C[SubmitC2<br/>d4e5f6g]
    C --> D[SubmitC1<br/>h7i8j9k]
    D --> E[Initial Submission<br/>l0m1n2o]
    
    style A fill:#d4edda
    style E fill:#fff3cd

(2) O papel da história

(3) Comando git log

git log é o comando principal para visualizar o histórico de commits e oferece uma ampla variedade de opções para personalizar a saída.


2. Visualização de registros básicos

(1) Ver histórico completo

▶ Exemplo: Visualizar o histórico de commits

BASH
# View Full History
git log

# Output Format:
# commit a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
# Author: Zhang San <zhangsan@example.com>
# Date:   Mon Jan 1 10:00:00 2026 +0800
#
#     feat: Add User Login Functionality
#
# commit d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2
# Author: Li Si <lisi@example.com>
# Date:   Sun Dec 31 15:30:00 2025 +0800
#
#     fix: Fix the login authentication error

(2) Modo compacto

▶ Exemplo: Exibição concisa

BASH
# One commit per line
git log --oneline

# Output:
# a1b2c3d feat: Add User Login Functionality
# d4e5f6g fix: Fix the login authentication error
# h7i8j9k docs: UpdateREADME
# l0m1n2o Initial commit

# Abbreviated form
git log --oneline --decorate

# Output:
# a1b2c3d (HEAD -> main) feat: Add User Login Functionality
# d4e5f6g (origin/main) fix: Fix the login authentication error

(3) Limitar o número de itens exibidos

▶ Exemplo: Limitando o número de itens exibidos

BASH
# Show Recent3Next Submission
git log -3

# Or
git log -n 3

# Simplified Mode: Show Recent 5
git log --oneline -5

# Output:
# a1b2c3d feat: Add User Login Functionality
# d4e5f6g fix: Fix the login authentication error
# h7i8j9k docs: UpdateREADME
# k9l0m1n style: Code Formatting
# n2o3p4q refactor: Optimize Query Logic

3. Saída formatada do log

(1) Opções de formatação

Opção Descrição Finalidade
--oneline Modo simplificado Histórico de navegação rápida
--stat Mostrar estatísticas Ver estatísticas de alterações no arquivo
-p Mostrar diferenças Ver alterações específicas
--graph Exibição gráfica Visualizar histórico de fusões de ramificações
--decorate Mostrar referências Visualizar referências de ramificações e tags

▶ Exemplo: Exibição de estatísticas

BASH
# Display File Change Statistics
git log --stat

# Output:
# commit a1b2c3d4e5f6...
# Author: Zhang San <zhangsan@example.com>
# Date:   Mon Jan 1 10:00:00 2026 +0800
#
#     feat: Add User Login Functionality
#
#  src/auth/login.js | 25 +++++++++++++++++++++++++
#  src/auth/index.js  |  3 ++-
#  2 files changed, 26 insertions(+), 2 deletions(-)

(2) Mostrar todas as diferenças

▶ Exemplo: Visualizando as diferenças entre commits

BASH
# Show the full diff for each commit
git log -p

# Show the differences from the most recent commit
git log -1 -p

# Output:
# commit a1b2c3d4e5f6...
# Author: Zhang San <zhangsan@example.com>
# Date:   Mon Jan 1 10:00:00 2026 +0800
#
#     feat: Add User Login Functionality
#
# diff --git a/src/auth/login.js b/src/auth/login.js
# new file mode 100644
# index 0000000..abc1234
# --- /dev/null
# +++ b/src/auth/login.js
# @@ -0,0 +1,25 @@
# +function login(username, password) {
# +  // Validation Logic
# +}

(3) Formatos personalizados

▶ Exemplo: Formato de saída personalizado

BASH
# Use a preset format
git log --pretty=oneline
git log --pretty=short
git log --pretty=full
git log --pretty=fuller

# Custom Format
git log --pretty=format:"%h - %an, %ar : %s"

# Output:
# a1b2c3d - Zhang San, 2 hours ago : feat: Add User Login Functionality
# d4e5f6g - Li Si, 1 day ago : fix: Fix the login authentication error

# A more detailed format
git log --pretty=format:"%C(yellow)%h%C(reset) - %C(green)%an%C(reset), %C(blue)%ar%C(reset) : %s"

# Table Format
git log --pretty=format:"%h | %an | %ad | %s" --date=short

# Output:
# a1b2c3d | Zhang San | 2026-01-01 | feat: Add User Login Functionality
# d4e5f6g | Li Si | 2025-12-31 | fix: Fix the login authentication error

(4) Espaços reservados de formatação

Espaço reservado Descrição Exemplo de saída
%H Hash completo a1b2c3d4e5f6...
%h Hash curto a1b2c3d
%an Nome do autor Zhang San
%ae E-mail do autor zhangsan@example.com
%ad Autor Data Seg, 1º de janeiro, 10:00:00, 2026
%ar Autor Data (relativa) 2 horas atrás
%s Enviar informações feat: Adicionar um recurso
%d Nome de referência (HEAD -> main)

4. Filtragem e consulta de logs

(1) Filtrar por data

▶ Exemplo: Filtragem por intervalo de tempo

BASH
# After the specified date
git log --since="2026-01-01"

# Before the specified date
git log --until="2026-01-31"

# Relative Time
git log --since="1 week ago"
git log --since="2 months ago"
git log --after="yesterday"

# Time Range
git log --since="2026-01-01" --until="2026-01-31"

# Combined Use
git log --oneline --since="1 week ago" --until="yesterday"

(2) Filtrar por autor

▶ Exemplo: Filtro por autor

BASH
# By Author Name
git log --author="Zhang San"

# By author's email address
git log --author="zhangsan@example.com"

# Fuzzy Matching
git log --author="Zhang"

# Combined Filtration
git log --author="Zhang San" --since="1 week ago"

(3) Filtrar por informações enviadas

▶ Exemplo: Pesquisa por informações de envio

BASH
# Search and Submit Information
git log --grep="fix"

# Multiple conditions(or relationship)
git log --grep="fix" --grep="feat"

# Regular Expressions
git log --grep="feat\|fix"

# Ignore case
git log --grep="FIX" -i

# Combined Filtration
git log --author="Zhang San" --grep="feat"

(4) Filtrar por arquivo

▶ Exemplo: Consulta do Histórico de Arquivos

BASH
# View the history of a specific file
git log -- README.md

# View Multiple Files
git log -- file1.js file2.js

# View Catalog History
git log -- src/auth/

# Show File Differences
git log -p -- README.md

# Display File Change Statistics
git log --stat -- README.md

# Show only commits that modified this file
git log --oneline -- README.md

# Output:
# a1b2c3d docs: UpdateREADME
# h7i8j9k docs: Add Installation Instructions
# l0m1n2o Initial commit

(5) Filtrar por escopo de envio

▶ Exemplo: Envio de uma consulta de intervalo

BASH
# View the history between two commits
git log a1b2c3d..d4e5f6g

# View the history following a specific commit
git log a1b2c3d..

# View the history leading up to a specific commit
git log ..d4e5f6g

# View Branch Differences
git log main..feature

# View the differences between the two branches
git log main...feature

5. Exibição gráfica

(1) Exibir o diagrama de ramificação

▶ Exemplo: Registro gráfico

BASH
# Display the branch merge diagram
git log --graph

# Common Combinations
git log --graph --oneline --all

# Output:
# *   a1b2c3d Merge branch 'feature'
# |\
# | * d4e5f6g Add feature
# * | b7c8d9e Fix bug
# |/
# * c0d1e2f Initial commit

# With decorative details
git log --graph --oneline --decorate --all

# Color Output
git log --graph --oneline --all --pretty=format:"%C(red)%h%C(reset) - %C(green)%s%C(reset)"

(2) Visualização do histórico do ramo

100%
gitGraph
    commit id: "Initial commit"
    commit id: "Add feature A"
    branch feature
    checkout feature
    commit id: "Feature work"
    checkout main
    commit id: "Fix bug"
    merge feature id: "Merge feature"
    commit id: "Release v1.0"

(3) Visualizar o histórico do ramo

▶ Exemplo: Histórico de ramificações

BASH
# View the history of all branches
git log --graph --oneline --all --decorate

# View the history of a specific branch
git log --graph --oneline feature

# View Branch Fork Points
git log --graph --oneline --simplify-by-decoration

# View the merged commit
git log --merges --oneline

# View Unmerged Commits
git log --no-merges --oneline

6. Técnicas avançadas de registro de logs

(1) Pesquisa binária

Use git bisect para identificar o commit que causou o problema:

▶ Exemplo: Solução para o problema da busca binária

BASH
# Start the binary search
git bisect start

# Mark the current commit as problematic
git bisect bad

# Mark a commit as normal
git bisect good v1.0.0

# GitIt will automatically switch to the middle submission
# Marked as good or bad after testing
git bisect good
# Or
git bisect bad

# After finding and submitting a bug
# a1b2c3d is the first bad commit

# End Binary Search
git bisect reset

(2) Visualizar o histórico de alterações do arquivo

▶ Exemplo: Análise do histórico de arquivos

BASH
# View the complete change history for the file
git log --follow -p -- filename

# View the revision history for each line of the file
git blame filename

# Output:
# a1b2c3d (Zhang San 2026-01-01 10:00:00  1) function login() {
# d4e5f6g (Li Si 2025-12-31 15:30:00  2)   // Validation Logic
# h7i8j9k (Zhang San 2025-12-30 09:00:00  3) }

# View the history for a specific row
git log -L 10,20:filename

# View Function History
git log -L :functionName:filename

(3) Registro de citações

▶ Exemplo: Visualizando o registro de citações

BASH
# ViewHEADMovement History
git reflog

# Output:
# a1b2c3d HEAD@{0}: commit: feat: Add Feature
# d4e5f6g HEAD@{1}: checkout: moving from feature to main
# h7i8j9k HEAD@{2}: commit: Feature work
# l0m1n2o HEAD@{3}: checkout: moving from main to feature

# View the history of a specific citation
git reflog show HEAD
git reflog show main

# Restore to the previous state
git reset HEAD@{5}

❓ Perguntas Frequentes

P: Como faço para visualizar o histórico de revisões de um arquivo?

R: Use git log -- <file> para visualizar o histórico de commits do arquivo, git log -p -- <file> para visualizar as alterações detalhadas e git blame <file> para visualizar as alterações em cada linha.

P: Como faço para ver as diferenças entre dois commits?

R: Use git log <commit1>..<commit2> para visualizar o histórico entre dois commits e use git diff <commit1> <commit2> para visualizar as diferenças em arquivos específicos.

P: Como faço para encontrar o commit que introduziu um determinado bug?

R: Use git bisect para realizar uma busca binária. Marque um commit que você sabe que está correto e outro que você sabe que apresenta um problema, e o Git identificará automaticamente o commit que causou o problema.

P: Qual é a diferença entre log e reflog?

R: git log exibe o histórico de commits, que é um registro da evolução do projeto; git reflog exibe o histórico das movimentações dos ramos, incluindo todas as operações, como commits, redefinições e checkouts — mesmo que um commit seja descartado, ele ainda pode ser encontrado no reflog.

P: Como faço para visualizar o histórico dos arquivos excluídos?

R: Use git log --all --full-history -- <file> para visualizar o histórico completo dos arquivos excluídos, incluindo as ações de exclusão.


📖 Resumo


📝 Exercícios

  1. Exercício básico: Use as diversas opções do git log para visualizar o histórico do projeto, incluindo o modo compacto, estatísticas e representações gráficas, e tente personalizar o formato de saída.

  2. Exercício avançado: Use as opções de filtro para localizar commits que atendam a critérios específicos, como: localizar commits da última semana, localizar todos os commits de um autor específico ou localizar commits cuja mensagem contenha “fix”.

  3. Desafio: Use git bisect para localizar o commit que introduziu um problema específico em um projeto com vários commits e experimente o poder da busca binária.

Web-Tutorial.com

Equipe Técnica Web-Tutorial

Uma plataforma de tutoriais mantida por diversos desenvolvedores. Cada tutorial é escrito e revisado por profissionais da área correspondente. Trabalhamos para manter nosso conteúdo preciso e confiável — se encontrar algum problema, avise-nos.

100%