reidmorrison / rails_semantic_logger

Rails Semantic Logger replaces the Rails default logger with Semantic Logger
https://logger.rocketjob.io/rails
Apache License 2.0
330 stars 117 forks source link

Logging user_id on log_tags #103

Closed truongnmt closed 3 years ago

truongnmt commented 4 years ago

Environment

Provide at least:

With regard to the Name Tags:

Named Tags Named tags can be added to every log message on a per web request basis, by overriding the Rails built-in config.log_tags with a hash value.

I want to add user_id to every log message

config.log_tags = {
  user_id: -> controller.current_user_id.present? "#{controller.current_user_id}" : 'guest'
}

However, it seems that I can't access the controller in there.

Adding custom data to the Rails Completed log message During Controller-action processing custom data can be added to the Rails Completed message.

To access controller we can use payload but I want to add this information on every log. Not just custom data. It's something in between Named Tags (added on every log message) and Payload (controller accessible).

It would be nice if I can add an additional log to Rails's default system log. 🤔

reidmorrison commented 4 years ago

Unfortunately this is a limitation of the way Rails does log tags. In our application we use the following to workaround this limitation:

    config.log_tags = {
      request_id:      :uuid,
      ip:              :remote_ip,
      amzn_trace_id:   -> request { request.headers["X-Amzn-Trace-ID"] },
      incap_req_id:    -> request { request.headers["INCAP-Req-ID"] },
      login:           -> request { request.cookie_jar['login'] }
    }
reidmorrison commented 4 years ago

log_tags are resolved long before the controller is created, so it is not possible to access the eventual controller at that point in time. You could use the Controller around feature to add named tags around all of the controller actions.

truongnmt commented 3 years ago

Ah thanks! By implementing append_info_to_payload we could add custom data to its payload from any controller. Rails support this: https://apidock.com/rails/v6.0.0/ActionController/Instrumentation/append_info_to_payload

Also written in our doc:

Adding custom data to the Rails Completed log message: https://rocketjob.github.io/semantic_logger/rails.html

Just make sure to implement this method in the base controller of all requests. That's very close and enough to my original purposes. Adding to log_tags seems a bit difficult, I should read the docs more carefully. Thanks very much!!!

maxivak commented 3 years ago

link https://rocketjob.github.io/semantic_logger/rails.html is broken

reidmorrison commented 2 years ago

This is the latest url: https://logger.rocketjob.io/rails.html