4 * This file is part of the Monolog package.
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Monolog\Processor;
15 * Injects url/method and remote IP of the current web request in all records
17 * @author Jordi Boggiano <j.boggiano@seld.be>
22 * @var array|\ArrayAccess
24 protected $serverData;
29 * Array is structured as [key in record.extra => key in $serverData]
33 protected $extraFields = array(
34 'url' => 'REQUEST_URI',
35 'ip' => 'REMOTE_ADDR',
36 'http_method' => 'REQUEST_METHOD',
37 'server' => 'SERVER_NAME',
38 'referrer' => 'HTTP_REFERER',
42 * @param array|\ArrayAccess $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data
43 * @param array|null $extraFields Field names and the related key inside $serverData to be added. If not provided it defaults to: url, ip, http_method, server, referrer
45 public function __construct($serverData = null, array $extraFields = null)
47 if (null === $serverData) {
48 $this->serverData = &$_SERVER;
49 } elseif (is_array($serverData) || $serverData instanceof \ArrayAccess) {
50 $this->serverData = $serverData;
52 throw new \UnexpectedValueException('$serverData must be an array or object implementing ArrayAccess.');
55 if (null !== $extraFields) {
56 if (isset($extraFields[0])) {
57 foreach (array_keys($this->extraFields) as $fieldName) {
58 if (!in_array($fieldName, $extraFields)) {
59 unset($this->extraFields[$fieldName]);
63 $this->extraFields = $extraFields;
69 * @param array $record
72 public function __invoke(array $record)
74 // skip processing if for some reason request data
75 // is not present (CLI or wonky SAPIs)
76 if (!isset($this->serverData['REQUEST_URI'])) {
80 $record['extra'] = $this->appendExtraFields($record['extra']);
86 * @param string $extraName
87 * @param string $serverName
90 public function addExtraField($extraName, $serverName)
92 $this->extraFields[$extraName] = $serverName;
101 private function appendExtraFields(array $extra)
103 foreach ($this->extraFields as $extraName => $serverName) {
104 $extra[$extraName] = isset($this->serverData[$serverName]) ? $this->serverData[$serverName] : null;
107 if (isset($this->serverData['UNIQUE_ID'])) {
108 $extra['unique_id'] = $this->serverData['UNIQUE_ID'];