1 | <?php |
||
11 | class AccessLog |
||
12 | { |
||
13 | use Utils\AttributeTrait; |
||
14 | |||
15 | /** |
||
16 | * @var LoggerInterface The router container |
||
17 | */ |
||
18 | private $logger; |
||
19 | |||
20 | /** |
||
21 | * @var bool |
||
22 | */ |
||
23 | private $combined = false; |
||
24 | |||
25 | /** |
||
26 | * Set the LoggerInterface instance. |
||
27 | * |
||
28 | * @param LoggerInterface $logger |
||
29 | */ |
||
30 | public function __construct(LoggerInterface $logger) |
||
34 | |||
35 | /** |
||
36 | * Whether use the combined log format instead the common log format. |
||
37 | * |
||
38 | * @param bool $combined |
||
39 | * |
||
40 | * @return self |
||
41 | */ |
||
42 | public function combined($combined = true) |
||
48 | |||
49 | /** |
||
50 | * Execute the middleware. |
||
51 | * |
||
52 | * @param ServerRequestInterface $request |
||
53 | * @param ResponseInterface $response |
||
54 | * @param callable $next |
||
55 | * |
||
56 | * @return ResponseInterface |
||
57 | */ |
||
58 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
59 | { |
||
60 | if (!self::hasAttribute($request, ClientIp::KEY)) { |
||
61 | throw new RuntimeException('AccessLog middleware needs ClientIp executed before'); |
||
62 | } |
||
63 | |||
64 | $response = $next($request, $response); |
||
65 | $message = $this->combined ? self::combinedFormat($request, $response) : self::commonFormat($request, $response); |
||
66 | |||
67 | if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 600) { |
||
68 | $this->logger->error($message); |
||
69 | } else { |
||
70 | $this->logger->info($message); |
||
71 | } |
||
72 | |||
73 | return $response; |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Generates a message using the Apache's Common Log format |
||
78 | * https://httpd.apache.org/docs/2.4/logs.html#accesslog. |
||
79 | * |
||
80 | * Note: The user identifier (identd) is ommited intentionally |
||
81 | * |
||
82 | * @param ServerRequestInterface $request |
||
83 | * @param ResponseInterface $response |
||
84 | * |
||
85 | * @return string |
||
86 | */ |
||
87 | private static function commonFormat(ServerRequestInterface $request, ResponseInterface $response) |
||
101 | |||
102 | /** |
||
103 | * Generates a message using the Apache's Combined Log format |
||
104 | * This is exactly the same than Common Log, with the addition of two more fields: Referer and User-Agent headers. |
||
105 | * |
||
106 | * @param ServerRequestInterface $request |
||
107 | * @param ResponseInterface $response |
||
108 | * |
||
109 | * @return string |
||
110 | */ |
||
111 | private static function combinedFormat(ServerRequestInterface $request, ResponseInterface $response) |
||
119 | } |
||
120 |