Skip to content

Commit

Permalink
Added Logger area and compatibility with Kirby4
Browse files Browse the repository at this point in the history
  • Loading branch information
michnhokn committed Mar 24, 2024
1 parent a2bbe80 commit 47e19d7
Show file tree
Hide file tree
Showing 31 changed files with 682 additions and 2,686 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true

[*.php]
indent_size = 4
26 changes: 24 additions & 2 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1,24 @@
# Auto detect text files and perform LF normalization
* text=auto
# Git
.gitattributes export-ignore
.github/ export-ignore
.gitignore export-ignore

# Source files
scripts/ export-ignore
src/panel/ export-ignore

# Development files
.editorconfig export-ignore
.eslintrc.js export-ignore
composer.lock export-ignore
package.json export-ignore
pnpm-lock.yaml export-ignore

# Tests
.codecov.yml export-ignore
.composer-require-checker.json export-ignore
.php-cs-fixer.dist.php export-ignore
phpmd.xml.dist export-ignore
phpunit.xml.dist export-ignore
psalm.xml.dist export-ignore
tests/ export-ignore
Binary file added .github/kirby-logger.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2021 Michael Scheurich
Copyright (c) 2021 Michael Engel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
105 changes: 105 additions & 0 deletions Logger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

namespace Michnhokn;

use Kirby\Data\Json;
use Kirby\Database\Database;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Filesystem\F;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Date;
use Kirby\Toolkit\Str;

class Logger
{
public const LEVEL_DEBUG = 'DEBUG';

public const LEVEL_INFO = 'INFO';

public const LEVEL_WARNING = 'WARNING';

public const LEVEL_ERROR = 'ERROR';

public const LEVEL_CRITICAL = 'CRITICAL';

private const LEVELS = [
self::LEVEL_DEBUG,
self::LEVEL_INFO,
self::LEVEL_WARNING,
self::LEVEL_ERROR,
self::LEVEL_CRITICAL
];

public const CHANNEL_DEFAULT = 'default';

public const CHANNEL_AUDIT = 'audit';

private const CHANNELS = [
self::CHANNEL_DEFAULT,
self::CHANNEL_AUDIT,
];

private static ?Database $connection = null;

public static function connect(): Database
{
if (static::$connection !== null) {
return static::$connection;
}

static::$connection = new Database([
'type' => 'sqlite',
'database' => kirby()->root('logs') . "/logger.sqlite"
]);

if (!self::$connection->validateTable('logs')) {
self::$connection->execute(F::read(__DIR__ . '/logs-schema.sql'));
}

return self::$connection;
}

public static function write(
string $message,
string $level = self::LEVEL_INFO,
string $channel = self::CHANNEL_DEFAULT,
array $context = [],
array $extra = [],
): void {
if (!in_array($channel, self::getChannels())) {
throw new \Exception("Logger channel $channel is not configured!");
}
(self::connect())->table('monolog')->insert([
'channel' => $channel,
'level' => $level,
'message' => $message,
'context' => Json::encode($context),
'extra' => Json::encode($extra),
'created_at' => Date::now()->format("Y-m-d\TH:i:s.uO"),
]);
}


public static function __callStatic(string $method, array $arguments)
{
$level = Str::upper($method);
if (in_array($level, static::LEVELS)) {
$arguments['level'] = $level;
self::write(...$arguments);
return;
}

throw new InvalidArgumentException('Invalid static Db method: ' . $method);
}

public static function getLevels(): array
{
return self::LEVELS;
}

public static function getChannels(): array
{
$channelsFromConfig = option('michnhokn.logger.channels', []);
return A::merge(self::CHANNELS, $channelsFromConfig);
}
}
104 changes: 78 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,92 @@
# A Website logger for Kirby3
![Kirby Logger](./.github/kirby-logger.png)

![Release](https://flat.badgen.net/packagist/v/michnhokn/kirby3-logger?color=92a9c4)
![Last Commit](https://flat.badgen.net/github/last-commit/michnhokn/kirby3-logger?color=92c496)
# Kirby Logger

![Kirby Logger](https://user-images.githubusercontent.com/38752255/141615310-f35b7dde-c732-4d5e-81b7-506d5dfc55db.png)
Gain deeper insights into your Kirby website's behavior with the powerful Logger. The new Logger panel area provides a
clear view of what's happening behind the scenes, while the included Logger utility lets you easily log events within
your custom code. This combination empowers you to both understand your website's activity and streamline debugging for
a smoother development experience.

## Commercial Usage
## Key Features

This plugin is free but if you use it in a commercial project please consider to

- [buy me a 🍺](https://buymeacoff.ee/michnhokn)
* 🕵️ **Effortless Log Exploration:** The intuitive panel view makes exploring your website's logs a breeze. Quickly find
the information you need to understand what's happening.
* 💾 **Reliable Log Storage:** Enjoy peace of mind knowing your logs are saved securely and efficiently using SQLite, a
robust database technology.
* 🐞 **Comprehensive Logging:** Gain a complete picture of your website's behavior. The extension automatically captures
all Kirby after hooks and logs exceptions, providing valuable insights.
* ⚡️ **Customizable Event Logging:** Take control of your debugging process! The custom Logger utility empowers you to
effortlessly log specific events within your custom code, allowing you to pinpoint issues with greater speed and
accuracy.

## Installation

- unzip [main.zip](https://github.com/michnhokn/kirby3-logger/archive/main.zip) as
folder `site/plugins/kirby3-logger` or
- `git submodule add https://github.com/michnhokn/kirby3-logger.git site/plugins/kirby3-logger` or
- `composer require michnhokn/kirby3-logger`
### Composer

```
composer require michnhokn/kirby-logger
```

### Download

Download and copy this repository to `/site/plugins/kirby-logger`

## Usage

Bolster your website's security with the comprehensive Audit Logs feature. This new panel section offers a centralized
view of all activity, complete with timestamps for context. Leverage granular filtering by channel and log level, or
utilize the powerful search bar to pinpoint specific events with ease. Gain actionable insights and stay on top of
everything happening within your website.

### Configuration

```php
<?php
// site/config/config.php

return [
'michnhokn.logger' => [
// optional - add your custom channels for better filtering in the panel
'channels' => ['custom', 'my-plugin-a'],

// optional - add specific hooks to an ignore list to prevent spamming in the panel
'ignoreHooks' => [
'page.render:after',
'kirbytags:after'
]
]
];
```

### Logger Utility

The `Michnhokn\Logger` class lets you easily add new log entries. Available levels
are `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`.

```php
// Write a custom log entry
\Michnhokn\Logger::write(
message: 'Whoops! Something bad happened.',
level: Logger::LEVEL_ERROR,
context: ['userId' => App::instance()->user()?->id()]
);

## Features
⚠️ This plugin is under development. Please rethink using it in a commercial project.
* Log the following actions to a searchable and filterable table: `user`, `file`, `page`, `site`
* Seperate panel view
// you can also use all available levels as a method name
\Michnhokn\Logger::info('A user logged in.',context: ['userId' => App::instance()->user()?->id()]);
```

## Setup
Just install the plugin. At the moment there are no settings what soever.
## Upcoming features

## Upcomming features
* Permissions to view the logs
* More configuration for the panel view
* More details in the panel view
* More details in the panel view (e.g. event arguments)
* More configuration for the panel view (e.g. date filter, event context)
* Better translations for the panel

## Misc
## Support the project

**License**: `MIT`
> [!NOTE]
> This plugin is provided free of charge & published under the permissive MIT License. If you use it in a commercial
> project, please consider to [buy me a beer 🍺](https://buymeacoff.ee/michnhokn)
**Credits**: [MichnHokn](https://github.com/michnhokn)
## License

**Inspiration**: [Kirby Logger](https://github.com/texnixe/kirby-logger) by @texnixe | [Logger for Kirby 3](https://github.com/medienbaecker/kirby-logger) by @medienbaecker
[MIT](./LICENSE.md) License © 2021-PRESENT [Michael Engel](https://github.com/michnhokn)
Loading

0 comments on commit 47e19d7

Please sign in to comment.