Skip to content
Snippets Groups Projects
LoggerTrait.php 2.88 KiB
Newer Older
<?php

namespace Library;

/**
 * Logger trait to add logging functionality to a class.
 * If no logger is set all logging methods, error(), info(), etc. do nothing.
 * The context for a log message can be provided with the ndc_push() and ndc_pop methods.
 * NDC stands for Nested Diagnostic Context
 *
 * To use this trait add
 *   use \Library\Logger;
 * at the begin of your class declaration.
 */
trait LoggerTrait {

    /**
     * PSR-3 compatible logger instance, if not set no logging is done
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * nested diagnostic context, used as context for log messages
     * @var array
     */
    protected $ndc_context = [];

    /**
     * set logger to send log messages to
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function set_logger(\Psr\Log\LoggerInterface $logger) {

        $this->logger = $logger;
        return $this;
    }

    /**
     * debug message
     * @param string $message
     * @param array $context if not set the ndc is used
     */
    public function debug(string $message, array $context = null) {

        if (isset($this->logger)) {
            $this->logger->debug($message, isset($context) ? $context : $this->ndc_context);
    }

    /**
     * info message
     * @param string $message
     * @param array $context if not set the ndc is used
     */
    public function info(string $message, array $context = null) {

        if (isset($this->logger)) {
            $this->logger->info($message, isset($context) ? $context : $this->ndc_context);
    }

    /**
     * warning message
     * @param string $message
     * @param array $context if not set the ndc is used
     */
    public function warning(string $message, array $context = null) {

        if (isset($this->logger)) {
            $this->logger->warning($message, isset($context) ? $context : $this->ndc_context);
    }

    /**
     * error message
     * @param string $message
     * @param array $context if not set the ndc is used
     */
    public function error(string $message, array $context = null) {

        if (isset($this->logger)) {
            $this->logger->error($message, isset($context) ? $context : $this->ndc_context);
    }

    /**
     * add message to the ndc (nested diagnostic context)
     * @param string $message
     */
    public function ndc_push(string $message){

        array_push($this->ndc_context, $message);
    }

    /**
     * remove last message from the ndc (nested diagnostic context)
     */
    public function ndc_pop(){

        array_pop($this->ndc_context);