afcd9c7cde9bd1ae47af91cadd26da6ec6f3d8b9
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Log / Writer / DatabaseWriter.php
1 <?php
2 namespace TYPO3\CMS\Core\Log\Writer;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16 use TYPO3\CMS\Core\Database\ConnectionPool;
17 use TYPO3\CMS\Core\Log\LogRecord;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19
20 /**
21 * Log writer that writes the log records into a database table.
22 */
23 class DatabaseWriter extends AbstractWriter
24 {
25 /**
26 * Table to write the log records to.
27 *
28 * @var string
29 */
30 protected $logTable = 'sys_log';
31
32 /**
33 * Set name of database log table
34 *
35 * @param string $tableName Database table name
36 * @return \TYPO3\CMS\Core\Log\Writer\AbstractWriter
37 */
38 public function setLogTable($tableName)
39 {
40 $this->logTable = $tableName;
41 return $this;
42 }
43
44 /**
45 * Get name of database log table
46 *
47 * @return string Database table name
48 */
49 public function getLogTable()
50 {
51 return $this->logTable;
52 }
53
54 /**
55 * Writes the log record
56 *
57 * @param LogRecord $record Log record
58 * @return \TYPO3\CMS\Core\Log\Writer\WriterInterface $this
59 */
60 public function writeLog(LogRecord $record)
61 {
62 $data = '';
63 $recordData = $record->getData();
64 if (!empty($recordData)) {
65 // According to PSR3 the exception-key may hold an \Exception
66 // Since json_encode() does not encode an exception, we run the _toString() here
67 if (isset($recordData['exception']) && $recordData['exception'] instanceof \Exception) {
68 $recordData['exception'] = (string)$recordData['exception'];
69 }
70 $data = '- ' . json_encode($recordData);
71 }
72
73 $fieldValues = [
74 'request_id' => $record->getRequestId(),
75 'time_micro' => $record->getCreated(),
76 'component' => $record->getComponent(),
77 'level' => $record->getLevel(),
78 'message' => $record->getMessage(),
79 'data' => $data
80 ];
81
82 GeneralUtility::makeInstance(ConnectionPool::class)
83 ->getConnectionForTable($this->logTable)
84 ->insert($this->logTable, $fieldValues);
85
86 return $this;
87 }
88 }