Processing and Sending Messages to Graylog with Source and Priority

  • Share this:

Code introduction


This function is used to process information and send it to Graylog, with specified source and priority.


Technology Stack : Python, Graypy, logging

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
def graylog_process_message(message, source, priority):
    """
    This function processes a message and sends it to Graylog with a specified source and priority.

    :param message: The message to be processed and sent to Graylog.
    :param source: The source of the message.
    :param priority: The priority of the message.
    """
    from graypy import GelfHandler
    import logging

    # Create a logger
    logger = logging.getLogger('graylog_logger')

    # Create a GelfHandler for Graylog
    graylog_handler = GelfHandler(host='graylog_server', port=12201)

    # Add the GelfHandler to the logger
    logger.addHandler(graylog_handler)

    # Set the message's priority
    logger.setLevel(priority)

    # Log the message
    logger.info(f"Source: {source}, Message: {message}")

    # Remove the GelfHandler to avoid double logging
    logger.removeHandler(graylog_handler)