Oihana PHP System

MonoLogManager extends LoggerManager

MonoLogManager is a PSR-3 compatible logger manager using Monolog.

This class provides:

  • Creation of a Monolog logger with a rotating file handler.
  • Customizable log formats and date formats.
  • Options for inline line breaks, ignoring empty context/extra, and stack traces.
  • Management of file and directory permissions for log storage. When a log directory does not exist, it is automatically created using the configured dirPermissions and a temporary umask of 0002 to ensure group writable directories (e.g., 0664 / 2775) for collaborative environments.
  • Automatic error and exception handling registration via Monolog's ErrorHandler.

Example usage:

$loggerManager = new MonoLogManager
([
    'directory' => '/var/log/myapp',
    'filePermissions' => 0664,
    'allowInlineLineBreaks' => true,
    'level' => Level::Info,
    'maxFiles' => 7
]);

$logger = $loggerManager->createLogger();
$logger->info('Application started');
Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Constants

DEFAULT_EXTENSION  = '.log'
Default log file extension.
DEFAULT_NAME  = 'log'
Default log file name.
DEFAULT_PATH  = 'log'
Default log folder path (relative to $directory).

Properties

$allowInlineLineBreaks  : bool
Whether to allow inline line breaks in log entries.
$bubbles  : bool
Indicates if the logger should bubble messages to higher-level loggers.
$dateFormat  : string
The date format to use in log entries.
$directory  : string
Default permissions for newly created directories.
$dirPermissions  : int|float
The directory permission.
$extension  : string
The file extension used for log files (e.g., ".log").
$filePermissions  : int|float
File permissions for new log files.
$format  : string
Format string for log messages.
$ignoreEmptyContextAndExtra  : bool
Whether to ignore empty context and extra arrays in log messages.
$includeStackTraces  : bool
Whether to include exception stack traces in log messages.
$level  : int|Level
The default log level for the logger (Monolog\Level or int).
$maxFiles  : int
Maximum number of log files to keep in rotation.
$name  : string|null
Optional name of the logging channel.
$path  : string
Subfolder or path where log files are stored (relative to $directory).
$formatter  : FormatterInterface|null
Internal line formatter instance for Monolog.

Methods

__construct()  : mixed
Creates a new MonoLogManager instance.
clear()  : bool
Clears the content of a specific log file.
countLines()  : int
Returns the number of lines in a log file.
createLog()  : Log|null
Parses a log line into a structured array.
createLogger()  : LoggerInterface
Creates and configures a logger instance.
ensureDirectory()  : void
Ensure the log directory exists and is writable.
getDirectory()  : string
Returns the full path of the log directory.
getExtension()  : string
Returns the file extension used for log files.
getFileName()  : string
Returns the base name of the log file.
getFilePath()  : string
Returns the full path to a log file.
getFormatter()  : FormatterInterface
Retrieves the formatter instance.
getLoggerFiles()  : array<string|int, mixed>|false
Returns the list of log files in the log directory matching the current logger name and extension.
getLogLines()  : array<string|int, mixed>|null
Returns the lines of a log file as an array of structured entries.

Constants

DEFAULT_EXTENSION

Default log file extension.

public mixed DEFAULT_EXTENSION = '.log'

DEFAULT_NAME

Default log file name.

public mixed DEFAULT_NAME = 'log'

DEFAULT_PATH

Default log folder path (relative to $directory).

public mixed DEFAULT_PATH = 'log'

Properties

$allowInlineLineBreaks

Whether to allow inline line breaks in log entries.

public bool $allowInlineLineBreaks = true

$bubbles

Indicates if the logger should bubble messages to higher-level loggers.

public bool $bubbles = true

$dateFormat

The date format to use in log entries.

public string $dateFormat = 'Y-m-d H:i:s'

Defaults to "Y-m-d H:i:s".

$directory

Default permissions for newly created directories.

public string $directory = \oihana\enums\Char::EMPTY

Group writable (g+w) for collaborative environments.

$dirPermissions

The directory permission.

public int|float $dirPermissions = 0775

$extension

The file extension used for log files (e.g., ".log").

public string $extension = '.log'

$filePermissions

File permissions for new log files.

public int|float $filePermissions = 0664

Defaults to 0664.

$format

Format string for log messages.

public string $format = "%datetime% %channel% %level_name% %message% %context% %extra%\n"

$ignoreEmptyContextAndExtra

Whether to ignore empty context and extra arrays in log messages.

public bool $ignoreEmptyContextAndExtra = true

$includeStackTraces

Whether to include exception stack traces in log messages.

public bool $includeStackTraces = false

$level

The default log level for the logger (Monolog\Level or int).

public int|Level $level = \Monolog\Level::Debug

$maxFiles

Maximum number of log files to keep in rotation.

public int $maxFiles = 0

$name

Optional name of the logging channel.

public string|null $name = null

Used as prefix for log files and as a descriptive label.

$path

Subfolder or path where log files are stored (relative to $directory).

public string $path = \oihana\enums\Char::EMPTY

$formatter

Internal line formatter instance for Monolog.

protected FormatterInterface|null $formatter = null

Methods

__construct()

Creates a new MonoLogManager instance.

public __construct([array{allowInlineLineBreaks?: bool|null, bubbles?: bool|null, directory?: string|null, dirPermissions?: int|null, filePermissions?: int|null, extension?: string|null, path?: string|null, dateFormat?: string|null, format?: string|null, includeStackTraces?: bool|null, ignoreEmptyContextAndExtra?: bool|null, level?: int|null, maxFiles?: int|null} $init = [] ][, string|null $name = null ]) : mixed
Parameters
$init : array{allowInlineLineBreaks?: bool|null, bubbles?: bool|null, directory?: string|null, dirPermissions?: int|null, filePermissions?: int|null, extension?: string|null, path?: string|null, dateFormat?: string|null, format?: string|null, includeStackTraces?: bool|null, ignoreEmptyContextAndExtra?: bool|null, level?: int|null, maxFiles?: int|null} = []

Optional initialization options.

$name : string|null = null

Optional logger channel name.

clear()

Clears the content of a specific log file.

public clear(string $file) : bool
Parameters
$file : string

Log file name.

Tags
throws
FileException

If clearing fails due to filesystem permissions or errors.

Return values
bool

True if the file was cleared, false if file does not exist.

countLines()

Returns the number of lines in a log file.

public countLines(string $file) : int
Parameters
$file : string

Log file name.

Tags
throws
FileException

If file cannot be read.

Return values
int

Number of lines in the file.

createLog()

Parses a log line into a structured array.

public createLog(string $line) : Log|null

Example: "2025-08-21 10:30:00 INFO Some message" becomes: [ 'date' => '2025-08-21', 'time' => '10:30:00', 'level' => 'INFO', 'message' => 'Some message' ]

Parameters
$line : string

Raw log line.

Tags
throws
ReflectionException
Return values
Log|null

Parsed log entry or null if line is empty or malformed.

createLogger()

Creates and configures a logger instance.

public createLogger() : LoggerInterface

This method sets up a logger with a rotating file handler, custom formatter, and registers it for error handling to capture system errors and exceptions.

Return values
LoggerInterface

The configured logger instance.

ensureDirectory()

Ensure the log directory exists and is writable.

public ensureDirectory() : void

If the directory does not exist, it will be created recursively. A temporary umask 0002 is applied so that the directory is group writable according to $this->dirPermissions (default 2775). Files created within the directory will inherit group write permission (0664 by default).

Throws a DirectoryException if the directory cannot be created or is not writable.

Tags
throws
DirectoryException

if the directory cannot be created or is not writable.

getDirectory()

Returns the full path of the log directory.

public getDirectory() : string

Combines the base $this->directory and $this->path using canonical path normalization. The returned path is absolute (or relative if $this->directory is relative) and can be safely used for file operations.

Return values
string

Absolute or relative path to the log folder.

getExtension()

Returns the file extension used for log files.

public getExtension() : string
Return values
string

Log file extension, including dot (e.g., ".log").

getFileName()

Returns the base name of the log file.

public getFileName() : string
Return values
string

Log file name.

getFilePath()

Returns the full path to a log file.

public getFilePath([string|null $file = null ]) : string

If $file is null, returns the default log file path: /. Uses joinPaths() to safely concatenate directory and file name.

Parameters
$file : string|null = null

Optional custom file name. Defaults to .

Return values
string

Full path to the log file.

getFormatter()

Retrieves the formatter instance.

public getFormatter() : FormatterInterface
Return values
FormatterInterface

getLoggerFiles()

Returns the list of log files in the log directory matching the current logger name and extension.

public getLoggerFiles() : array<string|int, mixed>|false

The search uses findFiles() with options:

  • Pattern: "*"
  • Mode: files only
  • Order: ascending by file name

Throws a DirectoryException if the log directory cannot be read.

Tags
throws
DirectoryException

if the log directory cannot be read.

Return values
array<string|int, mixed>|false

List of log file names or false on error.

getLogLines()

Returns the lines of a log file as an array of structured entries.

public getLogLines(string|null $file) : array<string|int, mixed>|null
Parameters
$file : string|null

Log file name.

Tags
throws
FileException

If the file cannot be read.

Return values
array<string|int, mixed>|null

Array of parsed log entries or null if file does not exist.


        
On this page

Search results