Event Syslog Example

From FreeNATS Wiki
Jump to: navigation, search


This example goes through developing a very simple event handler to write a specific alert action out to the system logger (syslog) using PHP's internal syslog functions.

To develop the event we need to create a PHP file to put into the server/base/site/events directory. Developing code directly inside FreeNATS is a potential problem as any parsing errors for example will stop the system from working entirely! If you do manage to break the system with your files see the troubleshooting document.

I would strongly recommend you develop within a development environment you can quickly edit/rename the files on if required.

The Basics

To create an event handler we define a PHP function and register it to FreeNATS as a handler. For this example we are interested in handling an alert action, we want to direct this output to the syslog rather than email or a URL.

From the reference section we can see some of the data array provided for the alert_action event is:

aaid => alert action id
name => alert action name
data => alert action data (on different lines)

We also must return false if we don't handle that action and true if we did (so it's cleared of the data).

Files are included by FreeNATS so the $NATS object should be already setup.

Create the Action

Create a new alert action of the type message queue and with the name syslog. This is the name we will use to determine our queue (rather than bothering to worry about the numeric ID).

Example Code

<?php // Syslog Event Handler Example for FreeNATS global $NATS; // have to do this as the include is within a function

// First the function to handle the data

function my_alert_action_syslog($data)

global $NATS; // we need the NATS object for logging

// Check if it is our alert action otherwise return false as
// we don't handle it
if ($data['name']!="syslog") return false;

// Open syslog connection

// Try to write to the system log
if (syslog(LOG_ERR,$data['data'])===false)
 { // log an error to the NATS log if failes
 $NATS->Event("Syslog Failed for ".$data['data'],2,"Syslog","Write");

// Close the syslog connection
// Return true to clear the message queue now we have handled it
return true;


// Now the function my_alert_action_syslog has been created we need // to register it for the alert_action event with FreeNATS

$NATS->AddEventHandler("alert_action","my_alert_action_syslog"); ?>