DEV Community

Cover image for Profile arbitrary code in prod console
Augusts Bautra
Augusts Bautra

Posted on • Edited on

2 1

Profile arbitrary code in prod console

Include stackprof in gemfile

gem "stackprof", ">= 0.2.26", require: false
Enter fullscreen mode Exit fullscreen mode

Require stackprof and run slow code in its block

require "stackprof"

def profile!
  profile =
    StackProf.run(ignore_gc: true, interval: 1000, mode: :wall, raw: true) do
      @value = # slow code
    end

  output_file = Rails.root.join("log/stackprof.json")  
  File.write(output_file, JSON.generate(profile))

  @value # return the original  
end

profile!
Enter fullscreen mode Exit fullscreen mode

DL the file to local computer

scp PROD:/path/to/log/stackprof.json ~/Desktop/profile.json
Enter fullscreen mode Exit fullscreen mode

Upload the file to https://www.speedscope.app and study flamegraph

Addendum

You can simplify accessing the file somewhat by writing it into Rails' public/ directory to have access it via the web-server.

For example

output_file = Rails.root.join("public/stackprof.json")
Enter fullscreen mode Exit fullscreen mode

Will be accessible at https://<your.site>/stackprof.json. Be mindful of security risks.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay