1+ <?php
2+
3+ namespace Prokl \BitrixOrdinaryToolsBundle \Services \Logger ;
4+
5+ use Bitrix \Main \Application ;
6+ use Bitrix \Main \EventLog \Internal \EventLogTable ;
7+ use Bitrix \Main \Type \DateTime ;
8+ use Monolog \Handler \AbstractProcessingHandler ;
9+ use Monolog \Logger ;
10+
11+ /**
12+ * Class EventLogLogger
13+ * Записывает логи в журнал событий /bitrix/admin/event_log.php?lang=ru.
14+ * @package Prokl\BitrixOrdinaryToolsBundle\Services\Logger
15+ */
16+ class EventLogLogger extends AbstractProcessingHandler
17+ {
18+ /**
19+ * @var string
20+ */
21+ private $ defaultModuleId ;
22+
23+ /**
24+ * @inheritdoc
25+ */
26+ public function __construct ($ level = Logger::DEBUG , string $ moduleId = '' )
27+ {
28+ parent ::__construct ($ level );
29+
30+ $ this ->defaultModuleId = $ moduleId ;
31+ }
32+
33+ /**
34+ * @inheritdoc
35+ */
36+ protected function write (array $ record ): void
37+ {
38+ global $ USER ;
39+ $ appContext = Application::getInstance ()->getContext ();
40+ $ server = $ appContext ->getServer ();
41+
42+ /** @var \DateTime $datetime */
43+ $ datetime = $ record ['datetime ' ];
44+
45+ EventLogTable::add ([
46+ 'TIMESTAMP_X ' => DateTime::createFromTimestamp ($ datetime ->getTimestamp ()),
47+ 'SEVERITY ' => $ record ['level_name ' ],
48+ 'MODULE_ID ' => $ record ['context ' ]['MODULE_ID ' ] ?? $ this ->defaultModuleId ,
49+ 'AUDIT_TYPE_ID ' => $ record ['level_name ' ],
50+ 'ITEM_ID ' => $ record ['context ' ]['ITEM_ID ' ] ?? '' ,
51+ 'REMOTE_ADDR ' => $ record ['context ' ]['REMOTE_ADDR ' ] ?? $ server ->getRemoteAddr (),
52+ 'USER_AGENT ' => $ record ['context ' ]['USER_AGENT ' ] ?? $ server ->getUserAgent (),
53+ 'REQUEST_URI ' => $ record ['context ' ]['REQUEST_URI ' ] ?? $ server ->getRequestUri (),
54+ 'SITE_ID ' => $ record ['context ' ]['SITE_ID ' ] ?? $ appContext ->getSite (),
55+ 'USER_ID ' => $ record ['context ' ]['USER_ID ' ] ?? $ USER ->GetID (),
56+ 'GUEST_ID ' => $ record ['context ' ]['GUEST_ID ' ] ?? '' ,
57+ 'DESCRIPTION ' => $ this ->interpolate ($ record ['formatted ' ], (array )$ record ['context ' ]),
58+ ]);
59+ }
60+
61+ /**
62+ * @param string $message
63+ * @param array $context
64+ *
65+ * @return string
66+ */
67+ public function interpolate (string $ message , array $ context = []): string
68+ {
69+ // build a replacement array with braces around the context keys
70+ $ replace = [];
71+ foreach ($ context as $ key => $ val ) {
72+ // check that the value can be cast to string
73+ if (!is_array ($ val ) && (!is_object ($ val ) || method_exists ($ val , '__toString ' ))) {
74+ $ replace ['{ ' . $ key . '} ' ] = $ val ;
75+ }
76+ }
77+
78+ // interpolate replacement values into the message and return
79+ return strtr ($ message , $ replace );
80+ }
81+ }
0 commit comments