Skip to content

Commit

Permalink
Added ability to change log level tag
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardoboss committed Apr 29, 2022
1 parent 183eeb3 commit e3329a5
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 32 deletions.
93 changes: 62 additions & 31 deletions src/Console.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use BadMethodCallException;
use DateTime;
use InvalidArgumentException;
use RangeException;
use Stringable;
use function count;
Expand Down Expand Up @@ -58,16 +59,7 @@
*/
class Console
{
private static bool $timestamps = true;
private static bool $colors = true;
private static string $timestamp_format = "d.m.y H:i:s.v";
private static int $log_level = 0;

private static string $colorFormat = "\033[%s;1m"; // 16-bit colors
// private static $extended = "\033[%s;5;%sm"; // 256-bit colors; 38 = foreground, 48 = background
private static string $reset = "\033[0m";

private static array $foregroundColors = [
public const FOREGROUNDS = [
'black' => 30,
'red' => 31,
'green' => 32,
Expand All @@ -88,7 +80,7 @@ class Console
'default' => 39,
];

private static array $backgroundColors = [
public const BACKGROUNDS = [
'black' => 40,
'red' => 41,
'green' => 42,
Expand All @@ -109,14 +101,34 @@ class Console
'default' => 49,
];

private static array $availableOptions = [
public const OPTIONS = [
'bold' => ['set' => 1, 'unset' => 22],
'underscore' => ['set' => 4, 'unset' => 24],
'blink' => ['set' => 5, 'unset' => 25],
'reverse' => ['set' => 7, 'unset' => 27],
'conceal' => ['set' => 8, 'unset' => 28],
];

private static bool $timestamps = true;
private static bool $colors = true;
private static string $timestamp_format = "d.m.y H:i:s.v";
private static int $log_level = 0;

private static string $colorFormat = "\033[%s;1m"; // 16-bit colors
// private static $extended = "\033[%s;5;%sm"; // 256-bit colors; 38 = foreground, 48 = background
private static string $reset = "\033[0m";

private static array $logLevelTags = [
'debug' => 'DEBUG ',
'info' => 'INFO ',
'notice' => 'NOTICE ',
'warning' => 'WARNING ',
'error' => 'ERROR ',
'critical' => 'CRITICAL ',
'alert' => 'ALERT ',
'emergency' => 'EMERGENCY',
];

public static function timestamps(bool $enable = true): void
{
self::$timestamps = $enable;
Expand All @@ -141,9 +153,27 @@ public static function logLevel(int $level = 0): void
self::$log_level = $level;
}

public static function logLevelTag(string $level, string $tag, bool $autoAdjustLengths = true): void
{
if (!array_key_exists($level, self::$logLevelTags)) {
throw new InvalidArgumentException("Log level '$level' is not valid.");
}

self::$logLevelTags[$level] = $tag;

if (!$autoAdjustLengths) {
return;
}

$maxLength = max(array_map('mb_strlen', array_map('rtrim', self::$logLevelTags)));
foreach (self::$logLevelTags as $key => $value) {
self::$logLevelTags[$key] = str_pad(rtrim($value), $maxLength, ' ', STR_PAD_RIGHT);
}
}

public static function link(string $link): string
{
return Console::cyan(Console::underscore($link));
return self::cyan(self::underscore($link));
}

public static function debug(string $message, ...$args): void
Expand All @@ -152,7 +182,7 @@ public static function debug(string $message, ...$args): void
return;
}

self::writeln("[DEB] " . vsprintf($message, $args), 'gray');
self::writeln("[" . self::$logLevelTags['debug'] . "] " . vsprintf($message, $args), 'gray');
}

public static function info(string $message, ...$args): void
Expand All @@ -161,7 +191,7 @@ public static function info(string $message, ...$args): void
return;
}

self::writeln("[INF] " . vsprintf($message, $args));
self::writeln("[" . self::$logLevelTags['info'] . "] " . vsprintf($message, $args));
}

public static function notice(string $message, ...$args): void
Expand All @@ -170,7 +200,7 @@ public static function notice(string $message, ...$args): void
return;
}

self::writeln("[NTC] " . vsprintf($message, $args), 'blue');
self::writeln("[" . self::$logLevelTags['notice'] . "] " . vsprintf($message, $args), 'blue');
}

public static function warn(string $message, ...$args): void
Expand All @@ -179,7 +209,7 @@ public static function warn(string $message, ...$args): void
return;
}

self::writeln("[WRN] " . vsprintf($message, $args), 'yellow');
self::writeln("[" . self::$logLevelTags['warning'] . "] " . vsprintf($message, $args), 'yellow');
}

public static function error(string $message, ...$args): void
Expand All @@ -188,7 +218,7 @@ public static function error(string $message, ...$args): void
return;
}

self::writeln("[ERR] " . vsprintf($message, $args), 'red', null, [], true);
self::writeln("[" . self::$logLevelTags['error'] . "] " . vsprintf($message, $args), 'red', error: true);
}

public static function critical(string $message, ...$args): void
Expand All @@ -197,7 +227,7 @@ public static function critical(string $message, ...$args): void
return;
}

self::writeln("[CRT] " . vsprintf($message, $args), 'magenta', null, ['bold'], true);
self::writeln("[" . self::$logLevelTags['critical'] . "] " . vsprintf($message, $args), 'magenta', options: ['bold'], error: true);
}

public static function alert(string $message, ...$args): void
Expand All @@ -206,12 +236,12 @@ public static function alert(string $message, ...$args): void
return;
}

self::writeln("[ALT] " . vsprintf($message, $args), null, 'yellow', ['bold'], true);
self::writeln("[" . self::$logLevelTags['alert'] . "] " . vsprintf($message, $args), background: 'yellow', options: ['bold'], error: true);
}

public static function emergency(string $message, ...$args): void
{
self::writeln("[EGY] " . vsprintf($message, $args), null, 'red', ['bold', 'underscore'], true);
self::writeln("[" . self::$logLevelTags['emergency'] . "] " . vsprintf($message, $args), background: 'red', options: ['bold'], error: true);
}

public static function strip(string $formattedMessage): string
Expand Down Expand Up @@ -264,7 +294,7 @@ public static function table(iterable $data, bool $ascii = false, bool $compact
}, $columns);

$hsep = $ascii ? '-' : '';
$vsep = Console::$borderColor($ascii ? '|' : '');
$vsep = self::$borderColor($ascii ? '|' : '');
$cross = $ascii ? '+' : '';

$headerHsep = $ascii ? '=' : '';
Expand Down Expand Up @@ -367,10 +397,11 @@ public static function writeln(
?string $foreground = null,
?string $background = null,
array $options = [],
string $eol = "\r\n",
bool $error = false
): void
{
self::write($message, $foreground, $background, $options, "\r\n", $error);
self::write($message, $foreground, $background, $options, $eol, $error);
}

public static function write(
Expand Down Expand Up @@ -409,17 +440,17 @@ public static function apply(
$unsetCodes = [];

if (null !== $foreground) {
$setCodes[] = self::$foregroundColors[$foreground];
$unsetCodes[] = self::$foregroundColors['default'];
$setCodes[] = self::FOREGROUNDS[$foreground];
$unsetCodes[] = self::FOREGROUNDS['default'];
}

if (null !== $background) {
$setCodes[] = self::$backgroundColors[$background];
$unsetCodes[] = self::$backgroundColors['default'];
$setCodes[] = self::BACKGROUNDS[$background];
$unsetCodes[] = self::BACKGROUNDS['default'];
}

foreach ($options as $option) {
$option = self::$availableOptions[$option];
$option = self::OPTIONS[$option];

$setCodes[] = $option['set'];
$unsetCodes[] = $option['unset'];
Expand All @@ -446,19 +477,19 @@ public static function __callStatic(string $name, array $arguments): string
{
$name = strtolower($name);

if (array_key_exists($name, self::$availableOptions)) {
if (array_key_exists($name, self::OPTIONS)) {
return self::apply($arguments[0], null, null, [$name]);
}

$backPos = stripos($name, 'back');
$background = $backPos !== false;
$color = $background ? substr($name, 0, $backPos) : $name;

if ($background && array_key_exists($color, self::$backgroundColors)) {
if ($background && array_key_exists($color, self::BACKGROUNDS)) {
return self::apply($arguments[0], null, $color, []);
}

if (array_key_exists($color, self::$foregroundColors)) {
if (array_key_exists($color, self::FOREGROUNDS)) {
return self::apply($arguments[0], $color, null, []);
}

Expand Down
15 changes: 14 additions & 1 deletion test.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@
['name', 'age', 'email'],
[Console::yellow('Johnson'), '25', '[email protected]'],
[Console::yellow('Jane'), '24', '[email protected]'],
], compact: true, borderColor: 'red') as $line) {
], compact: true, borderColor: 'green') as $line) {
Console::info($line);
}

Console::emergency("This has a really long tag");
Console::logLevelTag('info', 'INFORMATION');
Console::info("You can also adjust the tag for each log level.");
Console::info("The padding on the right gets adjusted automatically.");
Console::logLevelTag('emergency', 'EMERG');
Console::emergency("Now the tag is shorter.");
Console::logLevelTag('warning', 'WARN');
Console::logLevelTag('critical', 'CRIT');
Console::logLevelTag('notice', 'NOTI');
Console::logLevelTag('info', 'INFO');
Console::info("And even shorter");
Console::emergency("This is fine.");

0 comments on commit e3329a5

Please sign in to comment.