5

How can I search logs from a graylog server with PHP?

Assume the graylog servers is https://host.td/api/search/universal/absolute

Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
Klaus
  • 1,171
  • 1
  • 11
  • 16
  • I had a similar problem and used Python to access the API. A simple script can be found [here](https://gist.github.com/prathje/862cc96b531e0dcf904f5ea71f7812a1). – P. Rathje Mar 20 '21 at 16:57
  • here is another example using shell script : https://dev.to/boly38/hourly-errors-from-graylog-to-slack-24ga – boly38 Mar 21 '21 at 12:14
  • For others who had some trouble like me `from` and `to` fields are also required. This worked for me. Date format: `yyyy-MM-ddTHH:mm:ss.SSSZ (e.g. 2014-01-23T15:34:49.000Z) or yyyy-MM-dd HH:mm:ss.`. however, in Graylog API documentation it is under section **Legacy/Search/Absolute**, which seems like it should be used? – Nuryagdy Mustapayev Sep 02 '21 at 09:12
  • If you use the universal/relative endpoint rather than universal/absolute, then you don't need to format dates. Instead of "from" and "to", use "range". A value of "3600" will show you entries for the last hour. – David42 Jan 12 '22 at 19:27
  • @Klaus, StackOverflow does not recommend both asking and answering the question in the body of the question. I moved your answer below in my response. Please feel free to copy the text of my answer and repost it as your own... just send me a comment if you do so... I will gladly delete my "answer" once you respond – Mike Pennington Oct 13 '22 at 22:24

1 Answers1

0

This solution is implemented in PHP:

$url = 'https://host.td/api/search/universal/absolute'
   . '?query=' . urlencode('field:value')                 //query which you would also perform on UI
   . '&from=' . urlencode(Carbon::createFromTimestamp(0)) // min timestamp so we get all logs
   . '&to=' . urlencode(Carbon::createFromTimestamp(NumberUtils::MAX_32_BIT_INT)) // max timestamp so we get all logs
   . '&limit=' . $this->limit                             //how many results do we want?
   . '&fields=' . urlencode('field1,field2,field3')       //which fields do we want?
   . '&filter=' . urlencode('streams:<stream_id>')        //OPTIONAL: only search in this stream
   . '&sort=' . urlencode('field:desc')                   //sort result
   . '&decorate=false';                                   //decorate parameter


$res = (new Client())->get($url, [
    // generate a token on graylog UI;
    // we use basic auth, username=the token; password: hard coded string 'token'
'auth'    => ['<token_value>', 'token'],
'headers' => ['Accept' => 'application/json']             //we want a json result
]);

$json = \GuzzleHttp\json_decode($res->getBody());

If you want to sort by a timestamp you provided, don't call it timestamp since in this case graylog's timestamp is used, not yours. I ended up using a prefix on every field I am storing.

Mike Pennington
  • 41,899
  • 19
  • 136
  • 174