Skip to content

Commit

Permalink
feat: custom loggin
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefanie Gevaert committed Apr 14, 2023
1 parent de690fd commit 4881c32
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 67 deletions.
2 changes: 1 addition & 1 deletion docs/src/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ module.exports = {
'',
'configuration',
'collections',
'sync-and-flush',
'documents',
]
}
],
Expand Down
14 changes: 1 addition & 13 deletions docs/src/config/README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,3 @@
---
sidebar: auto
---

# Config

## foo

- Type: `string`
- Default: `/`

## bar

- Type: `string`
- Default: `/`
---
4 changes: 2 additions & 2 deletions docs/src/plugin/collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description: Create collections inside of Craft CMS
Collections are created within the Craft CMS through a config file. Copy over `src/config.php` and edit to get started with your collections.

## Config.php
Return an array with a keyed value `collections`. This key contains an array of all the collections you want to add.
Return an array with a keyed value `collections`. This key contains an array of all the collections you want to add. You can find all the supported [Typesense Field Types here](https://typesense.org/docs/0.23.0/api/collections.html#field-types)

Per array item, you will create a `new TypesenseCollectionIndex`. Here's a basic example on how to achieve this
```
Expand Down Expand Up @@ -100,7 +100,7 @@ function _getCategory($category)
```-->

### Element type
Define which element from Craft CMS is used to provide the data.
Define which element from Craft CMS is used to provide the data. You can look up the [documentation](https://typesense.org/docs/0.24.0/api/collections.html#field-types) to map out the data

### Criteria
Define the query to fetch the data from within the Database. You can look at the Craft CMS documentation on how to [fetch data from within PHP](https://Craft CMS.com/docs/4.x/element-queries.html#executing-element-queries). You don't have to define the `->all()`, this is being handled within the plugin.
14 changes: 13 additions & 1 deletion docs/src/plugin/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ description: Description of how to connect your Typesense server / cluster to Cr
There are two ways of setting up a connection from Craft CMS to Typesense. You can setup a managed cloud service in [Typsense Cloud](https://cloud.typesense.org/) or use a local machine / self hosting approach. To read more about these setups, please go to the [Typsense Guide](https://typesense.org/docs/guide/).

## Settings
If you go to the plugin settings, you'll find the different Typesense Server Type settings. You can either connect to a single server (look below on how to use inside of a Docker container) or a cluster.
If you go to the plugin settings, you'll find the different Typesense Server Type settings. You can either connect to a single server, this can either be a self hosted server or a single cluster. If you want a cluster with multiple nodes, you can choose the cluster and add the different nodes ; seperated and the load balanced endpoint.

You can create a cluster on [Typesense Cloud](https://cloud.typesense.org) and generate the API keys.

The settings page supports environment variables, this makes it able to setup indexes for different environments.

## Setup a server in Docker
If you want to use a self hosted server and replicate the setup in Docker, you can follow the steps bellow to setup a Docker container.

### Dockerfile
```
Expand All @@ -34,4 +37,13 @@ FROM typesense/typesense:0.22.2
- "3604:8108"
volumes:
- typesense-data:/data
```

### Settings
![Screenshot](../resources/docker-typsense.png)
```
TYPESENSE_API_KEY=xxxxx
TYPESENSE_SEARCH_ONLY_API_KEY=xxxxx
TYPESENSE_HOST=typesense
TYPESENSE_PORT=8108
```
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
---
title: Sync and Flush documents
title: Documents
description: Synd and flush documents inside of Craft CMS
---
# Sync and Flush documents
# Documents
By default, if any change is being done on an element, it will sync up to Typesense. So any delete, edit or add action will be synced. If you want to sync of flush manually, you can either do it in the control panel or as a console command.

Sync will empty the existing document and add the new content. It will also add or delete any change on entries. The flush will empty out all the documents and schema and build it from fresh. This last one is recommended if you have changed the schema in your config.php file or as best practice is you deploy to another environment.
Expand Down
Binary file added docs/src/resources/docker-typsense.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 14 additions & 45 deletions src/Typesense.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,27 @@
use craft\console\Application as ConsoleApplication;
use craft\elements\Entry;
use craft\events\ElementEvent;
use craft\events\RebuildConfigEvent;
use craft\events\RegisterUrlRulesEvent;
use craft\events\RegisterUserPermissionsEvent;
use craft\helpers\ElementHelper;
use craft\helpers\UrlHelper;
use craft\services\Elements;
use craft\services\Plugins;
use craft\services\ProjectConfig;
use craft\services\UserPermissions;
use craft\web\twig\variables\CraftVariable;
use craft\web\UrlManager;

use percipiolondon\typesense\base\PluginTrait;
use percipiolondon\typesense\helpers\CollectionHelper;
use percipiolondon\typesense\helpers\FileLog;
use percipiolondon\typesense\helpers\ProjectConfigDataHelper;
use percipiolondon\typesense\models\Settings;
use percipiolondon\typesense\services\CollectionService;
use percipiolondon\typesense\services\TypesenseService;
use percipiolondon\typesense\variables\TypesenseVariable;


use Typesense\Exceptions\ObjectNotFound;
use Typesense\Exceptions\ServerError;
use yii\base\Event;
use yii\db\Expression;

Expand Down Expand Up @@ -126,25 +126,13 @@ public function init()
$this->_registerEventHandlers();
$this->_registerVariable();

// // Initialize properties
// self::$settings = self::$plugin->getSettings();
//
// $this->name = self::$settings->pluginName ?? 'Typesense';

// Add in our console commands
if (Craft::$app instanceof ConsoleApplication) {
$this->controllerNamespace = 'percipiolondon\typesense\console\controllers';
}


// Register our utilities
/*Event::on(
Utilities::class,
Utilities::EVENT_REGISTER_UTILITY_TYPES,
function (RegisterComponentTypesEvent $event) {
$event->types[] = TypesenseUtility::class;
}
); */
// Create endpoint for custom logs
FileLog::create('typesense', 'percipiolondon\craft-typesense\*');

Craft::info(
Craft::t(
Expand Down Expand Up @@ -350,38 +338,13 @@ private function _registerProjectConfigEventListeners()
*/
private function _registerEventHandlers(): void
{
/* PENDING EVENT */
// Event::on(
// Plugins::class,
// Plugins::EVENT_AFTER_LOAD_PLUGINS,
// function() {
// $request = Craft::$app->getRequest();
// if (!$request->getIsConsoleRequest()) {
// // set timestamps to fetch todays entries
// $morning = mktime(0,0,0, date('m'), date('d'), date('y'));
// $evening = mktime(23,59,00, date('m'), date('d'), date('y'));
//
// // select entries of today's postDate where the dateUpdated is before the postDate gets out
// $todaysEntries = Entry::find()
// ->where(['between', 'postDate', date('Y/m/d H:i', $morning), date('Y/m/d H:i', $evening)])
// ->andWhere('`elements`.`dateUpdated` < `entries`.`postDate`')
// ->all();
//
// // resave those entries to setup the document in typsense
// foreach($todaysEntries as $entry) {
// Craft::$app->getElements()->saveElement($entry);
// }
// }
// }
// );

/* SAVE EVENTS */
$events = [
[Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT],
[Elements::class, Elements::EVENT_AFTER_RESTORE_ELEMENT],
[Elements::class, Elements::EVENT_AFTER_UPDATE_SLUG_AND_URI],
];

foreach ($events as $event) {
Event::on(
$event[0],
Expand Down Expand Up @@ -426,8 +389,14 @@ function(ElementEvent $event) {
if (($entry->enabled && $entry->getEnabledForSite()) && $entry->getStatus() === 'live') {
// element is enabled --> save to Typesense
if ($collection !== null) {
Craft::info('Typesense edit / add / delete document based of: ' . $entry->title);
self::$plugin->getClient()->client()->collections[$collection->indexName]->documents->upsert($collection->schema['resolver']($entry));
Craft::info('Typesense edit / add / delete document based of: ' . $entry->title, __METHOD__);

try {
self::$plugin->getClient()->client()->collections[$collection->indexName]->documents->upsert($collection->schema['resolver']($entry));
} catch(ObjectNotFound | ServerError $e) {
Craft::$app->session->setFlash('error', Craft::t('typesense', 'There was an issue saving your action, check the logs for more info'));
Craft::error($e->getMessage(), __METHOD__);
}
}
} else {
// element is disabled --> delete from Typesense
Expand Down
2 changes: 1 addition & 1 deletion src/console/controllers/DefaultController.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public function actionUpdateScheduledPosts()
$count += 1;
}

Craft::info('Typesense update scheduled post fired with ' . $count . ' result(s)');
Craft::info('Typesense update scheduled post fired with ' . $count . ' result(s)', __METHOD__);
$this->stdout("End fetching entries with today's post date with " . $count . ' result(s)');
$this->stdout(PHP_EOL);
}
Expand Down
42 changes: 42 additions & 0 deletions src/helpers/FileLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace percipiolondon\typesense\helpers;

use Craft;
use craft\log\MonologTarget;
use Monolog\Formatter\LineFormatter;
use Psr\Log\LogLevel;

class FileLog
{
// Public Static Methods
// =========================================================================

/**
* Create an additional file log target named $filename.log that logs messages
* in the category $category
*
* @param string $fileName
* @param string $category
* @return void
*/
public static function create(string $fileName, string $category): void
{
// Create a new file target
$fileTarget = new MonologTarget([
'name' => $fileName,
'categories' => [$category],
'level' => LogLevel::INFO,
'logContext' => false,
'allowLineBreaks' => true,
'formatter' => new LineFormatter(
format: "%datetime% [%channel%.%level_name%] [%extra.yii_category%] %message% %context% %extra%\n",
dateFormat: 'Y-m-d H:i:s',
allowInlineLineBreaks: true,
ignoreEmptyContextAndExtra: true,
),
]);
// Add the new target file target to the dispatcher
Craft::getLogger()->dispatcher->targets[] = $fileTarget;
}
}
4 changes: 2 additions & 2 deletions src/services/TypesenseService.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ public function client(): ?TypesenseClient
Craft::$app->getSession()->setNotice(Craft::t('typesense', 'Please provide your typesense API key in the settings to get started'));
}

Craft::error(Craft::t('typesense', 'Please provide your typesense API key in the settings to get started'));
Craft::error(Craft::t('typesense', 'Please provide your typesense API key in the settings to get started'), 'typesense');
}
} catch (\Exception $exception) {
if (Craft::$app->getRequest()->getIsConsoleRequest()) {
Craft::$app->getSession()->setNotice(Craft::t('typesense', 'There was an error with the Typesense Client Connection, check the logs'));
}

Craft::error($exception->getMessage(), __METHOD__);
Craft::error($exception->getMessage(), 'typesense');
}

return $client;
Expand Down

0 comments on commit 4881c32

Please sign in to comment.