Updated project.json

Added Console.php
Added Utilities.php
Added Validate.php
Added \LogLib\Objects > Backtrace
Added \LogLib\Objects > Event
Added \LogLib\Objects > Options
Added \LogLib\Interfaces >  HandlerInterface
Added \LogLib\Abstracts >  LevelType.php
Added \LogLib\Abstracts >  ConsoleColors.php
Added \LogLib\Abstracts > CallType
Added project.json (NCC)
This commit is contained in:
Netkas 2022-12-13 23:21:19 -05:00
parent c77fb2da6b
commit ad7dba97d2
11 changed files with 986 additions and 0 deletions

44
project.json Normal file
View file

@ -0,0 +1,44 @@
{
"project": {
"compiler": {
"extension": "php",
"minimum_version": "8.0",
"maximum_version": "8.2"
},
"options": []
},
"assembly": {
"name": "LogLib",
"package": "net.nosial.loglib",
"company": "Nosial",
"copyright": "Copyright (c) 2022 Nosial",
"version": "1.0.0",
"uuid": "de1deca6-7b65-11ed-a8b0-a172264634d8"
},
"build": {
"source_path": "src",
"default_configuration": "release",
"define_constants": {
"ASSEMBLY_NAME": "%ASSEMBLY.NAME%",
"ASSEMBLY_PACKAGE": "%ASSEMBLY.PACKAGE%",
"ASSEMBLY_VERSION": "%ASSEMBLY.VERSION%",
"ASSEMBLY_UID": "%ASSEMBLY.UID%"
},
"configurations": [
{
"name": "debug",
"output_path": "build/debug",
"define_constants": {
"DEBUG": "1"
}
},
{
"name": "release",
"output_path": "build/release",
"define_constants": {
"DEBUG": "0"
}
}
]
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace LogLib\Abstracts;
abstract class CallType
{
const MethodCall = '->';
const StaticCall = '::';
const FunctionCall = ' ';
}

View file

@ -0,0 +1,43 @@
<?php
namespace LogLib\Abstracts;
abstract class ConsoleColors
{
const Black = "0;30";
const DarkGray = "1;30";
const Blue = "0;34";
const LightBlue = "1;34";
const Green = "0;32";
const LightGreen = "1;32";
const Cyan = "0;36";
const LightCyan = "1;36";
const Red = "0;31";
const LightRed = "1;31";
const Purple = "0;35";
const LightPurple = "1;35";
const Brown = "0;33";
const Yellow = "1;33";
const LightGray = "0;37";
const White = "1;37";
const Reset = "0";
const All = [
self::Black,
self::DarkGray,
self::Blue,
self::LightBlue,
self::Green,
self::LightGreen,
self::Cyan,
self::LightCyan,
self::Red,
self::LightRed,
self::Purple,
self::LightPurple,
self::Brown,
self::Yellow,
self::LightGray,
self::White
];
}

View file

@ -0,0 +1,27 @@
<?php
namespace LogLib\Abstracts;
abstract class LevelType
{
const Silent = 0;
const Fatal = 1;
const Error = 2;
const Warning = 3;
const Info = 4;
const Verbose = 5;
const Debug = 6;
/**
* All types.
*/
const All = [
self::Silent,
self::Fatal,
self::Error,
self::Warning,
self::Info,
self::Verbose,
self::Debug
];
}

View file

@ -0,0 +1,220 @@
<?php
/** @noinspection PhpMissingFieldTypeInspection */
namespace LogLib\Classes;
use LogLib\Abstracts\ConsoleColors;
use LogLib\Abstracts\LevelType;
use LogLib\Objects\Event;
use LogLib\Objects\Options;
class Console
{
/**
* @var array
*/
private static $ApplicationColors = [];
/**
* Formats the application color for the console
*
* @param string $application
* @return string
*/
private static function formatAppColor(string $application): string
{
if(!isset(self::$ApplicationColors[$application]))
{
$colors = ConsoleColors::All;
$color = $colors[array_rand($colors)];
self::$ApplicationColors[$application] = $color;
}
return self::$ApplicationColors[$application];
}
/**
* Returns a color formatted string for the console
*
* @param string $text
* @param string $color
* @return string
*/
private static function color(string $text, string $color): string
{
return "\033[{$color}m$text\033[0m";
}
/**
* Colorizes a event string for the console
*
* @param Event $event
* @param string $text
* @return string
*/
private static function colorize(Event $event, string $text): string
{
$color = null;
switch($event->Level)
{
case LevelType::Debug:
$color = ConsoleColors::LightPurple;
break;
case LevelType::Verbose:
$color = ConsoleColors::LightCyan;
break;
case LevelType::Info:
$color = ConsoleColors::White;
break;
case LevelType::Warning:
$color = ConsoleColors::Yellow;
break;
case LevelType::Fatal:
$color = ConsoleColors::Red;
break;
case LevelType::Error:
$color = ConsoleColors::LightRed;
break;
}
if($color == null)
return Utilities::levelToString($text);
return self::color(Utilities::levelToString($text), $color);
}
/**
* Returns the formatted backtrace
*
* @param Event $event
* @return string|null
*/
private static function parseBacktrace(Event $event): ?string
{
$backtrace = null;
if($event->Backtrace !== null && count($event->Backtrace) > 0)
{
foreach($event->Backtrace as $item)
{
if($item->Class !== 'LogLib\\Log')
{
$backtrace = $item;
break;
}
}
}
$backtrace_output = null;
if($backtrace !== null)
{
if($backtrace->Class !== null)
{
$backtrace_output = $backtrace->Class . $backtrace->Type . $backtrace->Function . '()';
}
else
{
$backtrace_output = $backtrace->Function . '()';
}
if($backtrace->Line !== null)
$backtrace_output .= ':' . $backtrace->Line;
}
return $backtrace_output;
}
/**
* Regular console output for the event object
*
* @param Options $options
* @param Event $event
* @return void
*/
public static function out(Options $options, Event $event): void
{
// If the current level is verbose or higher, then we need to output the backtrace
if(Validate::checkLevelType(LevelType::Verbose, $options->getOutputLevel()))
{
$backtrace_output = self::parseBacktrace($event);
if($options->isConsoleAnsiColors())
{
print(sprintf(
"%s [%s] [%s] (%s) - %s" . PHP_EOL,
$event->getTimestamp(),
self::formatAppColor($options->getApplicationName()),
self::colorize($event, $event->Level),
$backtrace_output !== null ? $backtrace_output : 'λ',
$event->Message
));
}
else
{
print(sprintf(
"%s [%s] [%s] - %s - %s" . PHP_EOL,
$event->getTimestamp(), $options->getApplicationName(), $event->Level,
$backtrace_output !== null ? $backtrace_output : 'lambda',
$event->Message
));
}
if($event->Exception !== null)
self::outException($event->Exception);
}
elseif(!Validate::checkLevelType(LevelType::Fatal, $options->getOutputLevel()))
{
if($options->isConsoleAnsiColors())
{
print(sprintf(
"%s [%s] [%s] - %s" . PHP_EOL,
$event->getTimestamp(),
self::formatAppColor($options->getApplicationName()),
self::colorize($event, $event->Level),
$event->Message
));
}
else
{
print(sprintf(
"%s [%s] [%s] - %s" . PHP_EOL,
$event->getTimestamp(), $options->getApplicationName(), $event->Level,
$event->Message
));
}
if($event->Exception !== null)
self::outException($event->Exception);
}
}
/**
* Prints out the exception details
*
* @param array $exception
* @return void
*/
private static function outException(array $exception): void
{
$trace_header = self::color($exception['file'] . ':' . $exception['line'], ConsoleColors::Purple);
$trace_error = self::color('error: ', ConsoleColors::Red);
print($trace_header . ' ' . $trace_error . $exception['message'] . PHP_EOL);
print(sprintf('Error code: %s', $exception['code']) . PHP_EOL);
$trace = $exception['trace'];
if(count($trace) > 1)
{
print('Stack Trace:' . PHP_EOL);
foreach($trace as $item)
{
print( ' - ' . self::color($item['file'], ConsoleColors::Red) . ':' . $item['line'] . PHP_EOL);
}
}
if($exception['previous'] !== null)
{
print('Previous Exception:' . PHP_EOL);
self::outException($exception['previous']);
}
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace LogLib\Classes;
use LogLib\Abstracts\LevelType;
use LogLib\Objects\Backtrace;
use Throwable;
class Utilities
{
/**
* Returns the current backtrace
*
* @return Backtrace[]
*/
public static function getBacktrace(): array
{
if(!function_exists('debug_backtrace'))
return [];
$backtrace = debug_backtrace();
$results = [];
foreach($backtrace as $trace)
{
$results[] = Backtrace::fromArray($trace);
}
return $results;
}
/**
* @param Throwable $e
* @return array
*/
public static function exceptionToArray(Throwable $e): array
{
$results = [
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
];
if($e->getPrevious() !== null)
{
$results['previous'] = self::exceptionToArray($e->getPrevious());
}
return $results;
}
/**
* Returns the current level type as a string
*
* @param int $level
* @return string
*/
public static function levelToString(int $level): string
{
return match ($level)
{
LevelType::Debug => 'DBG',
LevelType::Verbose => 'VRB',
LevelType::Info => 'INF',
LevelType::Warning => 'WRN',
LevelType::Fatal => 'CRT',
LevelType::Error => 'ERR',
default => 'UNK',
};
}
}

View file

@ -0,0 +1,109 @@
<?php
namespace LogLib\Classes;
use LogLib\Abstracts\LevelType;
class Validate
{
/**
* Validates that the level is valid
*
* @param string $level
* @return bool
*/
public static function LevelType(string $level): bool
{
return in_array($level, LevelType::All);
}
/**
* Checks if the input level matches the current level
*
* @param string $input
* @param string $current_level
* @return bool
*/
public static function checkLevelType(string $input, string $current_level): bool
{
if($input == null)
return false;
if($current_level == null)
return false;
$input = strtolower($input);
if(!Validate::LevelType($input))
return false;
$current_level = strtolower($current_level);
if(!Validate::LevelType($current_level))
return false;
switch($current_level)
{
case LevelType::Debug:
$levels = [
LevelType::Debug,
LevelType::Verbose,
LevelType::Info,
LevelType::Warning,
LevelType::Fatal,
LevelType::Error
];
if(in_array($input, $levels))
return true;
return false;
case LevelType::Verbose:
$levels = [
LevelType::Verbose,
LevelType::Info,
LevelType::Warning,
LevelType::Fatal,
LevelType::Error
];
if(in_array($input, $levels))
return true;
return false;
case LevelType::Info:
$levels = [
LevelType::Info,
LevelType::Warning,
LevelType::Fatal,
LevelType::Error
];
if(in_array($input, $levels))
return true;
return false;
case LevelType::Warning:
$levels = [
LevelType::Warning,
LevelType::Fatal,
LevelType::Error
];
if(in_array($input, $levels))
return true;
return false;
case LevelType::Error:
$levels = [
LevelType::Fatal,
LevelType::Error
];
if(in_array($input, $levels))
return true;
return false;
case LevelType::Fatal:
if($input == LevelType::Fatal)
return true;
return false;
default:
case LevelType::Silent:
return false;
}
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace LogLib\Interfaces;
use LogLib\Objects\Event;
interface HandlerInterface
{
public function handle(Event $event): void;
}

View file

@ -0,0 +1,89 @@
<?php
/** @noinspection PhpMissingFieldTypeInspection */
namespace LogLib\Objects;
class Backtrace
{
/**
* The function name of the backtrace
*
* @var string|null
*/
public $Function;
/**
* The line number of the backtrace
*
* @var int|null
*/
public $Line;
/**
* The file name of the backtrace
*
* @var string|null
*/
public $File;
/**
* The class name, if any, of the backtrace
*
* @var string|null
*/
public $Class;
/**
* The current call type. If a method call, "->" is returned.
* If a static method call, "::" is returned. If a function call,
* nothing is returned.
*
* @see CallType
* @var string|null
*/
public $Type;
/**
* If inside a function, this lists the functions arguments. If inside
* an included file, this lists the included file name(s).
*
* @var array|null
*/
public $Args;
/**
* Returns an array representation of the backtrace
*
* @return array
*/
public function toArray(): array
{
return [
'function' => $this->Function,
'line' => $this->Line,
'file' => $this->File,
'class' => $this->Class,
'type' => $this->Type,
'args' => $this->Args
];
}
/**
* Constructs a new DebugBacktrace object from an array representation
*
* @param array $array
* @return Backtrace
*/
public static function fromArray(array $array): Backtrace
{
$backtrace = new Backtrace();
$backtrace->Function = ($array['function'] ?? null);
$backtrace->Line = ($array['line'] ?? null);
$backtrace->File = ($array['file'] ?? null);
$backtrace->Class = ($array['class'] ?? null);
$backtrace->Type = ($array['type'] ?? null);
$backtrace->Args = ($array['args'] ?? null);
return $backtrace;
}
}

View file

@ -0,0 +1,106 @@
<?php
/** @noinspection PhpMissingFieldTypeInspection */
namespace LogLib\Objects;
use LogLib\Abstracts\LevelType;
use LogLib\Classes\Utilities;
use Throwable;
class Event
{
/**
* The level of the event
*
* @see LevelType
* @var string
*/
public $Level;
/**
* The Unix Timestamp of when the event was created
*
* @var string
*/
private $Timestamp;
/**
* An array of backtraces, if any, that were created when the event was created
*
* @var Backtrace[]|null
*/
public $Backtrace;
/**
* The exception that was thrown, if any
*
* @var array|null
*/
public $Exception;
/**
* The message of the event
*
* @var string
*/
public $Message;
public function __construct()
{
$this->Timestamp = date('Y-m-dTH:i:s.v') . (date('p') == 'Z' ? 'Z' : 'L');
}
/**
* Sets an exception to the event
*
* @param Throwable $e
* @return void
*/
public function setException(Throwable $e): void
{
$this->Exception = Utilities::exceptionToArray($e);
}
/**
* Returns an array representation of the event
*
* @return array
*/
public function toArray(): array
{
return [
'level' => ($this->Level ?? null),
'timestamp' => ($this->Timestamp ?? null),
'backtrace' => $this->Backtrace,
'exception' => $this->Exception,
'message' => ($this->Message ?? null)
];
}
/**
* Constructs a new event from an array representation
*
* @param array $data
* @return Event
*/
public static function fromArray(array $data): Event
{
$event = new Event();
$event->Level = ($data['level'] ?? null);
$event->Timestamp = ($data['timestamp'] ?? null);
$event->Backtrace = ($data['backtrace'] ?? null);
$event->Exception = ($data['exception'] ?? null);
$event->Message = ($data['message'] ?? null);
return $event;
}
/**
* @return string
*/
public function getTimestamp(): string
{
return $this->Timestamp;
}
}

View file

@ -0,0 +1,252 @@
<?php
/** @noinspection PhpMissingFieldTypeInspection */
namespace LogLib\Objects;
use InvalidArgumentException;
use LogLib\Abstracts\LevelType;
use LogLib\Classes\Validate;
use LogLib\Interfaces\HandlerInterface;
class Options
{
/**
* The name of the application
*
* @var string
*/
private $ApplicationName;
/**
* The name of the NCC package that is using LogLib (eg; com.example.package)
*
* @var string|null
*/
private $PackageName;
/**
* The current output level of the logger, anything below this level will not be logged
*
* @see LevelType
* @var string
*/
private $OutputLevel;
/**
* Indicates whether the log should be written to the console or not.
*
* @var bool
*/
private $ConsoleOutput;
/**
* Indicates whether ansi colors should be used in the console output.
*
* @var bool
*/
private $ConsoleAnsiColors;
/**
* Writes the log to a file located at the package data path provided by NCC's API
* under a "logs" directory.
*
* @var bool
*/
private $WriteToPackageData;
/**
* Indicates whether the log should be split into different files based on the file size.
* Only applies if WriteToPackageData is true.
*
* @var bool
*/
private $SplitFiles;
/**
* The maximum size of a log file before it is split into a new file.
* Only applies if WriteToPackageData is true.
*
* @var int
*/
private $MaxFileSize;
/**
* An array of handlers that wil be used to handle the log events
* if applications want to handle the log events themselves.
*
* @var HandlerInterface[]
*/
private $Handlers;
/**
* Options constructor.
*/
public function __construct(string $application_name)
{
$this->ApplicationName = $application_name;
$this->WriteToPackageData = true;
$this->SplitFiles = true;
$this->MaxFileSize = 1073741824; // 1GB
$this->OutputLevel = LevelType::Info;
$this->ConsoleOutput = true;
$this->ConsoleAnsiColors = true;
$this->Handlers = [];
}
/**
* @return string|null
*/
public function getPackageName(): ?string
{
return $this->PackageName;
}
/**
* @param string|null $PackageName
*/
public function setPackageName(?string $PackageName): void
{
$this->PackageName = $PackageName;
}
/**
* @return string
*/
public function getOutputLevel(): string
{
return $this->OutputLevel;
}
/**
* @param string $OutputLevel
*/
public function setOutputLevel(string $OutputLevel): void
{
if(!in_array($OutputLevel, LevelType::All))
throw new InvalidArgumentException("Invalid output level provided");
$this->OutputLevel = $OutputLevel;
}
/**
* @return bool
*/
public function isConsoleOutput(): bool
{
return $this->ConsoleOutput;
}
/**
* @param bool $ConsoleOutput
*/
public function setConsoleOutput(bool $ConsoleOutput): void
{
$this->ConsoleOutput = $ConsoleOutput;
}
/**
* @return bool
*/
public function isConsoleAnsiColors(): bool
{
return $this->ConsoleAnsiColors;
}
/**
* @param bool $ConsoleAnsiColors
*/
public function setConsoleAnsiColors(bool $ConsoleAnsiColors): void
{
$this->ConsoleAnsiColors = $ConsoleAnsiColors;
}
/**
* @return bool
*/
public function isWriteToPackageData(): bool
{
return $this->WriteToPackageData;
}
/**
* @param bool $WriteToPackageData
*/
public function setWriteToPackageData(bool $WriteToPackageData): void
{
$this->WriteToPackageData = $WriteToPackageData;
}
/**
* @return bool
*/
public function isSplitFiles(): bool
{
return $this->SplitFiles;
}
/**
* @param bool $SplitFiles
*/
public function setSplitFiles(bool $SplitFiles): void
{
$this->SplitFiles = $SplitFiles;
}
/**
* @return int
*/
public function getMaxFileSize(): int
{
return $this->MaxFileSize;
}
/**
* @param int $MaxFileSize
*/
public function setMaxFileSize(int $MaxFileSize): void
{
if($MaxFileSize < 1)
throw new InvalidArgumentException("Max file size must be greater than 0");
$this->MaxFileSize = $MaxFileSize;
}
/**
* @return HandlerInterface[]
*/
public function getHandlers(): array
{
return $this->Handlers;
}
/**
* @param string $level
* @param HandlerInterface $handler
*/
public function setHandler(string $level, HandlerInterface $handler): void
{
if(!Validate::LevelType($level))
throw new InvalidArgumentException("Invalid level provided");
if(!isset($this->Handlers[$level]))
$this->Handlers[$level] = [];
$this->Handlers[$level][] = $handler;
}
/**
* @return void
*/
public function clearHandlers(): void
{
$this->Handlers = [];
}
/**
* @return string
*/
public function getApplicationName(): string
{
return $this->ApplicationName;
}
}