1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2016 Alexandre Terrasa <alexandre@moz-code.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
23 # Initialize a clock for the resquest.
25 # Can be used to compute the time passed to respond that request.
29 redef fun all
(req
, res
) do req
.clock
= new Clock
32 # Display log info about request processing.
37 # Do we want colors in the console output?
38 var no_color
= false is optional
40 redef var default_formatter
= new PopFormatter(no_color
) is optional
42 redef fun all
(req
, res
) do
45 add_raw
(info_level
, "{req.method} {req.url} {status(res)} ({clock.total}s)")
47 add_raw
(info_level
, "{req.method} {req.url} {status(res)}")
51 # Colorize the request status.
52 private fun status
(res
: HttpResponse): String do
53 if no_color
then return res
.status_code
.to_s
54 return res
.color_status
61 # Do not decorate messages with colors
62 var no_color
= false is optional
, writable
64 redef fun format
(level
, message
) do
65 var string
= message
.write_to_string
67 if level
== fatal_level
then
68 string
= "[FATAL] {string}"
69 else if level
== error_level
then
70 string
= "[ERROR] {string}"
71 else if level
== warn_level
then
72 string
= "[WARN] {string}"
73 else if level
== info_level
then
74 string
= "[INFO] {string}"
75 else if level
== debug_level
then
76 string
= "[DEBUG] {string}"
79 if no_color
then return string
81 if level
== fatal_level
then
83 else if level
== error_level
then
85 else if level
== warn_level
then
87 else if level
== info_level
then
89 else if level
== debug_level
then
98 redef class HttpRequest
99 # Time that request was received by the Popcorn app.
100 var clock
: nullable Clock = null
103 redef class HttpResponse
104 # Return `self` status colored for console.
105 fun color_status
: String do
106 if status_code
>= 100 and status_code
< 200 then return status_code
.to_s
.gray
107 if status_code
>= 200 and status_code
< 300 then return status_code
.to_s
.green
108 if status_code
>= 300 and status_code
< 400 then return status_code
.to_s
.blue
109 if status_code
>= 400 and status_code
< 500 then return status_code
.to_s
.yellow
110 if status_code
>= 500 and status_code
< 600 then return status_code
.to_s
.red
111 return status_code
.to_s