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 * - {version}: Protocol version
23 * - {target}: Request target of the request (path + query + fragment)
24 * - {hostname}: Hostname of the machine that sent the request
25 * - {code}: Status code of the response (if available)
26 * - {phrase}: Reason phrase of the response (if available)
27 * - {error}: Any error messages (if available)
28 * - {req_header_*}: Replace `*` with the lowercased name of a request header to add to the message
29 * - {res_header_*}: Replace `*` with the lowercased name of a response header to add to the message
30 * - {req_headers}: Request headers
31 * - {res_headers}: Response headers
32 * - {req_body}: Request body
33 * - {res_body}: Response body
35 class MessageFormatter
38 * Apache Common Log Format.
39 * @link http://httpd.apache.org/docs/2.4/logs.html#common
42 const CLF = "{hostname} {req_header_User-Agent} - [{date_common_log}] \"{method} {target} HTTP/{version}\" {code} {res_header_Content-Length}";
43 const DEBUG = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}";
44 const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}';
46 /** @var string Template used to format log messages */
50 * @param string $template Log message template
52 public function __construct($template = self::CLF)
54 $this->template = $template ?: self::CLF;
58 * Returns a formatted message string.
60 * @param RequestInterface $request Request that was sent
61 * @param ResponseInterface $response Response that was received
62 * @param \Exception $error Exception that was received
66 public function format(
67 RequestInterface $request,
68 ResponseInterface $response = null,
69 \Exception $error = null
73 return preg_replace_callback(
74 '/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
75 function (array $matches) use ($request, $response, $error, &$cache) {
76 if (isset($cache[$matches[1]])) {
77 return $cache[$matches[1]];
81 switch ($matches[1]) {
83 $result = Psr7\str($request);
86 $result = $response ? Psr7\str($response) : '';
89 $result = trim($request->getMethod()
90 . ' ' . $request->getRequestTarget())
91 . ' HTTP/' . $request->getProtocolVersion() . "\r\n"
92 . $this->headers($request);
98 $response->getProtocolVersion(),
99 $response->getStatusCode(),
100 $response->getReasonPhrase()
101 ) . "\r\n" . $this->headers($response)
105 $result = $request->getBody();
108 $result = $response ? $response->getBody() : 'NULL';
111 case 'date_iso_8601':
112 $result = gmdate('c');
114 case 'date_common_log':
115 $result = date('d/M/Y:H:i:s O');
118 $result = $request->getMethod();
121 $result = $request->getProtocolVersion();
125 $result = $request->getUri();
128 $result = $request->getRequestTarget();
131 $result = $request->getProtocolVersion();
135 ? $response->getProtocolVersion()
139 $result = $request->getHeaderLine('Host');
142 $result = gethostname();
145 $result = $response ? $response->getStatusCode() : 'NULL';
148 $result = $response ? $response->getReasonPhrase() : 'NULL';
151 $result = $error ? $error->getMessage() : 'NULL';
154 // handle prefixed dynamic headers
155 if (strpos($matches[1], 'req_header_') === 0) {
156 $result = $request->getHeaderLine(substr($matches[1], 11));
157 } elseif (strpos($matches[1], 'res_header_') === 0) {
159 ? $response->getHeaderLine(substr($matches[1], 11))
164 $cache[$matches[1]] = $result;
171 private function headers(MessageInterface $message)
174 foreach ($message->getHeaders() as $name => $values) {
175 $result .= $name . ': ' . implode(', ', $values) . "\r\n";
178 return trim($result);