From: Banana Date: Tue, 14 May 2024 13:41:41 +0000 (+0200) Subject: adding php loki X-Git-Url: http://91.132.146.200/gitweb/?a=commitdiff_plain;h=908a0ae6f7b669f3f229598e50801ec3eee6df3f;p=dolphin.git adding php loki Signed-off-by: Banana --- diff --git a/grafana-loki-metrics/index.php b/grafana-loki-metrics/index.php new file mode 100644 index 0000000..b27a0d4 --- /dev/null +++ b/grafana-loki-metrics/index.php @@ -0,0 +1,42 @@ + "value1", "streamlabel2" => "value2")); + +$Loki->log("log line text", array("structuredData" => "value")); +$Loki->log("log line text", array("structuredData" => "value2")); + +# send the data to loki at the end to avoid and multiple calls and breaking +# the process of the script. +$Loki->send(); \ No newline at end of file diff --git a/grafana-loki-metrics/loki.php b/grafana-loki-metrics/loki.php new file mode 100644 index 0000000..cf264bb --- /dev/null +++ b/grafana-loki-metrics/loki.php @@ -0,0 +1,121 @@ +_stream = $stream; + $this->_host = $host; + $this->_port = $port; + + if(defined("LOKI_USER") && !empty(LOKI_USER)) { + $this->_auth = base64_encode(LOKI_USER.":".LOKI_USER_PW); + } + } + + /** + * Add a log message with optional structured data to the values to be send() + * + * @param string $msg The log message + * @param array $structuredData Additional structured data to be processed from Loki if configured + * @return void + */ + public function log(string $msg, array $structuredData=array()): void { + $_nanosec = strval(shell_exec("date +%s%9N")-1); + if(!empty($structuredData)) { + $this->_values[] = array($_nanosec, $msg, $structuredData); + } else { + $this->_values[] = array($_nanosec, $msg); + } + } + + /** + * Send the collected messages from log() to the loki installation + * The messages to be send will be resetted after + * + * @return string Non empty on error + */ + public function send(): string { + $ret = ""; + + if(!LOKI_ENABLE) return $ret; + + $data = array( + "streams" => array( + array( + "stream" => $this->_stream, + "values" => $this->_values + ) + ) + ); + + $data = json_encode($data); + $out = "POST ".LOKI_PUSH_API." HTTP/1.1\r\n"; + $out .= "Host: $this->_host\r\n"; + if(!empty($this->_auth)) { + $out .= "Authorization: Basic $this->_auth\r\n"; + } + $out .= "Content-Type: application/json\r\n"; + $out .= "Content-Length: ".strlen($data)."\r\n"; + $out .= "Connection: Close\r\n\r\n"; + + $fp = fsockopen($this->_host, $this->_port, $errno, $errstr, 5); + if($fp) { + fwrite($fp, $out); + fwrite($fp, $data."\r\n"); + fclose($fp); + } else { + $ret = $errno.' '.$errstr; + } + + # reset + $this->_values = array(); + + return $ret; + } +}