Sending Log Messages to Graylog with Graypy

  • Share this:

Code introduction


This function uses the Graypy library to send log messages to a Graylog server, where you can specify the message, severity, and source.


Technology Stack : Graypy, GelfHandler, Graylog

Code Type : Log

Code Difficulty : Intermediate


                
                    
def graylog_log_message(message, severity="INFO", source="default"):
    from graypy import GelfHandler

    # Create a GelfHandler instance for logging to Graylog
    gelf_handler = GelfHandler(host='localhost', port=12201, version='1.1')

    # Create a log record with the provided message, severity, and source
    log_record = {
        'short_message': message,
        'severity': severity,
        'source': source
    }

    # Add the log record to the handler's queue
    gelf_handler.add_message(log_record)

    # Flush the handler's queue to send the log record to Graylog
    gelf_handler.flush()

# JSON representation of the code