How to retrieve log from graylog over API

3.7k Views Asked by At

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

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

1

There are 1 best solutions below

0
On

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.