/
logger.rb
325 lines (297 loc) · 9.81 KB
/
logger.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# Defines our PADRINO_LOG_LEVEL
PADRINO_LOG_LEVEL = ENV['PADRINO_LOG_LEVEL'] unless defined?(PADRINO_LOG_LEVEL)
module Padrino
##
# Returns the padrino logger
#
# ==== Examples
#
# logger.debug "foo"
# logger.warn "bar"
#
def self.logger
Thread.current[:padrino_logger] ||= Padrino::Logger.setup!
end
##
# Extensions to the built in Ruby logger.
#
# ==== Examples
#
# logger.debug "foo"
# logger.warn "bar"
#
class Logger
attr_accessor :level
attr_accessor :auto_flush
attr_reader :buffer
attr_reader :log
attr_reader :init_args
##
# Ruby (standard) logger levels:
#
# :fatal:: An unhandleable error that results in a program crash
# :error:: A handleable error condition
# :warn:: A warning
# :info:: generic (useful) information about system operation
# :debug:: low-level information for developers
#
Levels = {
:fatal => 7,
:error => 6,
:warn => 4,
:info => 3,
:debug => 0
} unless const_defined?(:Levels)
@@mutex = {}
##
# Configuration for a given environment, possible options are:
#
# :log_level:: Once of [:fatal, :error, :warn, :info, :debug]
# :stream:: Once of [:to_file, :null, :stdout, :stderr] our your custom stream
# :log_level::
# The log level from, e.g. :fatal or :info. Defaults to :debug in the
# production environment and :debug otherwise.
# :auto_flush::
# Whether the log should automatically flush after new messages are
# added. Defaults to true.
# :format_datetime:: Format of datetime. Defaults to: "%d/%b/%Y %H:%M:%S"
# :format_message:: Format of message. Defaults to: ""%s - - [%s] \"%s\"""
#
# ==== Examples
#
# Padrino::Logger::Config[:development] = { :log_level => :debug, :to_file }
# # or you can edit our defaults
# Padrino::Logger::Config[:development][:log_level] = :error
# # or you can use your stream
# Padrino::Logger::Config[:development][:stream] = StringIO.new
#
# Defaults are:
#
# :production => { :log_level => :warn, :stream => :to_file }
# :development => { :log_level => :debug, :stream => :stdout }
# :test => { :log_level => :fatal, :stream => :null }
#
Config = {
:production => { :log_level => :warn, :stream => :to_file },
:development => { :log_level => :debug, :stream => :stdout },
:test => { :log_level => :debug, :stream => :null }
}
# Embed in a String to clear all previous ANSI sequences.
CLEAR = "\e[0m"
# The start of an ANSI bold sequence.
BOLD = "\e[1m"
# Set the terminal's foreground ANSI color to black.
BLACK = "\e[30m"
# Set the terminal's foreground ANSI color to red.
RED = "\e[31m"
# Set the terminal's foreground ANSI color to green.
GREEN = "\e[32m"
# Set the terminal's foreground ANSI color to yellow.
YELLOW = "\e[33m"
# Set the terminal's foreground ANSI color to blue.
BLUE = "\e[34m"
# Set the terminal's foreground ANSI color to magenta.
MAGENTA = "\e[35m"
# Set the terminal's foreground ANSI color to cyan.
CYAN = "\e[36m"
# Set the terminal's foreground ANSI color to white.
WHITE = "\e[37m"
# Colors for levels
ColoredLevels = {
:fatal => [BOLD, RED],
:error => [RED],
:warn => [YELLOW],
:info => [GREEN],
:debug => [CYAN]
} unless defined?(ColoredLevels)
##
# Setup a new logger
#
def self.setup!
config_level = (PADRINO_LOG_LEVEL || Padrino.env || :test).to_sym # need this for PADRINO_LOG_LEVEL
config = Config[config_level]
stream = case config[:stream]
when :to_file
FileUtils.mkdir_p(Padrino.root("log")) unless File.exists?(Padrino.root("log"))
File.new(Padrino.root("log", "#{Padrino.env}.log"), "a+")
when :null then StringIO.new
when :stdout then $stdout
when :stderr then $stderr
else config[:stream] # return itself, probabilly is a custom stream.
end
Thread.current[:padrino_logger] = Padrino::Logger.new(config.merge(:stream => stream))
end
##
# To initialize the logger you create a new object, proxies to set_log.
#
# ==== Options
#
# :stream:: Either an IO object or a name of a logfile. Defaults to $stdout
# :log_level::
# The log level from, e.g. :fatal or :info. Defaults to :debug in the
# production environment and :debug otherwise.
# :auto_flush::
# Whether the log should automatically flush after new messages are
# added. Defaults to true.
# :format_datetime:: Format of datetime. Defaults to: "%d/%b/%Y %H:%M:%S"
# :format_message:: Format of message. Defaults to: ""%s - - [%s] \"%s\"""
#
def initialize(options={})
@buffer = []
@auto_flush = options.has_key?(:auto_flush) ? options[:auto_flush] : true
@level = options[:log_level] ? Levels[options[:log_level]] : Levels[:debug]
@log = options[:stream] || $stdout
@log.sync = true
@mutex = @@mutex[@log] ||= Mutex.new
@format_datetime = options[:format_datetime] || "%d/%b/%Y %H:%M:%S"
@format_message = options[:format_message] || "%s - [%s] \"%s\""
end
##
# Colorize our level
#
def colored_level(level)
style = ColoredLevels[level.to_s.downcase.to_sym].join("")
"#{style}#{level.to_s.upcase.rjust(7)}#{CLEAR}"
end
##
# Set a color for our string. Color can be a symbol/string
#
def set_color(string, color, bold=false)
color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
bold = bold ? BOLD : ""
"#{bold}#{color}#{string}#{CLEAR}"
end
##
# Flush the entire buffer to the log object.
#
def flush
return unless @buffer.size > 0
@mutex.synchronize do
@log.write(@buffer.slice!(0..-1).join(''))
end
end
##
# Close and remove the current log object.
#
def close
flush
@log.close if @log.respond_to?(:close) && !@log.tty?
@log = nil
end
##
# Appends a message to the log. The methods yield to an optional block and
# the output of this block will be appended to the message.
#
def push(message = nil, level = nil)
self << @format_message % [colored_level(level), set_color(Time.now.strftime(@format_datetime), :yellow), message.to_s.strip]
end
##
# Directly append message to the log.
#
def <<(message = nil)
message << "\n" unless message[-1] == ?\n
@buffer << message
flush if @auto_flush
message
end
##
# Generate the logging methods for Padrino.logger for each log level.
#
Levels.each_pair do |name, number|
class_eval <<-LEVELMETHODS, __FILE__, __LINE__
# Appends a message to the log if the log level is at least as high as
# the log level of the logger.
#
# ==== Parameters
# message:: The message to be logged. Defaults to nil.
#
# ==== Returns
# self:: The logger object for chaining.
def #{name}(message = nil)
if #{number} >= level
message = block_given? ? yield : message
self.push(message, :#{name}) if #{number} >= level
end
self
end
# Appends a message to the log if the log level is at least as high as
# the log level of the logger. The bang! version of the method also auto
# flushes the log buffer to disk.
#
# ==== Parameters
# message:: The message to be logged. Defaults to nil.
#
# ==== Returns
# self:: The logger object for chaining.
def #{name}!(message = nil)
if #{number} >= level
message = block_given? ? yield : message
self.push(message, :#{name}) if #{number} >= level
flush if #{number} >= level
end
self
end
# ==== Returns
# Boolean:: True if this level will be logged by this logger.
def #{name}?
#{number} >= level
end
LEVELMETHODS
end
##
# Padrino::Loggger::Rack forwards every request to an +app+ given, and
# logs a line in the Apache common log format to the +logger+, or
# rack.errors by default.
#
class Rack
##
# Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common
# "lilith.local - - GET / HTTP/1.1 500 -"
# %{%s - %s %s %s%s %s - %d %s %0.4f}
#
FORMAT = %{%s - %s %s %s%s%s %s - %d %s %0.4f}
def initialize(app, uri_root)
@app = app
@uri_root = uri_root.sub(/\/$/,"")
end
def call(env)
began_at = Time.now
status, header, body = @app.call(env)
log(env, status, header, began_at)
[status, header, body]
end
private
def log(env, status, header, began_at)
now = Time.now
length = extract_content_length(header)
logger.debug FORMAT % [
env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"] || "-",
env["REMOTE_USER"] || "-",
env["REQUEST_METHOD"],
@uri_root || "",
env["PATH_INFO"],
env["QUERY_STRING"].empty? ? "" : "?" + env["QUERY_STRING"],
env["HTTP_VERSION"],
status.to_s[0..3],
length,
now - began_at ]
end
def extract_content_length(headers)
headers.each do |key, value|
if key.downcase == 'content-length'
return value.to_s == '0' ? '-' : value
end
end
'-'
end
end # Rack
end # Logger
end # Padrino
module Kernel #:nodoc:
##
# Define a logger available every where in our app
#
def logger
Padrino.logger
end
end # Kernel