bhenk/logger

About

Logger facilitates normal logging for applications with wrappers around Monolog\Logger(s).

Log statements can give insight in what your code is doing but it is awkward to read or follow complete log files. Logger enables you to redirect log output to console during PHPUnit testing of your application. To not drown in log statements this can be turned on or off on TestClass and testMethod basis.

Logger is written in PHP.

Source code: https://github.com/bhenk/logger-d

Copyright © 2023 by henk van den berg
License: Apache 2.0
Version: 1.0.4

Usage

Requirements

Minimum (tested) PHP-version is 8.1.
Minimum (tested) PHPUnit version is PHPUnit 9.5.

Installing with composer

composer require bhenk/logger

Configuration

Configuration file

Everything will work on default settings. Nevertheless, configuration of loggers and handlers can be given.

The LoggerFactory will look for a directory config and a file named log_config.php. The config directory and the LoggerFactory file should have a common ancestor:

                  | /config/log_config.php
{common ancestor} |
                  | /{..}/vendor/{..}/bhenk/logger/{..}

See LoggerFactory for an example of a log_config file.

Log output files

Unless specified with absolute filenames in the configuration file (see above) log files will be relative to the directory logs that is a child of a common ancestor of the code base:

                  | /logs/logger/{..}
{common ancestor} |
                  | /{..}/vendor/{..}/bhenk/logger/{..}

Logging

Static logger classes make for easy and concise coding. Logger facilitates two logger agents:

  • Log - for normal use;

  • Req - for logging request properties

Both have static methods as specified on interface LoggerInterface.

Console logging with PHPUnit

Testing your code is great. Using PHPUnit invites you to write testable code. But there will always be more or less obscure places in your code. Does the program flow take the expected junction at an if statement? Has this or that variable the right value at a precise moment? You can put in debug statements for your logger at those places, but chances are you drown in log statements by the time your code base has grown sufficiently large. Wouldn’t it be great to see exactly those log statements on your console, of that part of your codebase that is under test, with the chosen severity level? A Trait and an Attribute in the package bhenk\logger\unit allows you to precisely do that.

The ConsoleLoggerTrait use the PHPUnit fixtures setUp, tearDown, setUpBeforeClass and tearDownAfterClass to redirect log statements of the code under test to console. The injected ConsoleHandler makes for readable and clickable log statements that otherwise would be lost in the log files. The LogAttribute enables you to choose exactly which test methods and which test classes will output to console.

Here is an example of console output using ConsoleLoggerTrait and LogAttribute on a TestCase.

console view example

Console view example

The start and exit of the TestCase (here AbstractDaoTest) are clearly marked. The start of the test method is indicated (here testInsert) and the log statements invoked by the code under test are printed to console, with the originating location of the log statement (in most IDE’s) as clickable link. Note that among the 22 tests only the chosen test method is outputting log statements to console.

Check if an error message is clear and understandable by producing that error in a test method.

console view example of inspecting error messages

Console view example of inspecting error messages

See ConsoleLoggerTrait for directions of how to use Trait and Attribute on TestCases.

Happy coding!

api-docs

logger

build

Depends on

Dependency invoked by

handle

ConsoleLoggerCreator

Build Loggers

AbstractLoggerCreator

namespace

bhenk\logger\build

predicates

Abstract

implements

LoggerCreatorInterface

known subclasses

ConsoleLoggerCreator | DefaultLoggerCreator | ErrorLoggerCreator | RequestLoggerCreator


Constants
AbstractLoggerCreator::LOG_DIR

predicates

public

Inherited from

LoggerCreatorInterface::LOG_DIR

Name of an ancestor child directory expected to be dedicated for logfiles

string(4) "logs"

Methods
AbstractLoggerCreator::makeAbsolute

predicates

public

Tries to make the given filename absolute

An absolute param $filename will be returned as such.

This method will than try to locate an ancestor directory with a child with the name specified by LoggerCreatorInterface::LOG_DIR (logs). The returned absolute filename will than point to a child of this ancestor-child directory.

A param $filename is invalid if it is the empty string (“”) or the slash forward (/).

public function makeAbsolute(
      Parameter #0 [ <required> string $filename ]
 ): string
param string $filename - absolute or relative to ancestor directory ‘logs’
return string - absolute filename

AbstractLoggerCreator::create

predicates

public | abstract

Creates a logger that implements LoggerInterface

public abstract function create(
      Parameter #0 [ <optional> array $paras = [] ]
 ): LoggerInterface
param array $paras - array of name-value pairs needed for building the logger.

Sat, 29 Apr 2023 12:38:18 +0000

ConsoleLoggerCreator

namespace

bhenk\logger\build

predicates

Cloneable | Instantiable

implements

LoggerCreatorInterface

extends

AbstractLoggerCreator

hierarchy

ConsoleLoggerCreator -> AbstractLoggerCreator

Class capable of creating a Logger that outputs to console

The Logger created is equipped with a ConsoleHandler that is optimized for logging to console during test runs.

see also

ConsoleHandler


Constants
ConsoleLoggerCreator::CHANNEL

predicates

public

Default channel

string(3) "clt"

ConsoleLoggerCreator::LEVEL

predicates

public

Default LogLevel

string(5) "debug"

ConsoleLoggerCreator::BUBBLE

predicates

public

By default, does not bubble

bool(false)

ConsoleLoggerCreator::WHITE_LINE

predicates

public

Induce a white line before each log statement

bool(true)

ConsoleLoggerCreator::STACK_MATCH

predicates

public

Regular expression used to filter lines in error traces

string(8) "/(.*?)/i"

ConsoleLoggerCreator::DATE_FORMAT

predicates

public

Date format for log statements

string(7) "H:i:s:u"

ConsoleLoggerCreator::EXCLAMATION

predicates

public

Exclamation on encountering an error

string(6) "chips!"

ConsoleLoggerCreator::COLOR_SCHEME

predicates

public

ColorScheme used by ConsoleHandler

string(35) "bhenk\logger\handle\ColorSchemeDark"

ConsoleLoggerCreator::LOG_DIR

predicates

public

Inherited from

LoggerCreatorInterface::LOG_DIR

Name of an ancestor child directory expected to be dedicated for logfiles

string(4) "logs"

Methods
ConsoleLoggerCreator::create

predicates

public

implements

LoggerCreatorInterface::create

Creates a Logger that outputs to console

The logger created has a ConsoleHandler that outputs log statements to console

Optional param $paras set behaviour of ConsoleHandler and have the following format:

"clt" => [
    "channel" => {string},
    "level" => {string|int|Monolog\Level|\Psr\Log\LogLevel},
    "bubble" => {bool},
    "white_line" => {bool},
    "stack_match" => {regex},
    "date_format" => {date format},  // "H:i:s:u"
    "exclamation" => {string},
    "color_scheme" => {string},      // bhenk\logger\handle\ColorSchemeInterface
]

param $paras can be incorporated in LoggerFactory::LOG_CONFIG_FILE.

@inheritdoc

Creates a logger that implements LoggerInterface

param array $paras - array of name-value pairs needed for building the logger.

@inheritdoc from method LoggerCreatorInterface::create

public function create(
      Parameter #0 [ <optional> array $paras = [] ]
 ): Logger
param array $paras - see above
return Logger - Logger with a ConsoleHandler

ConsoleLoggerCreator::makeAbsolute

predicates

public

inherited from

AbstractLoggerCreator::makeAbsolute

Tries to make the given filename absolute

An absolute param $filename will be returned as such.

This method will than try to locate an ancestor directory with a child with the name specified by LoggerCreatorInterface::LOG_DIR (logs). The returned absolute filename will than point to a child of this ancestor-child directory.

A param $filename is invalid if it is the empty string (“”) or the slash forward (/).

public function makeAbsolute(
      Parameter #0 [ <required> string $filename ]
 ): string
param string $filename - absolute or relative to ancestor directory ‘logs’
return string - absolute filename

Sat, 29 Apr 2023 12:38:18 +0000

DefaultLoggerCreator

namespace

bhenk\logger\build

predicates

Cloneable | Instantiable

implements

LoggerCreatorInterface

extends

AbstractLoggerCreator

hierarchy

DefaultLoggerCreator -> AbstractLoggerCreator

Class capable of creating a default logger

The default logger logs standard log messages to a logfile. Log messages exceeding a certain level will also be logged to an error logfile.


Constants
DefaultLoggerCreator::LOG_FILENAME

predicates

public

Default logfile

string(17) "logger/logger.log"

DefaultLoggerCreator::LOG_MAX_FILES

predicates

public

Default max logfiles to keep around

int(5)

DefaultLoggerCreator::LOG_LEVEL

predicates

public

Default log level

enum(Monolog\Level::Info)

DefaultLoggerCreator::FORMAT

predicates

public

Format for log entries

string(58) "%level_name% | %datetime% | %message% | %context% %extra% "

DefaultLoggerCreator::DATE_FORMAT

predicates

public

Date format in log entries

string(11) "Y-m-d H:i:s"

DefaultLoggerCreator::INTROSPECTION_PROCESSOR

predicates

public

Add an IntrospectionProcessor

bool(true)

DefaultLoggerCreator::ERR_FILENAME

predicates

public

Default error filename

string(16) "logger/error.log"

DefaultLoggerCreator::ERR_MAX_FILES

predicates

public

Default max error files to keep around

int(5)

DefaultLoggerCreator::ERR_LEVEL

predicates

public

Default error level

enum(Monolog\Level::Error)

DefaultLoggerCreator::DEFAULT_CHANNEL

predicates

public

Default channel name

string(3) "log"

DefaultLoggerCreator::LOG_DIR

predicates

public

Inherited from

LoggerCreatorInterface::LOG_DIR

Name of an ancestor child directory expected to be dedicated for logfiles

string(4) "logs"

Methods
DefaultLoggerCreator::create

predicates

public

implements

LoggerCreatorInterface::create

Creates a default logger

Optional param $paras have the format

[
   "channel" => "{string}",
   "log_file" => "{string}",
   "log_max_files" => {int},
   "log_level" => Level|LogLevel|string|int,
   "err_file" => "{string}",
   "err_max_files" => {int},
   "err_level" => Level|LogLevel|string|int,
   "format" => "{string}",
   "date_format" => "{string}",
   "introspection" => {bool},
]

@inheritdoc

Creates a logger that implements LoggerInterface

param array $paras - array of name-value pairs needed for building the logger.

@inheritdoc from method LoggerCreatorInterface::create

public function create(
      Parameter #0 [ <optional> array $paras = [] ]
 ): Logger
param array $paras
return Logger

DefaultLoggerCreator::makeAbsolute

predicates

public

inherited from

AbstractLoggerCreator::makeAbsolute

Tries to make the given filename absolute

An absolute param $filename will be returned as such.

This method will than try to locate an ancestor directory with a child with the name specified by LoggerCreatorInterface::LOG_DIR (logs). The returned absolute filename will than point to a child of this ancestor-child directory.

A param $filename is invalid if it is the empty string (“”) or the slash forward (/).

public function makeAbsolute(
      Parameter #0 [ <required> string $filename ]
 ): string
param string $filename - absolute or relative to ancestor directory ‘logs’
return string - absolute filename

Sat, 29 Apr 2023 12:38:18 +0000

ErrorLoggerCreator

namespace

bhenk\logger\build

predicates

Cloneable | Instantiable

implements

LoggerCreatorInterface

extends

AbstractLoggerCreator

hierarchy

ErrorLoggerCreator -> AbstractLoggerCreator


Constants
ErrorLoggerCreator::FILENAME

predicates

public

string(16) "logger/error.log"

ErrorLoggerCreator::LOG_DIR

predicates

public

Inherited from

LoggerCreatorInterface::LOG_DIR

Name of an ancestor child directory expected to be dedicated for logfiles

string(4) "logs"

Methods
ErrorLoggerCreator::create

predicates

public

implements

LoggerCreatorInterface::create

@inheritdoc

Creates a logger that implements LoggerInterface

param array $paras - array of name-value pairs needed for building the logger.

@inheritdoc from method LoggerCreatorInterface::create

public function create(
      Parameter #0 [ <optional> array $paras = [] ]
 ): Logger
param array $paras
return Logger

ErrorLoggerCreator::makeAbsolute

predicates

public

inherited from

AbstractLoggerCreator::makeAbsolute

Tries to make the given filename absolute

An absolute param $filename will be returned as such.

This method will than try to locate an ancestor directory with a child with the name specified by LoggerCreatorInterface::LOG_DIR (logs). The returned absolute filename will than point to a child of this ancestor-child directory.

A param $filename is invalid if it is the empty string (“”) or the slash forward (/).

public function makeAbsolute(
      Parameter #0 [ <required> string $filename ]
 ): string
param string $filename - absolute or relative to ancestor directory ‘logs’
return string - absolute filename

Sat, 29 Apr 2023 12:38:18 +0000

LoggerCreatorInterface

namespace

bhenk\logger\build

predicates

Abstract | Interface

known implementations

AbstractLoggerCreator | ConsoleLoggerCreator | DefaultLoggerCreator | ErrorLoggerCreator | RequestLoggerCreator

Defines an interface for classes that are capable of creating loggers

The loggers implement LoggerInterface.


Constants
LoggerCreatorInterface::LOG_DIR

predicates

public

Name of an ancestor child directory expected to be dedicated for logfiles

string(4) "logs"

Methods
LoggerCreatorInterface::create

predicates

public | abstract

Creates a logger that implements LoggerInterface

public abstract function create(
      Parameter #0 [ <optional> array $paras = [] ]
 ): LoggerInterface
param array $paras - array of name-value pairs needed for building the logger.

Sat, 29 Apr 2023 12:38:18 +0000

LoggerFactory

namespace

bhenk\logger\build

predicates

Cloneable | Instantiable

Static class to create and stock Loggers

This class delegates the creation of loggers (implementing LoggerInterface) to LoggerCreators that will take an array of parameters as build specification. Parameters can be expressed in a configuration file:

{ancestor directory}/config/log_config.php

This class will look for the directory config as a child of an ancestor directory.

Example of a logger configuration file:

<?php

return [
    "req" => [
        "channel" => "req",
        "filename" => "unit/req.log",
        "level" => \Psr\Log\LogLevel::DEBUG,
        "max_files" => 2,
        "filename_format" => "{filename}-{date}",
        "filename_date_format" => "Y-m",
        "line_format" => "%datetime% %extra%\n",
    ],
    "log" => [
        "channel" => "log",
        "log_file" => "unit/logger.log",
        "log_max_files" => 5,
        "log_level" => \Psr\Log\LogLevel::INFO,
        "err_file" => "unit/error.log",
        "err_max_files" => 5,
        "err_level" => \Psr\Log\LogLevel::ERROR,
        "format" => "%level_name% | %datetime% | %message% | %context% %extra%\n",
        "date_format" => "Y-m-d H:i:s",
        "introspection" => true,
    ],
    "clt" => [
        "channel" => "clt",
        "level" => \Psr\Log\LogLevel::DEBUG,
        "bubble" => false,
        "white_line" => true,
        "stack_match" => "/(application|src)\/(bhenk|unit)/i",
        "date_format" => "H:i:s:u",
        "exclamation" => "chips!",
        "color_scheme" => "bhenk\logger\handle\ColorSchemeDark",
    ]
];

All parameters are optional.


Constants
LoggerFactory::CONFIG_DIR

predicates

public

The ancestor child directory that is expected to hold the log configuration file

string(6) "config"

LoggerFactory::LOG_CONFIG_FILE

predicates

public

The expected configuration filename

string(14) "log_config.php"

Methods
LoggerFactory::getConfigFile

predicates

public | static

Get the current configuration filename or false if no configuration file was found

public static function getConfigFile(): string|bool
return string | bool - the current configuration filename; false if not found

LoggerFactory::setConfigFile

predicates

public | static

Set the configuration file

Loads logger definitions from the configuration file.

public static function setConfigFile(
      Parameter #0 [ <required> string $config_file ]
 ): void
param string $config_file
return void

LoggerFactory::getLogger

predicates

public | static

Get the Logger of the given type

Will get the Logger from stock or tries to create the specified Logger. If anything goes wrong during creation will output an error message to

{ancestor directory}/logs/logger/factory_error.log
public static function getLogger(
      Parameter #0 [ <required> bhenk\logger\build\LoggerTypes $type ]
 ): LoggerInterface
param LoggerTypes $type - type of Logger
return LoggerInterface - Logger as specified

LoggerFactory::getDefinition

predicates

public | static

Get the definition for the given type of logger (if any)

public static function getDefinition(
      Parameter #0 [ <required> bhenk\logger\build\LoggerTypes $type ]
 ): array
param LoggerTypes $type
return array

LoggerFactory::setDefinition

predicates

public | static

Set the definition for a given type of logger

public static function setDefinition(
      Parameter #0 [ <required> bhenk\logger\build\LoggerTypes $type ]
      Parameter #1 [ <optional> array $definition = [] ]
 ): void
param LoggerTypes $type
param array $definition
return void

LoggerFactory::isQuiet

predicates

public | static

public static function isQuiet(): bool
return bool

LoggerFactory::setQuiet

predicates

public | static

Sets whether the factory will output error messages to STDERR when creating loggers

public static function setQuiet(
      Parameter #0 [ <required> bool $quiet ]
 ): void
param bool $quiet
return void

Sat, 29 Apr 2023 12:38:18 +0000

LoggerTypes

namespace

bhenk\logger\build

predicates

Final | Enum

implements

UnitEnum


Constants
LoggerTypes::req

predicates

public | enum case

enum(bhenk\logger\build\LoggerTypes::req)

LoggerTypes::log

predicates

public | enum case

enum(bhenk\logger\build\LoggerTypes::log)

LoggerTypes::clt

predicates

public | enum case

enum(bhenk\logger\build\LoggerTypes::clt)

Methods
LoggerTypes::cases

predicates

public | static

implements

UnitEnum::cases

public static function cases(): array
return array

Sat, 29 Apr 2023 12:38:18 +0000

RequestLoggerCreator

namespace

bhenk\logger\build

predicates

Cloneable | Instantiable

implements

LoggerCreatorInterface

extends

AbstractLoggerCreator

hierarchy

RequestLoggerCreator -> AbstractLoggerCreator

Class capable of creating a request logger

The request logger outputs request properties to a file. Request properties are for instance

  • request url,

  • ip address of the client,

  • http_method,

  • server,

  • referrer,

  • client browser


Constants
RequestLoggerCreator::FILENAME

predicates

public

The default filename for a request logger

string(14) "logger/req.log"

RequestLoggerCreator::CHANNEL

predicates

public

The default channel for a request logger

string(3) "req"

RequestLoggerCreator::LOG_DIR

predicates

public

Inherited from

LoggerCreatorInterface::LOG_DIR

Name of an ancestor child directory expected to be dedicated for logfiles

string(4) "logs"

Methods
RequestLoggerCreator::create

predicates

public

implements

LoggerCreatorInterface::create

Creates a request logger

Optional param $paras have the format

[
  "channel" => "{string}",               // optional, default "req"
  "level" => Level,                      // optional, default Level::Debug
  "filename" => "{string}",              // optional, default self::FILENAME
  "max_files" => {int},                  // optional, default 2
  "filename_format" => "{string}",       // optional, default "{filename}-{date}"
  "filename_date_format" => "{string}",  // optional, default "Y-m"
  "line_format" => "{string}}"           // optional, default "%datetime% %extra%\n"
]

The optional filename may be relative to the ancestor log directory. @see LoggerCreatorInterface::LOG_DIR.

@inheritdoc

Creates a logger that implements LoggerInterface

param array $paras - array of name-value pairs needed for building the logger.

@inheritdoc from method LoggerCreatorInterface::create

see also

WebProcessor

public function create(
      Parameter #0 [ <optional> array $paras = [] ]
 ): Logger
param array $paras - see above
return Logger - a Logger that logs request properties in a file

RequestLoggerCreator::getFilename

predicates

public

Gets the absolute filename of the logfile

public function getFilename(): ?string
return ?string - the absolute filename of the logfile of the last logger created or null if a logger was not yet created

RequestLoggerCreator::makeAbsolute

predicates

public

inherited from

AbstractLoggerCreator::makeAbsolute

Tries to make the given filename absolute

An absolute param $filename will be returned as such.

This method will than try to locate an ancestor directory with a child with the name specified by LoggerCreatorInterface::LOG_DIR (logs). The returned absolute filename will than point to a child of this ancestor-child directory.

A param $filename is invalid if it is the empty string (“”) or the slash forward (/).

public function makeAbsolute(
      Parameter #0 [ <required> string $filename ]
 ): string
param string $filename - absolute or relative to ancestor directory ‘logs’
return string - absolute filename

Sat, 29 Apr 2023 12:38:18 +0000


Sat, 29 Apr 2023 12:38:18 +0000

handle

ColorSchemeBright

namespace

bhenk\logger\handle

predicates

Cloneable | Instantiable

implements

ColorSchemeInterface

Bright schema for ConsoleHandler


Constants
ColorSchemeBright::NL

predicates

public

string(2) " "

ColorSchemeBright::RESET

predicates

public

string(26) "\033[0m\033[48;5;231m\033[38;5;235m"

ColorSchemeBright::DEBUG

predicates

public

string(11) "\033[38;5;100m"

ColorSchemeBright::INFO

predicates

public

string(11) "\033[38;5;107m"

ColorSchemeBright::NOTICE

predicates

public

string(11) "\033[38;5;111m"

ColorSchemeBright::WARNING

predicates

public

string(11) "\033[38;5;128m"

ColorSchemeBright::ERROR

predicates

public

string(15) "\033[7m\033[38;5;124m"

ColorSchemeBright::CRITICAL

predicates

public

string(15) "\033[7m\033[38;5;203m"

ColorSchemeBright::ALERT

predicates

public

string(15) "\033[7m\033[38;5;199m"

ColorSchemeBright::EMERGENCY

predicates

public

string(15) "\033[7m\033[38;5;196m"

ColorSchemeBright::C_DATE

predicates

public

string(11) "\033[38;5;245m"

ColorSchemeBright::C_CLASS

predicates

public

string(11) "\033[38;5;245m"

ColorSchemeBright::C_FILE

predicates

public

string(11) "\033[38;5;249m"

ColorSchemeBright::CONTEXT

predicates

public

string(11) "\033[38;5;104m"

ColorSchemeBright::EXTRA

predicates

public

string(11) "\033[38;5;104m"

ColorSchemeBright::T_EXCL

predicates

public

string(25) "\033[1m\033[48;5;15m\033[38;5;124m"

ColorSchemeBright::T_BY

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeBright::T_MSG

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeBright::T_STACK

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeBright::T_CAUSE

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeBright::TRAIT_HELLO

predicates

public

string(0) ""

ColorSchemeBright::TRAIT_METHOD

predicates

public

string(10) "\033[38;5;40m"

ColorSchemeBright::TRAIT_GOODBYE

predicates

public

string(11) "\033[38;5;110m"

ColorSchemeBright::TEST

predicates

public

string(44) "I am a bhenk\logger\handle\ColorSchemeBright"

ColorSchemeBright::END

predicates

public

Inherited from

ColorSchemeInterface::END

string(4) "\033[0m"

ColorSchemeBright::C_CONTEXT

predicates

public

Inherited from

ColorSchemeInterface::C_CONTEXT

string(0) ""

ColorSchemeBright::C_EXTRA

predicates

public

Inherited from

ColorSchemeInterface::C_EXTRA

string(0) ""

Sat, 29 Apr 2023 12:38:18 +0000

ColorSchemeDark

namespace

bhenk\logger\handle

predicates

Cloneable | Instantiable

implements

ColorSchemeInterface

Dark schema for ConsoleHandler


Constants
ColorSchemeDark::NL

predicates

public

string(2) " "

ColorSchemeDark::RESET

predicates

public

string(26) "\033[0m\033[48;5;236m\033[38;5;252m"

ColorSchemeDark::DEBUG

predicates

public

string(11) "\033[38;5;100m"

ColorSchemeDark::INFO

predicates

public

string(11) "\033[38;5;107m"

ColorSchemeDark::NOTICE

predicates

public

string(11) "\033[38;5;111m"

ColorSchemeDark::WARNING

predicates

public

string(11) "\033[38;5;128m"

ColorSchemeDark::ERROR

predicates

public

string(15) "\033[7m\033[38;5;124m"

ColorSchemeDark::CRITICAL

predicates

public

string(15) "\033[7m\033[38;5;203m"

ColorSchemeDark::ALERT

predicates

public

string(15) "\033[7m\033[38;5;199m"

ColorSchemeDark::EMERGENCY

predicates

public

string(15) "\033[7m\033[38;5;196m"

ColorSchemeDark::C_DATE

predicates

public

string(11) "\033[38;5;245m"

ColorSchemeDark::C_CLASS

predicates

public

string(11) "\033[38;5;245m"

ColorSchemeDark::C_FILE

predicates

public

string(11) "\033[38;5;249m"

ColorSchemeDark::C_CONTEXT

predicates

public

string(11) "\033[38;5;104m"

ColorSchemeDark::C_EXTRA

predicates

public

string(11) "\033[38;5;104m"

ColorSchemeDark::T_EXCL

predicates

public

string(25) "\033[1m\033[48;5;15m\033[38;5;124m"

ColorSchemeDark::T_BY

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeDark::T_MSG

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeDark::T_STACK

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeDark::T_CAUSE

predicates

public

string(11) "\033[38;5;114m"

ColorSchemeDark::TRAIT_HELLO

predicates

public

string(0) ""

ColorSchemeDark::TRAIT_METHOD

predicates

public

string(11) "\033[38;5;227m"

ColorSchemeDark::TRAIT_GOODBYE

predicates

public

string(11) "\033[38;5;110m"

ColorSchemeDark::TEST

predicates

public

string(42) "I am a bhenk\logger\handle\ColorSchemeDark"

ColorSchemeDark::END

predicates

public

Inherited from

ColorSchemeInterface::END

string(4) "\033[0m"

Sat, 29 Apr 2023 12:38:18 +0000

ColorSchemeInterface

namespace

bhenk\logger\handle

predicates

Interface

known implementations

ColorSchemeBright | ColorSchemeDark

Provides color schema for ConsoleHandler

Implementations of this interface may override color constants.


Constants
ColorSchemeInterface::NL

predicates

public

string(0) ""

ColorSchemeInterface::RESET

predicates

public

string(0) ""

ColorSchemeInterface::END

predicates

public

string(4) "\033[0m"

ColorSchemeInterface::DEBUG

predicates

public

string(0) ""

ColorSchemeInterface::INFO

predicates

public

string(0) ""

ColorSchemeInterface::NOTICE

predicates

public

string(0) ""

ColorSchemeInterface::WARNING

predicates

public

string(0) ""

ColorSchemeInterface::ERROR

predicates

public

string(0) ""

ColorSchemeInterface::CRITICAL

predicates

public

string(0) ""

ColorSchemeInterface::ALERT

predicates

public

string(0) ""

ColorSchemeInterface::EMERGENCY

predicates

public

string(0) ""

ColorSchemeInterface::C_DATE

predicates

public

string(0) ""

ColorSchemeInterface::C_CLASS

predicates

public

string(0) ""

ColorSchemeInterface::C_FILE

predicates

public

string(0) ""

ColorSchemeInterface::C_CONTEXT

predicates

public

string(0) ""

ColorSchemeInterface::C_EXTRA

predicates

public

string(0) ""

ColorSchemeInterface::T_EXCL

predicates

public

string(0) ""

ColorSchemeInterface::T_BY

predicates

public

string(0) ""

ColorSchemeInterface::T_MSG

predicates

public

string(0) ""

ColorSchemeInterface::T_STACK

predicates

public

string(0) ""

ColorSchemeInterface::T_CAUSE

predicates

public

string(0) ""

ColorSchemeInterface::TRAIT_HELLO

predicates

public

string(0) ""

ColorSchemeInterface::TRAIT_METHOD

predicates

public

string(0) ""

ColorSchemeInterface::TRAIT_GOODBYE

predicates

public

string(0) ""

ColorSchemeInterface::TEST

predicates

public

string(26) "I'm a ColorSchemeInterface"

Sat, 29 Apr 2023 12:38:18 +0000

ConsoleHandler

namespace

bhenk\logger\handle

predicates

Cloneable | Instantiable

implements

ResettableInterface | HandlerInterface

extends

AbstractHandler

hierarchy

ConsoleHandler -> AbstractHandler -> Handler

Handler class for displaying log output on console


Constructor
ConsoleHandler::__construct

predicates

public | constructor

Outputs log statements to console

This AbstractHandler is especially equipped to be used during development. See ConsoleLoggerTrait on how to switch logging to console for a particular TestCase.

The param $stack_match expects a regular expression. It can be used to suppress the amount of stacktrace elements of Throwables. Par example, the regex "/application\/(bhenk|unit)/i" will only print traces of files that have either /application/bhenk or /application/unit in their filename. Defaults to "/(.*?)/i" - all files.

The param $date_format defaults to a short “H:i:s:u”.

The param $color_scheme points to the (fully qualified) classname of a class implementing the ColorSchemeInterface and defaults to ColorSchemeDark, a dark scheme.

See also AbstractHandler.

public function __construct(
      Parameter #0 [ <optional> Monolog\Level|string|int $level = \Monolog\Level::Debug ]
      Parameter #1 [ <optional> bool $bubble = false ]
      Parameter #2 [ <optional> bool $white_line = true ]
      Parameter #3 [ <optional> ?string $stack_match = NULL ]
      Parameter #4 [ <optional> ?string $date_format = NULL ]
      Parameter #5 [ <optional> ?string $exclamation = NULL ]
      Parameter #6 [ <optional> ?string $color_scheme = NULL ]
 )
param Level | string | int $level - accepted minimum logging level
param bool $bubble - controls the bubbling process of the handler stack
param bool $white_line - print empty line above each log statement (default true)
param ?string $stack_match - reg-ex to match filenames in stack traces
param ?string $date_format - date format for printed log statements
param ?string $exclamation - thrown in when a throwable is reported
param ?string $color_scheme - color scheme for this handler

Methods
ConsoleHandler::getColorScheme

predicates

public

Get the color scheme used by this class

public function getColorScheme(): ColorSchemeInterface

ConsoleHandler::resetCount

predicates

public

Reset the log statement counter

public function resetCount(): void
return void

ConsoleHandler::handle

predicates

public

implements

HandlerInterface::handle

@inheritdoc

Handles a record

All records may be passed to this method, and the handler should discard those that it does not want to handle.

The return value of this function controls the bubbling process of the handler stack. Unless the bubbling is interrupted (by returning true), the Logger class will keep on calling further handlers in the stack with a given log record.

param AbstractHandler LogRecord - $record The record to handle
return bool - true means that this handler handled the record, and that bubbling is not permitted. false means the record was either not processed or that this handler allows bubbling.

@inheritdoc from method HandlerInterface::handle

public function handle(
      Parameter #0 [ <required> Monolog\LogRecord $record ]
 ): bool
param LogRecord $record
return bool

ConsoleHandler::isHandling

predicates

public

implements

HandlerInterface::isHandling

inherited from

AbstractHandler::isHandling

@inheritdoc

Checks whether the given record will be handled by this handler

This is mostly done for performance reasons, to avoid calling processors for nothing.

Handlers should still check the record levels within handle(), returning false in isHandling() is no guarantee that handle() will not be called, and isHandling() might not be called for a given record.

param LogRecord $record - Partial log record having only a level initialized

@inheritdoc from method HandlerInterface::isHandling

public function isHandling(
      Parameter #0 [ <required> Monolog\LogRecord $record ]
 ): bool
param LogRecord $record
return bool

ConsoleHandler::setLevel

predicates

public

inherited from

AbstractHandler::setLevel

Sets minimum logging level at which this handler will be triggered

phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
public function setLevel(
      Parameter #0 [ <required> Monolog\Level|string|int $level ]
 ): self
param Level | string | int $level - Level or level name
return self

ConsoleHandler::getLevel

predicates

public

inherited from

AbstractHandler::getLevel

Gets minimum logging level at which this handler will be triggered

public function getLevel(): Level
return Level

ConsoleHandler::setBubble

predicates

public

inherited from

AbstractHandler::setBubble

Sets the bubbling behavior

public function setBubble(
      Parameter #0 [ <required> bool $bubble ]
 ): self
param bool $bubble - true means that this handler allows bubbling. false means that bubbling is not permitted.
return self

ConsoleHandler::getBubble

predicates

public

inherited from

AbstractHandler::getBubble

Gets the bubbling behavior

public function getBubble(): bool
return bool - true means that this handler allows bubbling. false means that bubbling is not permitted.

ConsoleHandler::reset

predicates

public

implements

ResettableInterface::reset

inherited from

AbstractHandler::reset

@inheritdoc

No DocComment found on method ResettableInterface::reset

public function reset(): void
return void

ConsoleHandler::handleBatch

predicates

public

implements

HandlerInterface::handleBatch

inherited from

Handler::handleBatch

@inheritdoc

Handles a set of records at once

@inheritdoc from method HandlerInterface::handleBatch

public function handleBatch(
      Parameter #0 [ <required> array $records ]
 ): void
param array $records
return void

ConsoleHandler::close

predicates

public

implements

HandlerInterface::close

inherited from

Handler::close

@inheritdoc

Closes the handler

Ends a log cycle and frees all resources used by the handler.

Closing a Handler means flushing all buffers and freeing any open resources/handles.

Implementations have to be idempotent (i.e. it should be possible to call close several times without breakage) and ideally handlers should be able to reopen themselves on handle() after they have been closed.

This is useful at the end of a request and will be called automatically when the object is destroyed if you extend MonologHandlerHandler.

If you are thinking of calling this method yourself, most likely you should be calling ResettableInterface::reset instead. Have a look.

@inheritdoc from method HandlerInterface::close

public function close(): void
return void

ConsoleHandler::__destruct

predicates

public

inherited from

Handler::__destruct

public function __destruct()

ConsoleHandler::__sleep

predicates

public

inherited from

Handler::__sleep

public function __sleep()

Sat, 29 Apr 2023 12:38:18 +0000


Sat, 29 Apr 2023 12:38:18 +0000

log

Depends on

Dependency invoked by

build

Log | Req

Logging facilities

Log

namespace

bhenk\logger\log

predicates

Cloneable | Instantiable

known subclasses

Req

Default log agent

The type of Logger used by this log agent defaults to “log” and has a two logfiles, one for all statements. Log messages exceeding a certain level will also be logged to an error logfile.

Documentation of logging calls copied from https://www.php-fig.org/psr/psr-3/.


Methods
Log::getType

predicates

public | static

Get the type of logger used by this log agent

public static function getType(): LoggerTypes
return LoggerTypes - type currently in use.

Log::setType

predicates

public | static

Set the type of logger used by this log agent

public static function setType(
      Parameter #0 [ <required> bhenk\logger\build\LoggerTypes $type ]
 ): LoggerTypes
param LoggerTypes $type - the new type.
return LoggerTypes - the old type.

Log::setLevel

predicates

public | static

Set the level at which the handlers of this log agents logger will fire

Warning: do not use this method for logging configuration. Use a logger definition file instead.

Caveat: this method will only have effect on implementations of logger that expose the method getHandlers() and only on handlers that expose the method setLevel().

public static function setLevel(
      Parameter #0 [ <required> Monolog\Level|Psr\Log\LogLevel|string|int $level ]
 ): void
param Level | LogLevel | string | int $level - the level to set on the handlers of this log agent.
return void

Log::emergency

predicates

public | static

System is unusable

public static function emergency(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::alert

predicates

public | static

Action must be taken immediately

Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.

public static function alert(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::critical

predicates

public | static

Critical conditions

Example: Application component unavailable, unexpected exception.

public static function critical(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::error

predicates

public | static

Runtime errors that do not require immediate action but should typically be logged and monitored

public static function error(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::warning

predicates

public | static

Exceptional occurrences that are not errors

Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.

public static function warning(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::notice

predicates

public | static

Normal but significant events

public static function notice(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::info

predicates

public | static

Interesting events

Example: User logs in, SQL logs.

public static function info(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::debug

predicates

public | static

Detailed debug information

public static function debug(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Log::log

predicates

public | static

Logs with an arbitrary level

public static function log(
      Parameter #0 [ <required> Monolog\Level|string|int $level ]
      Parameter #1 [ <required> Stringable|string $message ]
      Parameter #2 [ <optional> array $context = [] ]
 ): void
param Level | string | int $level
param Stringable | string $message
param array $context
return void

Sat, 29 Apr 2023 12:38:18 +0000

Req

namespace

bhenk\logger\log

predicates

Cloneable | Instantiable

extends

Log

hierarchy

Req -> Log

A log agent for recording request parameters

The type of Logger used by this log agent defaults to “req”.

Documentation of logging calls copied from https://www.php-fig.org/psr/psr-3/.


Methods
Req::getType

predicates

public | static

implements

Log::getType

@inheritdoc

Get the type of logger used by this log agent

return LoggerTypes - type currently in use.

@inheritdoc from method Log::getType

public static function getType(): LoggerTypes

Req::setType

predicates

public | static

implements

Log::setType

@inheritdoc

Set the type of logger used by this log agent

param LoggerTypes $type - the new type.
return LoggerTypes - the old type.

@inheritdoc from method Log::setType

public static function setType(
      Parameter #0 [ <required> bhenk\logger\build\LoggerTypes $type ]
 ): LoggerTypes
param LoggerTypes $type

Req::setLevel

predicates

public | static

inherited from

Log::setLevel

Set the level at which the handlers of this log agents logger will fire

Warning: do not use this method for logging configuration. Use a logger definition file instead.

Caveat: this method will only have effect on implementations of logger that expose the method getHandlers() and only on handlers that expose the method setLevel().

public static function setLevel(
      Parameter #0 [ <required> Monolog\Level|Psr\Log\LogLevel|string|int $level ]
 ): void
param Level | LogLevel | string | int $level - the level to set on the handlers of this log agent.
return void

Req::emergency

predicates

public | static

inherited from

Log::emergency

System is unusable

public static function emergency(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::alert

predicates

public | static

inherited from

Log::alert

Action must be taken immediately

Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.

public static function alert(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::critical

predicates

public | static

inherited from

Log::critical

Critical conditions

Example: Application component unavailable, unexpected exception.

public static function critical(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::error

predicates

public | static

inherited from

Log::error

Runtime errors that do not require immediate action but should typically be logged and monitored

public static function error(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::warning

predicates

public | static

inherited from

Log::warning

Exceptional occurrences that are not errors

Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.

public static function warning(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::notice

predicates

public | static

inherited from

Log::notice

Normal but significant events

public static function notice(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::info

predicates

public | static

inherited from

Log::info

Interesting events

Example: User logs in, SQL logs.

public static function info(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::debug

predicates

public | static

inherited from

Log::debug

Detailed debug information

public static function debug(
      Parameter #0 [ <required> Stringable|string $message ]
      Parameter #1 [ <optional> array $context = [] ]
 ): void
param Stringable | string $message
param array $context
return void

Req::log

predicates

public | static

inherited from

Log::log

Logs with an arbitrary level

public static function log(
      Parameter #0 [ <required> Monolog\Level|string|int $level ]
      Parameter #1 [ <required> Stringable|string $message ]
      Parameter #2 [ <optional> array $context = [] ]
 ): void
param Level | string | int $level
param Stringable | string $message
param array $context
return void

Sat, 29 Apr 2023 12:38:18 +0000


Sat, 29 Apr 2023 12:38:18 +0000

unit

Depends on

Dependency invoked by

build

ConsoleLoggerTrait

handle

ConsoleLoggerTrait

log

ConsoleLoggerTrait

Influence logging behaviour during testing

ConsoleLoggerTrait

namespace

bhenk\logger\unit

predicates

Trait

Trait capable of redirecting log output to console

Note

Caveat: only log statements logged via Log will be redirected. Test cases that want to inspect log output of classes under test use this trait. It is recommended to use this trait together with LogAttribute.

Example usage:

class SomeTest extends TestCase {
    use ConsoleLoggerTrait;
...

All log statements via Log will be redirected during runtime of the TestCase, permanently. At least until you remove the use statement. When more flexibility is required also use LogAttribute.

#[LogAttribute()]
class SomeTest extends TestCase {
    use ConsoleLoggerTrait;
...

All log statements via Log will be redirected. To stop redirecting log statements for the entire TestCase just type false as the first argument for LogAttribute. To change the Level of all log statements that pass to console do something like #[LogAttribute(true, Level::Error)]. When more fine-grained control is needed use LogAttribute also on individual test methods.

#[LogAttribute(false)]
public function testSomeFeature() : void {
     ...
}

Suppress all logging via console of code touched by SomeFeature. When revisiting the test method just change the LogAttribute parameter to true. Optionally change the level of log statements seen via console as well.

The on/off setting of LogAttribute on class level has precedence over that on method level. A class with #[LogAttribute(false)] will never output via console.

The setting of the level parameter of LogAttribute on individual methods has precedence over that set on class level.

If you override one of the PHPUnit fixtures make sure to call the corresponding trait-method:

#[LogAttribute(true)]
class ResourceTest extends TestCase {
    use ConsoleLoggerTrait {
        setUp as public traitSetUp;
    }

    private Resource $resource;

    public function setUp(): void {
        $this->traitSetUp();
        $this->resource = new Resource();
    }

This trait calls on Log to set the type of logger temporarily to LoggerTypes::clt. Skies look bright if the logger of this type has the handler ConsoleHandler. If so, this trait will use the ColorSchemeInterface set on this handler. Otherwise, a RuntimeException will be thrown with the message that you messed up the code.


Methods
ConsoleLoggerTrait::setUpBeforeClass

predicates

public | static

Sets up before the TestCase starts running

If LogAttribute on class level is absent or enabled, will print a line to console with the name of the TestCase. Will call on parent::setUpBeforeClass() after this.

public static function setUpBeforeClass(): void
return void

ConsoleLoggerTrait::tearDownAfterClass

predicates

public | static

Tears down after the TestCase has run

If LogAttribute on class level is absent or enabled, will print a farewell message to console as demarcation of the TestCase. Will call on parent::tearDownAfterClass() after this.

public static function tearDownAfterClass(): void
return void

ConsoleLoggerTrait::setUp

predicates

public

Set up before an individual test method starts running

If LogAttribute on method level is absent or enabled, will print the name of the method to console. Sets the LoggerTypes::clt as type on Log. Will call on parent::setUp() after this.

public function setUp(): void
return void

ConsoleLoggerTrait::tearDown

predicates

public

Resets the Logger type

Will reset the Log to its original LoggerType. Calls parent::tearDown() after this.

public function tearDown(): void
return void

Sat, 29 Apr 2023 12:38:18 +0000

LogAttribute

namespace

bhenk\logger\unit

predicates

Cloneable | Instantiable

Attribute to influence logging behavior


Constructor
LogAttribute::__construct

predicates

public | constructor

Constructs a LogAttribute

public function __construct(
      Parameter #0 [ <optional> bool $on = true ]
      Parameter #1 [ <optional> Monolog\Level $level = \Monolog\Level::Debug ]
 )
param bool $on - set attribute on or off. Default true.
param Level $level - set the level of log output. Default Level::Debug.

Sat, 29 Apr 2023 12:38:18 +0000


Sat, 29 Apr 2023 12:38:18 +0000


Sat, 29 Apr 2023 12:38:18 +0000