_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; } }