Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Rails 4 and structured logging, how can I add the request id field to logs?

I am adding structured logging to a Rails 4 app. Using lograge and logstash-logger as describe in this article, I've got things mostly working.

I'm having trouble adding request id to the logs. The closest I've found is to add this to config/${ENV}.rb:

config.log_tags = [:uuid]

But this adds the request id to the tags list, instead of adding it as a named field.

{
  "tags": [
    "da76b4be-01ae-4cc4-8d3c-87062ea02cfe"
  ],
  "host": "services",
  "severity": "DEBUG",
  "@version": "1",
  "@timestamp": "2016-09-13T17:24:34.883+00:00",
  "message": "..."
}

This is problematic. It makes it more awkward and less obvious on how to search for a particular request id. Plus, parsing the message in logstash it overwrites any other tags that are already associated with the log message.

Is there any way that I can add the request id to the log as a named field?

{
  "request_id", "da76b4be-01ae-4cc4-8d3c-87062ea02cfe",
  "host": "services",
  "severity": "DEBUG",
  "@version": "1",
  "@timestamp": "2016-09-13T17:24:34.883+00:00",
  "message": "..."
}
like image 927
leedm777 Avatar asked Sep 13 '16 18:09

leedm777


1 Answers

Old question but maybe it will help someone like me who struggled to find a simple way to do this.

Using the custom_payload (instead of custom_options), you can directly access the request received by the controller and get its id to add it to the logs:

config.lograge.custom_payload do |controller|
  {
    request_id: controller.request.request_id
  }
end

No need to configure the log_tags for this to work.

like image 93
Ianlet Avatar answered Nov 02 '22 09:11

Ianlet