Back to code Ruby

Resumir un log de accesos: códigos de estado y pedidos lentos

Quince líneas que leen un log sin cargarlo entero en memoria y dicen cuántos errores hubo y cuáles fueron los pedidos más lentos.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

El sitio anduvo lento anoche y hay un log de doscientos megas. Antes de montar una herramienta, hace falta una respuesta rápida: cuántos errores y qué rutas tardaron.

Ruby
conteo = Hash.new(0)
lentas = []

File.foreach(ARGV[0] || "access.log") do |linea|
  # formato: 2026-03-01T10:30:00 GET /pedidos 200 0.182
  _fecha, metodo, ruta, estado, segundos = linea.split
  next unless estado
  conteo[estado] += 1
  lentas << [segundos.to_f, metodo, ruta] if segundos.to_f > 1.0
end

conteo.sort.each { |estado, n| puts "#{estado}: #{n}" }
puts "\nLas 5 más lentas:"
lentas.max(5).each { |s, m, r| puts format("  %.2fs  %s %s", s, m, r) }

Why it is written this way

  1. File.foreach lee línea por línea: el archivo nunca está entero en memoria, pese doscientos megas o veinte gigas.
  2. Hash.new(0) arranca cada contador en cero, así que conteo[estado] += 1 funciona sin preguntar si la clave existe.
  3. La asignación múltiple reparte las columnas de la línea en variables con nombre.
  4. max(5) sobre arreglos compara por el primer elemento: los segundos.
How to try it

Guardalo como resumen.rb y corré: ruby resumen.rb access.log. Si tu log tiene otro formato, ajustá el orden de las variables.

Watch out

split por espacios se rompe si la ruta o el agente de usuario traen espacios. Para logs de Apache o Nginx reales conviene una expresión regular con el formato exacto.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo este script de Ruby que resume un log de accesos. Mi log tiene este formato real: [TRES LÍNEAS DE EJEMPLO]. Adaptalo con una expresión regular para ese formato y agregá: pedidos por hora, las diez rutas con más errores 5xx y el percentil 95 del tiempo de respuesta. Que siga leyendo línea por línea sin cargar el archivo en memoria.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.