4 use Psr\Http\Message\MessageInterface;
5 use Psr\Http\Message\RequestInterface;
6 use Psr\Http\Message\ResponseInterface;
9 * Formats log messages using variable substitutions for requests, responses,
10 * and other transactional data.
12 * The following variable substitutions are supported:
14 * - {request}: Full HTTP request message
15 * - {response}: Full HTTP response message
16 * - {ts}: ISO 8601 date in GMT
17 * - {date_iso_8601} ISO 8601 date in GMT
18 * - {date_common_log} Apache common log date using the configured timezone.
19 * - {host}: Host of the request
20 * - {method}: Method of the request
21 * - {uri}: URI of the request
22 * - {host}: Host of the request
23 * - {version}: Protocol version
24 * - {target}: Request target of the request (path + query + fragment)
25 * - {hostname}: Hostname of the machine that sent the request
26 * - {code}: Status code of the response (if available)
27 * - {phrase}: Reason phrase of the response (if available)
28 * - {error}: Any error messages (if available)
29 * - {req_header_*}: Replace `*` with the lowercased name of a request header to add to the message
30 * - {res_header_*}: Replace `*` with the lowercased name of a response header to add to the message
31 * - {req_headers}: Request headers
32 * - {res_headers}: Response headers
33 * - {req_body}: Request body
34 * - {res_body}: Response body
36 class MessageFormatter
39 * Apache Common Log Format.
40 * @link http://httpd.apache.org/docs/2.4/logs.html#common
43 const CLF = "{hostname} {req_header_User-Agent} - [{date_common_log}] \"{method} {target} HTTP/{version}\" {code} {res_header_Content-Length}";
44 const DEBUG = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}";
45 const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}';
47 /** @var string Template used to format log messages */
51 * @param string $template Log message template
53 public function __construct($template = self::CLF)
55 $this->template = $template ?: self::CLF;
59 * Returns a formatted message string.
61 * @param RequestInterface $request Request that was sent
62 * @param ResponseInterface $response Response that was received
63 * @param \Exception $error Exception that was received
67 public function format(
68 RequestInterface $request,
69 ResponseInterface $response = null,
70 \Exception $error = null
74 return preg_replace_callback(
75 '/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
76 function (array $matches) use ($request, $response, $error, &$cache) {
78 if (isset($cache[$matches[1]])) {
79 return $cache[$matches[1]];
83 switch ($matches[1]) {
85 $result = Psr7\str($request);
88 $result = $response ? Psr7\str($response) : '';
91 $result = trim($request->getMethod()
92 . ' ' . $request->getRequestTarget())
93 . ' HTTP/' . $request->getProtocolVersion() . "\r\n"
94 . $this->headers($request);
100 $response->getProtocolVersion(),
101 $response->getStatusCode(),
102 $response->getReasonPhrase()
103 ) . "\r\n" . $this->headers($response)
107 $result = $request->getBody();
110 $result = $response ? $response->getBody() : 'NULL';
113 case 'date_iso_8601':
114 $result = gmdate('c');
116 case 'date_common_log':
117 $result = date('d/M/Y:H:i:s O');
120 $result = $request->getMethod();
123 $result = $request->getProtocolVersion();
127 $result = $request->getUri();
130 $result = $request->getRequestTarget();
133 $result = $request->getProtocolVersion();
137 ? $response->getProtocolVersion()
141 $result = $request->getHeaderLine('Host');
144 $result = gethostname();
147 $result = $response ? $response->getStatusCode() : 'NULL';
150 $result = $response ? $response->getReasonPhrase() : 'NULL';
153 $result = $error ? $error->getMessage() : 'NULL';
156 // handle prefixed dynamic headers
157 if (strpos($matches[1], 'req_header_') === 0) {
158 $result = $request->getHeaderLine(substr($matches[1], 11));
159 } elseif (strpos($matches[1], 'res_header_') === 0) {
161 ? $response->getHeaderLine(substr($matches[1], 11))
166 $cache[$matches[1]] = $result;
173 private function headers(MessageInterface $message)
176 foreach ($message->getHeaders() as $name => $values) {
177 $result .= $name . ': ' . implode(', ', $values) . "\r\n";
180 return trim($result);