Graylog2 Log Search Function

  • Share this:

Code introduction


This function uses the Graylog2 library to perform a log search query on a Graylog server.


Technology Stack : Graylog2 library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def graylog_search_query(query, from_time, to_time):
    from graylog2.gelf import GELFMessage
    from graylog2.client import Graylog2Client

    # Create a Graylog2 client
    client = Graylog2Client(host='localhost', port=12201, username='admin', password='admin')

    # Create a GELF message with the search query
    message = GELFMessage(
        short_message=query,
        _timestamp=from_time,
        _source='python_script'
    )

    # Send the message to the Graylog2 server
    client.submit(message)

    # Query the logs within the specified time range
    response = client.search(query, from_time, to_time)

    # Return the results
    return response