<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2016 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flLogHandlerPapertrail Class
 *
 * Log handler for papertrail.
 *
 * @package fusionLib
 */
class flLogHandlerPapertrail implements flLogHandler {

	/**
	 * The socket to the logger.
	 *
	 * @var resource
	 */
	protected $sock = null;

	/**
	 * The host name.
	 *
	 * @var string
	 */
	protected $host;

	/**
	 * The port.
	 *
	 * @var int
	 */
	protected $port;

	/**
	 * Constructor.
	 *
	 * @param string $host The host to connect to.
	 * @param int $port The port to connect to.
	 */
	function __construct($host, $port) {
		$this->host = $host;
		$this->port = $port;
	}

	/**
	 * Release resources.
	 */
	function __destruct() {
		if($this->sock) {
			socket_close($this->sock);
			$this->sock = null;
		}
	}

	/**
	 * Write a record to the log target.
	 *
	 * @param array $record The record to log.
	 */
	public function write($record) {

		// Format the message
		$message = (empty($record['channel']) ? '' : $record['channel'] . '.') . $record['level_name'] . ' ';
		if(is_array($record['message']) || (is_object($record['message']) && !method_exists($record['message'], '__toString'))) {
			$message .= json_encode($record['message']);
		} else {
			$message .= (string)$record['message'];
		}

		// Open the socket if not open
		if(!$this->sock)
			$this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

		// Send message to papertrail
		socket_sendto($this->sock, $message, strlen($message), 0, $this->host, $this->port);
	}
}