Skip to content

Commit

Permalink
Add Logger class (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
VerifiedJoseph authored Apr 29, 2024
1 parent 51db7be commit b696629
Show file tree
Hide file tree
Showing 17 changed files with 345 additions and 118 deletions.
13 changes: 8 additions & 5 deletions daemon.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Vigilant\Fetch;
use Vigilant\Notify;
use Vigilant\Output;
use Vigilant\Logger;
use Vigilant\Version;
use Vigilant\Exception\ConfigException;
use Vigilant\Exception\AppException;
Expand All @@ -19,23 +20,25 @@
$config->validate();

$fetch = new Fetch();
$feeds = new Feeds($config);
$logger = new Logger($config->getTimezone());
$feeds = new Feeds($config, $logger);

/** @phpstan-ignore-next-line */
while (true) {
foreach ($feeds->get() as $details) {
$notify = new Notify($details, $config);
$notify = new Notify($details, $config, $logger);
$check = new Check(
$details,
$fetch,
$config,
$fetch
$logger
);

if ($check->isDue() === true) {
$check->check();
$notify->send($check->getMessages());

Output::text(sprintf(
$logger->info(sprintf(
'Next check in %s seconds at %s',
$details->getInterval(),
$check->getNextCheckDate()
Expand All @@ -46,6 +49,6 @@
sleep(30);
}
} catch (ConfigException | AppException $err) {
Output::text($err->getMessage());
Output::text('[Vigilant] ' . $err->getMessage());
exit(1);
}
42 changes: 27 additions & 15 deletions src/Check.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@

final class Check
{
/** @var Config */
private Config $config;
/** @var Feed\Details $details Feed details (name, url, interval and hash) */
private Feed\Details $details;

/** @var Fetch */
/** @var Fetch Fetch class instance */
private Fetch $fetch;

/** @var Feed\Details $details Feed details (name, url, interval and hash) */
private Feed\Details $details;
/** @var Config Config class instance */
private Config $config;

/** @var Logger Logger class instance */
private Logger $logger;

/** @var Cache $cache Cache class instance */
private Cache $cache;
Expand All @@ -29,14 +32,16 @@ final class Check

/**
* @param Feed\Details $details Feed details
* @param Config $config Script config
* @param Config $config Config class instance
* @param Fetch $fetch Fetch class instance
* @param Logger $logger Logger class instance
*/
public function __construct(Feed\Details $details, Config $config, Fetch $fetch)
public function __construct(Feed\Details $details, Fetch $fetch, Config $config, Logger $logger)
{
$this->details = $details;
$this->config = $config;
$this->fetch = $fetch;
$this->config = $config;
$this->logger = $logger;

$this->cache = new Cache(
$this->config->getCachePath(),
Expand Down Expand Up @@ -78,14 +83,18 @@ public function getNextCheckDate(): string
public function check(): void
{
try {
Output::text('Checking...' . $this->details->getName() . ' (' . $this->details->getUrl() . ')');
$this->logger->info(sprintf(
'Checking...%s (%s)',
$this->details->getName(),
$this->details->getUrl()
));

$result = $this->fetch->get($this->details->getUrl());

$this->process($result);
$this->cache->resetErrorCount();
} catch (FetchException $err) {
Output::text($err->getMessage());
$this->logger->error($err->getMessage());

$this->cache->increaseErrorCount();

Expand Down Expand Up @@ -129,24 +138,27 @@ private function process(\FeedIo\Reader\Result $result): void
if (in_array($hash, $this->cache->getItems()) === false) {
$newItems += 1;

Output::text('Found...' . html_entity_decode($item->getTitle()) . ' (' . $hash . ')');
$title = html_entity_decode($item->getTitle());
$body = strip_tags(html_entity_decode($item->getContent()));

$this->logger->info(sprintf('Found...%s (%s)', $title, $hash));

if ($this->cache->isFirstCheck() === false) {
$this->messages[] = new Message(
title: html_entity_decode($item->getTitle()),
body: strip_tags(html_entity_decode($item->getContent())),
title: $title,
body: $body,
url: $item->getLink()
);
}
}
}

Output::text('Found ' . $newItems . ' new item(s).');
$this->logger->info(sprintf('Found %s new item(s).', $newItems));

$this->cache->updateItems($itemHashes);

if ($newItems > 0 && $this->cache->isFirstCheck() === true) {
Output::text('First feed check, not sending notifications for found items.');
$this->logger->info('First feed check, not sending notifications for found items.');
}
}
}
18 changes: 11 additions & 7 deletions src/Feeds.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Vigilant;

use Vigilant\Check;
use Vigilant\Feed\Feed;
use Vigilant\Feed\Details;
use Vigilant\Exception\AppException;
Expand All @@ -17,19 +16,24 @@ final class Feeds
*/
private Config $config;

/**
* @var Logger
*/
private Logger $logger;

/**
* @var array<int, Details> $feeds Feed classes for each feeds.yaml entry
*/
private array $feeds = [];

/**
* Constructor
*
* @param Config $config Feeds filepath
* @param Config $config Config class instance
* @param Logger $logger Logger class instance
*/
public function __construct(Config $config)
public function __construct(Config $config, Logger $logger)
{
$this->config = $config;
$this->logger = $logger;

try {
$feeds = $this->load($this->config->getFeedsPath());
Expand Down Expand Up @@ -60,7 +64,7 @@ public function get(): array
private function load(string $path): array
{
try {
Output::text('Loading feeds.yaml (' . $path . ')');
$this->logger->debug(sprintf('Loading feeds.yaml (%s)', $path));

return Yaml::parseFile($path);
} catch (ParseException $err) {
Expand All @@ -76,7 +80,7 @@ private function load(string $path): array
*/
private function validate(array $feeds): void
{
Output::text('Validating feeds.yaml');
$this->logger->debug('Validating feeds.yaml');

if (array_key_exists('feeds', $feeds) === false || is_array($feeds['feeds']) === false) {
throw new FeedsException('No feeds in feeds.yaml');
Expand Down
99 changes: 99 additions & 0 deletions src/Logger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

namespace Vigilant;

use DateTime;
use DateTimeZone;

class Logger
{
private DateTimeZone $timezone;

/**
* Logging level
*
* - `1` - Normal
* - `2` - Verbose
*
* @var int
*/
public int $logLevel = 1;

/**
* @param string $timezone Timezone
* @param int $level Logging level (`1` - Normal, `2` - Verbose)
*/
public function __construct(string $timezone, int $level = 1)
{
$this->setLevel($level);
$this->timezone = new DateTimeZone($timezone);
}

/**
* Display text in terminal
*
* @param string $text Text string to display
*/
public function info(string $text): void
{
$this->log($text);
}

/**
* Display error text in terminal
*
* @param string $text Text string to display
*/
public function error(string $text): void
{
$this->log($text);
}

/**
* Display text in terminal when debugging is enabled
*
* @param string $text Text string to display
*/
public function debug(string $text): void
{
if ($this->logLevel === 2) {
$this->log($text);
}
}

/**
* Display text in terminal
*
* @param string $text Text string to display
*/
private function log(string $text): void
{
$date = new DateTime('now', $this->timezone);

echo sprintf(
'[%s] %s %s',
$date->format('Y-m-d h:i:s P'),
$text,
PHP_EOL
);
}

/**
* Set logging level
*
* - `1` - Normal
* - `2` - Verbose
*
* @param int $level Logging level
*/
private function setLevel(int $level): void
{
if ($level < 1) {
$this->logLevel = 1;
} elseif ($level > 2) {
$this->logLevel = 2;
} else {
$this->logLevel = $level;
}
}
}
14 changes: 10 additions & 4 deletions src/Notification/AbstractNotification.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@

namespace Vigilant\Notification;

use Vigilant\Logger;

abstract class AbstractNotification
{
/**
* @var array<string, mixed> $config Notification config
*/
/** @var array<string, mixed> $config Notification config */
protected array $config = [];

/** @var Logger Logger class instance */
protected Logger $logger;

/**
* @param array<string, mixed> $config Notification config
* @param Logger $logger Logger class instance
*/
public function __construct(array $config)
public function __construct(array $config, Logger $logger)
{
$this->config = $config;
$this->logger = $logger;

$this->setup();
}

Expand Down
3 changes: 1 addition & 2 deletions src/Notification/Gotify.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Vigilant\Notification;

use Vigilant\Output;
use Vigilant\Notification\AbstractNotification;
use Vigilant\Exception\NotificationException;
use Gotify\Server;
Expand Down Expand Up @@ -35,7 +34,7 @@ public function send(string $title, string $body, string $url = ''): void
]
);

Output::text('Sent notification using Gotify');
$this->logger->info('Sent notification using Gotify');
} catch (EndpointException | GotifyException $err) {
throw new NotificationException('[Gotify] ' . $err->getMessage());
}
Expand Down
2 changes: 1 addition & 1 deletion src/Notification/Ntfy.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function send(string $title, string $body, string $url = ''): void

$this->client->send($message);

Output::text('Sent notification using Ntfy');
$this->logger->info('Sent notification using Ntfy');
} catch (EndpointException | NtfyException $err) {
throw new NotificationException('[Ntfy] ' . $err->getMessage());
}
Expand Down
Loading

0 comments on commit b696629

Please sign in to comment.