vrza/simplogger

Lightweight PHP logging library

v1.0.0 2024-02-21 14:45 UTC

This package is auto-updated.

Last update: 2024-08-28 16:13:43 UTC


README

Overview

The goal of Simplogger is to provide a logging utility library for PHP that is lightweight, simple to use, and simple to integrate.

Simplogger can log to:

  • stdout/stderr

  • local syslogd (/dev/log)

  • remote syslogd (UDP)

  • file

Typical use case is a PHP microservice that uses syslogd for logging when deployed, but can just as easily use stdout/stderr (e.g. in the development environment).

use \VladimirVrzic\Simplogger\StdouterrLogger;
use \VladimirVrzic\Simplogger\SyslogLogger;

$ident = basename($argv[0]);
$opts = getopt('s', ['syslog']);
$logger = array_key_exists('s', $opts) || array_key_exists('syslog', $opts)
  ? new SyslogLogger($ident, LOG_CONS, LOG_LOCAL1)
  : new StdoutLogger;
$logger->notice('Hello world!');

Setup

Installation

Assuming you have PHP Composer installed, and that the composer executable is in your $PATH:

composer require vrza/simplogger

Log to local syslog

$ident = 'my-program-name';
$facility = LOG_LOCAL1;
$options = LOG_CONS;
$logger = new SyslogLogger($ident, $options, $facility);

SyslogLogger logs using PHP’s syslog() function. Parameters are the same as passed to openlog().

Log to remote syslogd via UDP

$syslogHost = 192.0.2.22;
$syslogPort = 514;
$logger = new RemoteSysLogger($ident, $facility, $syslogHost, $syslogPort);

RemoteSysLogger sends all messages to syslogd over UDP. Default host is 127.0.0.1, default port number is 514.

Log to stdout/stderr

$logger = new StdoutLogger;

StdoutLogger writes all messages to stdout.

StderrLogger writes all messages to stderr.

StdouterrLogger writes WARNING and higher severity messages to stderr, writes other messages to stdout.

These loggers can be optionally set up to include timestamp, ident and severity with each message:

$timestamp = TRUE;
$severity = TRUE;
$logger = new StdoutLogger($timestamp, $severity, $ident);

Log to file

$logFile = '/var/log/my.log';
$logger = new FileLogger($logFile);

FileLogger writes all messages to a given file.

Like the stdout/stderr loggers, FileLogger has an option to include timestamp, ident and severity with each message.

$logger = new FileLogger($logFile, $timestamp, $severity, $ident);

Usage

$logger->alert('A message with ALERT severity');
$logger->crit('A message with CRIT severity');
$logger->err('A message with ERR severity');
$logger->warning('A message with WARNING severity');
$logger->notice('A message with NOTICE severity');
$logger->info('A message with INFO severity');
$logger->debug('A messsage with DEBUG severity');