如何将具体的请求细节记录到rails服务器日志 [英] How to log specific request details to rails server logs
问题描述
我通常不喜欢直接询问如何做某些事情,而不了解发生了什么,但我对rails很新,而且我很难完成这项工作。
基本上,我需要在单个日志语句中捕获每个请求的以下信息(如果可能)
自定义日志格式的首选方式是什么?是否可以修改现有日志并将这些信息传递给它?或者我需要扩展并覆盖我需要的行为?
我不需要将其保存到其他日志文件或任何内容,只需将其输出到STDOUT即可每个请求。
任何帮助都将不胜感激。
谢谢!
我相信大部分(如果不是全部)您请求的信息都可以在请求头文件和响应中找到。有关如何将其添加到日志的信息已在 之前回答,但基本上,您可以在ApplicationController中使用 around_filter 来记录您关心的信息形成请求标头。例如,下面是如何从响应中的请求和状态代码中记录用户代理:
class ApplicationController< ActionController :: Base
around_filter:global_request_logging
def global_request_logging
logger.infoUSERAGENT:#{request.headers ['HTTP_USER_AGENT']}
begin
收益
保证
logger.inforesponse_status:#{response.status}
end
end
end
至于获取所需的格式,如果打包调用,则可以输出任何您想要的格式。此外,Rails记录器也是非常可定制的,并且有一些项目已经存在,可能适合您的需要以取代默认日志记录或作为如何创建有用格式的灵感:
I typically don't like to ask directly how to do something without much understanding of what's going on, but I'm fairly new to rails and I'm having a hard time accomplishing this.
Basically, I need to capture the following information for each request in a single log statement (if possible)
What's the preferred way of customizing the log format? Is it possible to just modify the existing logs and pass it this information? Or would I need to extend and overwrite the behavior I need?
I don't need this to be saved to a different log file or anything, just output to STDOUT on each request.
Any help with this would be greatly appreciated.
Thanks!
I believe most, if not all, of the info you requested can be found in the request headers and response. Information on how to add that to logs has been answered before, but basically you can use an around_filter in the ApplicationController to log the information you care about form the request headers. For example here's how you could log the user agent from the request and status code from the response:
class ApplicationController < ActionController::Base
around_filter :global_request_logging
def global_request_logging
logger.info "USERAGENT: #{request.headers['HTTP_USER_AGENT']}"
begin
yield
ensure
logger.info "response_status: #{response.status}"
end
end
end
As far as getting the format you want, if you wrap calls you can output whatever format you want. Also, the Rails logger is also very customizable, and a few projects already exist that might suit your needs to replace default logging or as inspiration for how to go about creating a useful format:
- lograge - replaces default Rails logging with single line, key-value output, but doesn't yet do request parameters
- scrolls - More generic contextual, key-value
这篇关于如何将具体的请求细节记录到rails服务器日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!