1
+ <?php
2
+ /**
3
+ * @link https://www.moaas.de/
4
+ * @copyright Copyright (c) 2019 moaas GmbH
5
+ * @license MIT
6
+ */
7
+
8
+ namespace wepushit \log ;
9
+ use Yii ;
10
+ use yii \log \Logger ;
11
+ use yii \log \Target ;
12
+
13
+ /**
14
+ * SplunkTarget sends logs to httpcollector from splunk enterprise.
15
+ *
16
+ * @author moaas GmbH <[email protected] >
17
+ * @since 2.0
18
+ */
19
+ class SplunkTarget extends Target
20
+ {
21
+
22
+ /**
23
+ * @inheritdoc
24
+ */
25
+ public function export ()
26
+ {
27
+
28
+ $ splunkmsg = [
29
+ 'source ' => Yii::$ app ->params ['splunk ' ]['source ' ],
30
+ 'host ' => $ _SERVER ['SERVER_NAME ' ],
31
+ 'event ' => '' ,
32
+ ];
33
+
34
+
35
+ foreach ($ this ->messages as $ key => $ message ) {
36
+
37
+ $ splunkmsg ["event " ] = $ this ->formatMessage ($ message );
38
+
39
+ $ ch = curl_init ();
40
+ curl_setopt ($ ch , CURLOPT_URL , Yii::$ app ->params ['splunk ' ]['url ' ]);
41
+ curl_setopt ($ ch , CURLOPT_USERPWD , Yii::$ app ->params ['splunk ' ]['token ' ]);
42
+ curl_setopt ($ ch , CURLOPT_SSL_VERIFYPEER , 0 ); // Skip SSL Verification
43
+ curl_setopt ($ ch , CURLOPT_SSL_VERIFYHOST , false );
44
+ curl_setopt ($ ch , CURLOPT_RETURNTRANSFER , true );
45
+ curl_setopt ($ ch , CURLOPT_POST , true );
46
+ curl_setopt ($ ch , CURLOPT_POSTFIELDS , json_encode ($ splunkmsg ));
47
+
48
+ $ output = curl_exec ($ ch );
49
+ if ($ output === false )
50
+ {
51
+ Yii::error ('Curl-Fehler: ' . curl_error ($ ch ));
52
+ Yii::error ('Curl-Fehlernr: ' . curl_errno ($ ch ));
53
+ }
54
+ curl_close ($ ch );
55
+ }
56
+ }
57
+
58
+ public function formatMessage ($ message )
59
+ {
60
+ list ($ text , $ level , $ category , $ timestamp ) = $ message ;
61
+ $ level = Logger::getLevelName ($ level );
62
+ if (!is_string ($ text )) {
63
+ // exceptions may not be serializable if in the call stack somewhere is a Closure
64
+ if ($ text instanceof \Throwable || $ text instanceof \Exception) {
65
+ $ text = (string ) $ text ;
66
+ }
67
+ }
68
+ $ traces = [];
69
+ if (isset ($ message [4 ])) {
70
+ foreach ($ message [4 ] as $ trace ) {
71
+ $ traces [] = "in {$ trace ['file ' ]}: {$ trace ['line ' ]}" ;
72
+ }
73
+ }
74
+
75
+ $ prefix = $ this ->getMessagePrefix ($ message );
76
+
77
+ return [
78
+ 'timestamp ' => $ this ->getTime ($ timestamp ),
79
+ 'prefix ' => $ prefix ,
80
+ 'level ' => $ level ,
81
+ 'category ' => $ category ,
82
+ 'text ' => $ text ,
83
+ 'traces ' => empty ($ traces ) ? '' : $ traces ,
84
+ ];
85
+ }
86
+ }
0 commit comments