Rails logger format string configuration

后端 未结 4 1427
余生分开走
余生分开走 2020-12-01 08:36

How can I configure the rails logger to output its log strings in another format? I would like to get something that is more informative like:

[Log Level] [Time] [Me

相关标签:
4条回答
  • 2020-12-01 08:51

    The problem with tags is that they clutter your logs to the point where they are unreadable.

    I'd recommend something like timber. It automatically augments your logs with context (level, time, session id, etc) without sacrificing readability.

    0 讨论(0)
  • 2020-12-01 08:53
    # config/initializers/rack_logger.rb
    module Rails
      module Rack
        class Logger < ActiveSupport::LogSubscriber
          # Add UserAgent
          def started_request_message(request)
             'Started %s "%s" for %s at %s by %s' % [
              request.request_method,
              request.filtered_path,
              request.ip,
              Time.now.to_default_s,
              request.env['HTTP_USER_AGENT'] ]
          end
        end
      end
    end
    

    source link

    0 讨论(0)
  • 2020-12-01 09:01

    For rails 4 apps, I've put together a simple gem that not only adds support for basic tagging like time stamp and log level, but even adds color to the log messages themselves.

    https://github.com/phallguy/shog

    0 讨论(0)
  • 2020-12-01 09:06

    Did some digging and found this post in the RubyOnRails Talk google group.

    So I modified it a little bit and put it at the end of my environment.rb:

    module ActiveSupport
      class BufferedLogger
        def add(severity, message = nil, progname = nil, &block)
          return if @level > severity
          message = (message || (block && block.call) || progname).to_s
    
          level = {
            0 => "DEBUG",
            1 => "INFO",
            2 => "WARN",
            3 => "ERROR",
            4 => "FATAL"
          }[severity] || "U"
    
          message = "[%s: %s #%d] %s" % [level,
                                         Time.now.strftime("%m%d %H:%M:%S"),
                                         $$,
                                         message]
    
          message = "#{message}\n" unless message[-1] == ?\n
          buffer << message
          auto_flush
          message
        end
      end
    end
    

    This results in a format string like this:

    [DEBUG: 0121 10:35:26 #57078] Rendered layouts/_header (0.00089)

    0 讨论(0)
提交回复
热议问题