From 33cd2628ba61847cda90953fd5446da132ae5282 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Wed, 18 Nov 2026 10:44:51 +0700 Subject: [PATCH 1/9] [SLS] initial import --- .github/workflows/docs.yml | 79 ++++++++ .gitignore | 7 + Branding/Logo.svg | 11 ++ Docs/index.md | 22 +++ Docs/toc.yml | 7 + LICENSE.md | 133 +++++++++++++ NOTICE | 12 ++ README.md | 29 +++ Stellar.LoggingSystem.stellar.module | 8 + Template/public/main.css | 67 +++++++ docfx.json | 40 ++++ global.json | 5 + .../Stellar.LoggingSystem/LoggerFormats.cs | 185 ++++++++++++++++++ .../LoggingSystemModule.cs | 12 ++ .../Stellar.LoggingSystem.csproj | 7 + .../LoggingSystemModuleTests.cs | 8 + .../Stellar.LoggingSystem.Tests.csproj | 9 + 17 files changed, 641 insertions(+) create mode 100644 .github/workflows/docs.yml create mode 100644 .gitignore create mode 100644 Branding/Logo.svg create mode 100644 Docs/index.md create mode 100644 Docs/toc.yml create mode 100644 LICENSE.md create mode 100644 NOTICE create mode 100644 README.md create mode 100644 Stellar.LoggingSystem.stellar.module create mode 100644 Template/public/main.css create mode 100644 docfx.json create mode 100644 global.json create mode 100644 src/Managed/Stellar.LoggingSystem/LoggerFormats.cs create mode 100644 src/Managed/Stellar.LoggingSystem/LoggingSystemModule.cs create mode 100644 src/Managed/Stellar.LoggingSystem/Stellar.LoggingSystem.csproj create mode 100644 tests/Stellar.LoggingSystem.Tests/LoggingSystemModuleTests.cs create mode 100644 tests/Stellar.LoggingSystem.Tests/Stellar.LoggingSystem.Tests.csproj diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..ae87db5 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,79 @@ +name: Docs + +# Builds the documentation site of the module from Docs/ with DocFX (docfx.json) and publishes it to GitHub Pages. +# Pull requests and manual runs on other branches only build; the site is deployed from master only. +# Repository setting required once: Settings -> Pages -> Source = "GitHub Actions". + +on: + push: + branches: [master] + paths: + - 'Docs/**' + - 'README.md' + - 'docfx.json' + - '.github/workflows/docs.yml' + pull_request: + paths: + - 'Docs/**' + - 'README.md' + - 'docfx.json' + - '.github/workflows/docs.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: docs-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + DOCFX_VERSION: '2.81.0' + DOTNET_NOLOGO: 'true' + DOTNET_CLI_TELEMETRY_OPTOUT: 'true' + +jobs: + build: + name: Build site + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v5 + + # The global.json of a module pins Stellar.Sdk, not the .NET SDK + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: '9.0.x' + + - name: Install DocFX + working-directory: ${{ runner.temp }} + run: dotnet tool install docfx --version "$DOCFX_VERSION" --tool-path "$RUNNER_TEMP/docfx" + + - name: Build documentation + run: '"$RUNNER_TEMP/docfx/docfx" build docfx.json --warningsAsErrors' + + - name: Upload Pages artifact + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master' + uses: actions/upload-pages-artifact@v5 + with: + path: artifacts/docs/site + + deploy: + name: Deploy to GitHub Pages + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master' + needs: build + runs-on: ubuntu-latest + concurrency: + group: pages + cancel-in-progress: false + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy + id: deployment + uses: actions/deploy-pages@v5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3da75a5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +[Bb]in/ +[Oo]bj/ +.vs/ +.idea/ +*.user +# The documentation site, built by docfx +artifacts/ diff --git a/Branding/Logo.svg b/Branding/Logo.svg new file mode 100644 index 0000000..7fe7aa7 --- /dev/null +++ b/Branding/Logo.svg @@ -0,0 +1,11 @@ + + + + + + + diff --git a/Docs/index.md b/Docs/index.md new file mode 100644 index 0000000..c6aa78c --- /dev/null +++ b/Docs/index.md @@ -0,0 +1,22 @@ +# Stellar.LoggingSystem + +logging system of the engine + +A `CoreModule` module of [StellarEngine](https://quantumdevteam.github.io/StellarEngine-Mono/). Its site is https://quantumdevteam.github.io/Stellar.LoggingSystem/, built from the Markdown +files of `Docs/` with DocFX; the whole engine, with every module, is on the [site of the engine](https://quantumdevteam.github.io/StellarEngine-Mono/). + +## Using it + +Add `Stellar.LoggingSystem` to `Dependencies` of your module or project descriptor, then: + +```powershell +stellar modules sync +``` + +## Working on it + +```powershell +stellar modules build Stellar.LoggingSystem --tests +``` + +See [the README](../README.md) for the layout of the module. diff --git a/Docs/toc.yml b/Docs/toc.yml new file mode 100644 index 0000000..89c53bd --- /dev/null +++ b/Docs/toc.yml @@ -0,0 +1,7 @@ +# Navigation of the documentation site of the module (DocFX). Paths are relative to this file. +- name: Home + href: index.md +- name: README + href: ../README.md +- name: StellarEngine + href: https://quantumdevteam.github.io/StellarEngine-Mono/ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..d8dbac9 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,133 @@ +# PolyForm Noncommercial License 1.0.0 + + + +Required Notice: Copyright (c) 2026 QuantumDevTeam (see NOTICE) + +## Acceptance + +In order to get any license under these terms, you must agree +to them as both strict obligations and conditions to all +your licenses. + +## Copyright License + +The licensor grants you a copyright license for the +software to do everything you might do with the software +that would otherwise infringe the licensor's copyright +in it for any permitted purpose. However, you may +only distribute the software according to [Distribution +License](#distribution-license) and make changes or new works +based on the software according to [Changes and New Works +License](#changes-and-new-works-license). + +## Distribution License + +The licensor grants you an additional copyright license +to distribute copies of the software. Your license +to distribute covers distributing the software with +changes and new works permitted by [Changes and New Works +License](#changes-and-new-works-license). + +## Notices + +You must ensure that anyone who gets a copy of any part of +the software from you also gets a copy of these terms or the +URL for them above, as well as copies of any plain-text lines +beginning with `Required Notice:` that the licensor provided +with the software. For example: + +> Required Notice: Copyright Yoyodyne, Inc. (http://example.com) + +## Changes and New Works License + +The licensor grants you an additional copyright license to +make changes and new works based on the software for any +permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that +covers patent claims the licensor can license, or becomes able +to license, that you would infringe by using the software. + +## Noncommercial Purposes + +Any noncommercial purpose is a permitted purpose. + +## Personal Uses + +Personal use for research, experiment, and testing for +the benefit of public knowledge, personal study, private +entertainment, hobby projects, amateur pursuits, or religious +observance, without any anticipated commercial application, +is use for a permitted purpose. + +## Noncommercial Organizations + +Use by any charitable organization, educational institution, +public research organization, public safety or health +organization, environmental protection organization, +or government institution is use for a permitted purpose +regardless of the source of funding or obligations resulting +from the funding. + +## Fair Use + +You may have "fair use" rights for the software under the +law. These terms do not limit them. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of +your licenses to anyone else, or prevent the licensor from +granting licenses to anyone else. These terms do not imply +any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or +contributes to infringement of any patent, your patent license +for the software granted under these terms ends immediately. If +your company makes such a claim, your patent license ends +immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have +violated any of these terms, or done anything with the software +not covered by your licenses, your licenses can nonetheless +continue if you come into full compliance with these terms, +and take practical steps to correct past violations, within +32 days of receiving notice. Otherwise, all your licenses +end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without +any warranty or condition, and the licensor will not be liable +to you for any damages arising out of these terms or the use +or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these +terms, and the **software** is the software the licensor makes +available under these terms. + +**You** refers to the individual or entity agreeing to these +terms. + +**Your company** is any legal entity, sole proprietorship, +or other kind of organization that you work for, plus all +organizations that have control over, are under the control of, +or are under common control with that organization. **Control** +means ownership of substantially all the assets of an entity, +or the power to direct its management and policies by vote, +contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the +software under these terms. + +**Use** means anything you do with the software requiring one +of your licenses. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..644897c --- /dev/null +++ b/NOTICE @@ -0,0 +1,12 @@ +StellarEngine +Copyright (c) 2026 QuantumDevTeam + +QuantumDevTeam is the name under which Timur Shestakov acts personally. It is a brand and a +trade name, not a legal entity: the copyright in StellarEngine, and in every module and tool +published under this name, belongs to Timur Shestakov, who is the licensor of the license +below and the "Project Owner" of CLA.md. If a legal entity is established later, the rights +may be assigned to it as CLA.md describes, and this notice will name it. + +Licensed under the PolyForm Noncommercial License 1.0.0 +https://polyformproject.org/licenses/noncommercial/1.0.0 +See LICENSE.md and CLA.md. diff --git a/README.md b/README.md new file mode 100644 index 0000000..24436b5 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# Stellar.LoggingSystem + +logging system of the engine + +| | | +|---|---| +| Level | `CoreModule` | +| Descriptor | `Stellar.LoggingSystem.stellar.module` | + +## Layout + +``` +Stellar.LoggingSystem/ +├── Stellar.LoggingSystem.stellar.module what the engine knows about the module +├── src/Managed/Stellar.LoggingSystem/ the C# project +├── src/Native/ native projects, if any: built first, their DLLs travel with the assembly +├── tests/ test projects +├── Branding/Logo.svg the icon of the module: a placeholder, replace it with your own +└── Docs/ the documentation site of the module (docfx.json, published by .github/workflows/docs.yml) +``` + +## Working on it + +```bash +stellar modules build Stellar.LoggingSystem --tests +``` + +A dependency on another module goes into `Dependencies` of the descriptor, then `stellar modules sync`: the +project gets the reference by itself. diff --git a/Stellar.LoggingSystem.stellar.module b/Stellar.LoggingSystem.stellar.module new file mode 100644 index 0000000..18d24a3 --- /dev/null +++ b/Stellar.LoggingSystem.stellar.module @@ -0,0 +1,8 @@ +{ + "$schema": "https://quantumdevteam.github.io/StellarEngine-Core/schemas/stellar.module.schema.json", + "Id": "Stellar.LoggingSystem", + "Version": "0.9.0", + "Level": "CoreModule", + "Description": "logging system of the engine", + "Dependencies": [] +} diff --git a/Template/public/main.css b/Template/public/main.css new file mode 100644 index 0000000..3e66746 --- /dev/null +++ b/Template/public/main.css @@ -0,0 +1,67 @@ +/* + The theme of the StellarEngine sites, over the "modern" template of DocFX: the sites of the core and of the + orchestra list this folder last in "template", the template of a module carries a copy. +*/ + +:root { + --stellar-accent: #8a63ff; + --stellar-accent-strong: #6d3df5; +} + +[data-bs-theme="dark"] { + --stellar-accent: #a98bff; + --stellar-accent-strong: #c4b0ff; +} + +/* The brand: the icon and the name side by side, a fixed size, room before the menu */ +.navbar-brand { + display: inline-flex; + align-items: center; + gap: 0.55rem; + margin-right: 1.75rem; + font-weight: 600; + letter-spacing: 0.01em; + white-space: nowrap; +} + +/* The icon is wide (Shared/Branding/stellar_icon.svg: the emblem without the name): fixed height, its own width */ +.navbar-brand #logo { + height: 34px; + width: auto; + max-width: 84px; + flex: none; + object-fit: contain; +} + +/* Entries of the menu stay on one line */ +.navbar-nav .nav-link { + white-space: nowrap; +} + +/* A thin line under the header instead of a block */ +header .navbar { + border-bottom: 1px solid var(--bs-border-color-translucent); +} + +/* Links and the active entry in the accent of the logo */ +article a, +.toc a.active, +.navbar-nav .nav-link.active { + color: var(--stellar-accent); +} + +article a:hover { + color: var(--stellar-accent-strong); +} + +/* Code blocks of one command (the installer) read better a little larger */ +article pre > code { + font-size: 0.92em; +} + +/* Wide tables of the docs scroll inside the page instead of pushing it */ +article table { + display: block; + max-width: 100%; + overflow-x: auto; +} diff --git a/docfx.json b/docfx.json new file mode 100644 index 0000000..7862755 --- /dev/null +++ b/docfx.json @@ -0,0 +1,40 @@ +{ + "$schema": "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json", + "build": { + "content": [ + { + "src": "Docs", + "files": [ + "**/*.md", + "toc.yml" + ] + }, + { + "files": [ + "README.md" + ] + } + ], + "resource": [ + { + "files": [ + "Branding/Logo.svg" + ] + } + ], + "output": "artifacts/docs/site", + "template": [ + "default", + "modern", + "Template" + ], + "globalMetadata": { + "_appName": "Stellar.LoggingSystem", + "_appTitle": "Stellar.LoggingSystem", + "_appFooter": "Stellar.LoggingSystem, a module of StellarEngine", + "_appLogoPath": "Branding/Logo.svg", + "_appFaviconPath": "Branding/Logo.svg", + "_enableSearch": true + } + } +} diff --git a/global.json b/global.json new file mode 100644 index 0000000..3ae5863 --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "msbuild-sdks": { + "Stellar.Sdk": "0.4.0" + } +} diff --git a/src/Managed/Stellar.LoggingSystem/LoggerFormats.cs b/src/Managed/Stellar.LoggingSystem/LoggerFormats.cs new file mode 100644 index 0000000..2260390 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/LoggerFormats.cs @@ -0,0 +1,185 @@ +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem; + +/// +/// TODO: summary +/// +public sealed class LoggerFormats +{ + /// + /// TODO: summary + /// + public LogFormat Info { get; init; } = new() + { + Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", + ColorizedFormat = "\e[32m{0}\e[0m" + + "\e[31m:\e[0m" + + "\e[2;32m{1}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[1;38m{2}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[36m{3}\e[0m" + + "\e[31m:\e[0m" + + "\e[36m{4}\e[0m " + + // "\e[31m:\e[0m" + + // "\e[36m{5}\e[0m " + + + "\e[31m-\e[0m " + + + "\e[1;38m{6}\e[0m" + }; + + /// + /// TODO: summary + /// + public LogFormat Debug { get; init; } = new() + { + Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", + ColorizedFormat = "\e[32m{0}\e[0m" + + "\e[31m:\e[0m" + + "\e[2;32m{1}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[1;33m{2}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[36m{3}\e[0m" + + "\e[31m:\e[0m" + + "\e[36m{4}\e[0m " + + // "\e[31m:\e[0m" + + // "\e[36m{5}\e[0m " + + + "\e[31m-\e[0m " + + + "\e[1;33m{6}\e[0m" + }; + + /// + /// TODO: summary + /// + public LogFormat Success { get; init; } = new() + { + Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", + ColorizedFormat = "\e[32m{0}\e[0m" + + "\e[31m:\e[0m" + + "\e[2;32m{1}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[1;32m{2}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[36m{3}\e[0m" + + "\e[31m:\e[0m" + + "\e[36m{4}\e[0m " + + // "\e[31m:\e[0m" + + // "\e[36m{5}\e[0m " + + + "\e[31m-\e[0m " + + + "\e[1;32m{6}\e[0m" + }; + + /// + /// TODO: summary + /// + public LogFormat Warning { get; init; } = new() + { + Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", + ColorizedFormat = "\e[32m{0}\e[0m" + + "\e[31m:\e[0m" + + "\e[2;32m{1}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[1;34m{2}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[36m{3}\e[0m" + + "\e[31m:\e[0m" + + "\e[36m{4}\e[0m " + + // "\e[31m:\e[0m" + + // "\e[36m{5}\e[0m " + + + "\e[31m-\e[0m " + + + "\e[1;34m{6}\e[0m" + }; + + /// + /// TODO: summary + /// + public LogFormat Error { get; init; } = new() + { + Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", + ColorizedFormat = "\e[32m{0}\e[0m" + + "\e[31m:\e[0m" + + "\e[2;32m{1}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[1;31m{2}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[36m{3}\e[0m" + + "\e[31m:\e[0m" + + "\e[36m{4}\e[0m" + + // "\e[31m:\e[0m" + + // "\e[36m{5}\e[0m " + + + "\e[31m-\e[0m " + + + "\e[1;38m{6}\e[0m" + }; + + /// + /// TODO: summary + /// + public LogFormat Exception { get; init; } = new() + { + Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", + ColorizedFormat = "\e[32m{0}\e[0m" + + "\e[31m:\e[0m" + + "\e[2;32m{1}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[1;31m{2}\e[0m " + + + "\e[31m|\e[0m " + + + "\e[36m{3}\e[0m" + + "\e[31m:\e[0m" + + "\e[36m{4}\e[0m " + + // "\e[31m:\e[0m" + + // "\e[36m{5}\e[0m " + + + "\e[31m-\e[0m " + + + "\e[1;31m{6}\e[0m" + }; + + /// + /// TODO: summary + /// + public LogFormat GetFormat(LogLevel level) => level switch + { + LogLevel.Info => Info, + LogLevel.Debug => Debug, + LogLevel.Success => Success, + LogLevel.Warning => Warning, + LogLevel.Error => Error, + LogLevel.Exception => Exception, + _ => throw new ArgumentOutOfRangeException(nameof(level), level, null) + }; +} diff --git a/src/Managed/Stellar.LoggingSystem/LoggingSystemModule.cs b/src/Managed/Stellar.LoggingSystem/LoggingSystemModule.cs new file mode 100644 index 0000000..feac735 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/LoggingSystemModule.cs @@ -0,0 +1,12 @@ +namespace Stellar.LoggingSystem; + +/// +/// The LoggingSystem module of StellarEngine. +/// +public static class LoggingSystemModule +{ + /// + /// The identifier of the module, as its descriptor names it. + /// + public const string Id = "Stellar.LoggingSystem"; +} diff --git a/src/Managed/Stellar.LoggingSystem/Stellar.LoggingSystem.csproj b/src/Managed/Stellar.LoggingSystem/Stellar.LoggingSystem.csproj new file mode 100644 index 0000000..349485b --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/Stellar.LoggingSystem.csproj @@ -0,0 +1,7 @@ + + + diff --git a/tests/Stellar.LoggingSystem.Tests/LoggingSystemModuleTests.cs b/tests/Stellar.LoggingSystem.Tests/LoggingSystemModuleTests.cs new file mode 100644 index 0000000..9d183ca --- /dev/null +++ b/tests/Stellar.LoggingSystem.Tests/LoggingSystemModuleTests.cs @@ -0,0 +1,8 @@ +namespace Stellar.LoggingSystem.Tests; + +public class LoggingSystemModuleTests +{ + [Fact] + public void TheAssemblyIsTheModule() => + typeof(LoggingSystemModule).Assembly.GetName().Name.Should().Be(LoggingSystemModule.Id); +} diff --git a/tests/Stellar.LoggingSystem.Tests/Stellar.LoggingSystem.Tests.csproj b/tests/Stellar.LoggingSystem.Tests/Stellar.LoggingSystem.Tests.csproj new file mode 100644 index 0000000..62aa0f5 --- /dev/null +++ b/tests/Stellar.LoggingSystem.Tests/Stellar.LoggingSystem.Tests.csproj @@ -0,0 +1,9 @@ + + + Tests + + + + + + From 6e99492bdb9ca0b30709e0b2336c87b0128388fd Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Wed, 18 Nov 2026 23:46:44 +0700 Subject: [PATCH 2/9] versioning --- global.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/global.json b/global.json index 3ae5863..f4183af 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "Stellar.Sdk": "0.4.0" + "Stellar.Sdk": "0.4.1" } } From b5b2972aee915b96cba47acd3e9f24a6d4a17ad7 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Wed, 25 Nov 2026 19:25:09 +0700 Subject: [PATCH 3/9] [SLS] add the loggers, the catalog and the entry point --- Docs/index.md | 18 + src/Managed/Stellar.LoggingSystem/Logger.cs | 85 +++++ .../Stellar.LoggingSystem/LoggerBase.cs | 154 ++++++++ .../Stellar.LoggingSystem/LoggerCatalog.cs | 64 ++++ .../Stellar.LoggingSystem/LoggerFormats.cs | 185 ---------- .../Stellar.LoggingSystem/LoggerNames.cs | 22 ++ .../Stellar.LoggingSystem/LoggingSettings.cs | 110 ++++++ .../LoggingSystemEntryPoint.cs | 106 ++++++ .../Sink/ConsoleLogger.cs | 63 ++++ .../Stellar.LoggingSystem/Sink/FileLogger.cs | 191 ++++++++++ .../Stellar.LoggingSystem/Sink/LogCaller.cs | 38 ++ .../Sink/LoggerTextFormatter.cs | 54 +++ .../EntryPointTests.cs | 229 ++++++++++++ .../LoggerTests.cs | 294 ++++++++++++++++ .../LoggingSettingsTests.cs | 101 ++++++ .../Stellar.LoggingSystem.Tests/SinkTests.cs | 330 ++++++++++++++++++ .../TestSupport.cs | 90 +++++ 17 files changed, 1949 insertions(+), 185 deletions(-) create mode 100644 src/Managed/Stellar.LoggingSystem/Logger.cs create mode 100644 src/Managed/Stellar.LoggingSystem/LoggerBase.cs create mode 100644 src/Managed/Stellar.LoggingSystem/LoggerCatalog.cs delete mode 100644 src/Managed/Stellar.LoggingSystem/LoggerFormats.cs create mode 100644 src/Managed/Stellar.LoggingSystem/LoggerNames.cs create mode 100644 src/Managed/Stellar.LoggingSystem/LoggingSettings.cs create mode 100644 src/Managed/Stellar.LoggingSystem/LoggingSystemEntryPoint.cs create mode 100644 src/Managed/Stellar.LoggingSystem/Sink/ConsoleLogger.cs create mode 100644 src/Managed/Stellar.LoggingSystem/Sink/FileLogger.cs create mode 100644 src/Managed/Stellar.LoggingSystem/Sink/LogCaller.cs create mode 100644 src/Managed/Stellar.LoggingSystem/Sink/LoggerTextFormatter.cs create mode 100644 tests/Stellar.LoggingSystem.Tests/EntryPointTests.cs create mode 100644 tests/Stellar.LoggingSystem.Tests/LoggerTests.cs create mode 100644 tests/Stellar.LoggingSystem.Tests/LoggingSettingsTests.cs create mode 100644 tests/Stellar.LoggingSystem.Tests/SinkTests.cs create mode 100644 tests/Stellar.LoggingSystem.Tests/TestSupport.cs diff --git a/Docs/index.md b/Docs/index.md index c6aa78c..a5a49b3 100644 --- a/Docs/index.md +++ b/Docs/index.md @@ -13,6 +13,24 @@ Add `Stellar.LoggingSystem` to `Dependencies` of your module or project descript stellar modules sync ``` +## Settings + +In the `Runtime` section of `.stellar.project`, or on the command line (`--stellar:LogPath=logs/game.log`), which wins. +Names in any case. A value that cannot be read is told in the log and left at its default. + +| Setting | Default | What it is | +|---|---|---| +| `LogPath` | none, no file | Where the log is also written. A path of the disk, relative to the folder of the application (`logs/game.log`), needs nothing else. `domain://path` goes through the file system of the engine: the lines wait (up to 1024) till somebody publishes `IFileSystem` and mounts the domain | +| `LogLevel` | `Debug` | The least serious level of the console | +| `LogFileLevel` | `Info` | The least serious level of the file | + +The file is appended to, and can be read while the engine runs. + +## A logger of your own + +Derive from `LoggerBase` (or implement `ILogger`, with `ILabeled` for a name), add it to `ILoggerCatalog` when your +module starts and take it out when it stops. The catalog never disposes what it did not make. + ## Working on it ```powershell diff --git a/src/Managed/Stellar.LoggingSystem/Logger.cs b/src/Managed/Stellar.LoggingSystem/Logger.cs new file mode 100644 index 0000000..d17867b --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/Logger.cs @@ -0,0 +1,85 @@ +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem; + +/// +/// The default logger of an engine: the front door that gives every message to every logger of the catalog. +/// +/// +/// It is a router, not a sink: it formats nothing and writes nowhere. The loggers of the catalog are the +/// sinks (console, file, a module's own), each with its own formats in its meta. +/// It is never in the catalog: refuses it, and a sink that is this logger is +/// skipped. A sink that logs while it fails cannot come back here: routing is remembered per thread. +/// Every member is safe to call from any thread. +/// +public sealed class Logger + : LoggerBase +{ + [ThreadStatic] private static Logger? _routing; + + private readonly ILoggerCatalog _catalog; + private readonly TextWriter? _fallback; + + /// Makes the default logger. + /// The loggers this one gives messages to. + /// Where a failure of a sink is told; the error output if null. + public Logger(ILoggerCatalog catalog, TextWriter? fallback = null) + : base(LoggerNames.Default, minimumLevel: LogLevel.Debug) + { + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _fallback = fallback; + } + + private void WriteFallback(string message) + { + try + { + (_fallback ?? Console.Error).WriteLine($"[Stellar.LoggingSystem] {message}"); + } + catch + { + // ignore + } + } + + /// + protected override void Write(string message, LogLevel? level) + { + if (ReferenceEquals(_routing, this)) + { + WriteFallback($"[reentrant {level}] {message}"); + return; + } + + var previous = _routing; + _routing = this; + try + { + if (_catalog.Count == 0) + { + if (level is LogLevel.Warning or LogLevel.Error or LogLevel.Exception) + WriteFallback($"[{level}] {message}"); + return; + } + + foreach (var sink in _catalog.Values) + { + if (ReferenceEquals(sink, this)) continue; + + try + { + if (level is not null) sink.Log((LogLevel)level, message); + else sink.LogWithoutFormat(message); + } + catch (Exception exception) + { + WriteFallback($"The logger '{sink.UID}' failed: {exception}"); + } + } + } + finally + { + _routing = previous; + } + } +} diff --git a/src/Managed/Stellar.LoggingSystem/LoggerBase.cs b/src/Managed/Stellar.LoggingSystem/LoggerBase.cs new file mode 100644 index 0000000..33b6d56 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/LoggerBase.cs @@ -0,0 +1,154 @@ +using Stellar.Core.Quantization; +using Stellar.Kernel; +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem; + +/// +/// The meta of a logger: its label, its switch, its level and its formats. Safe to change from any thread. +/// +public sealed class LoggerMeta + : MetaQuant +{ + private int _isActive; + private object _format; + private int _minimumLevel; + + /// + /// Gets the label of the logger. + /// + public Label Label { get; } + + /// Makes the meta of a logger. + /// Its name, unique in the catalog. + /// Its activity state. + /// The formats of its lines; if null. + /// The least serious level it takes. + /// Thrown if the name is empty. + public LoggerMeta( + string name, + bool isActive = true, + LoggerFormat? format = null, + LogLevel minimumLevel = LogLevel.Debug + ) + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentException("A logger needs a name", nameof(name)); + + Label = new Label(UID, name); + _isActive = isActive ? 1 : 0; + _format = format ?? LoggerFormat.Default; + _minimumLevel = (int)minimumLevel; + } + + /// + /// Gets or sets whether the logger takes messages. + /// + public bool IsActive + { + get => Volatile.Read(ref _isActive) != 0; + set => Volatile.Write(ref _isActive, value ? 1 : 0); + } + + /// + /// Gets or sets the least serious level the logger takes. + /// + public LogLevel MinimumLevel + { + get => (LogLevel)Volatile.Read(ref _minimumLevel); + set => Volatile.Write(ref _minimumLevel, (int)value); + } + + /// + /// Gets or sets the formats of the lines. + /// + public LoggerFormat Format + { + get => (LoggerFormat)Volatile.Read(ref _format); + set => Volatile.Write(ref _format, value); + } +} + +/// +/// What every logger of this module shares: a meta with its name, switch, level and formats, and the rules of +/// taking a message. +/// +/// Its name in the catalog. +/// Its activity state +/// Its formats; if null. +/// The least serious level it takes. +public abstract class LoggerBase( + string name, + bool isActive = true, + LoggerFormat? format = null, + LogLevel minimumLevel = LogLevel.Debug +) : Quant(new LoggerMeta(name, isActive, format, minimumLevel)), ILogger, ILabeled +{ + /// + /// Gets the label of the logger. + /// + public Label Label => MetaQuant.Label; + + /// + /// Gets whether the logger takes messages. + /// + public bool IsActive => MetaQuant.IsActive; + + /// + /// Gets or sets the least serious level the logger takes. + /// + public LogLevel MinimumLevel + { + get => MetaQuant.MinimumLevel; + set => MetaQuant.MinimumLevel = value; + } + + /// + /// Gets or sets the formats of the lines. + /// + public LoggerFormat Format + { + get => MetaQuant.Format; + set => MetaQuant.Format = value; + } + + private bool IsEnabled(LogLevel level) + { + return level >= MetaQuant.MinimumLevel; + } + + /// + /// Writes a message the logger took: it is active, and the level is serious enough. + /// + /// The message, never null. + /// The level; null for a message without a format. + protected abstract void Write(string message, LogLevel? level); + + /// + public void Log(LogLevel level, string message) + { + // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + if (message is null || !MetaQuant.IsActive || !IsEnabled(level)) return; + Write(message, level); + } + + /// + public void LogWithoutFormat(string message) + { + // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + if (message is null || !MetaQuant.IsActive) return; + Write(message, null); + } + + /// + public virtual void Start() + { + MetaQuant.IsActive = true; + } + + /// + public virtual void Stop() + { + MetaQuant.IsActive = false; + } +} diff --git a/src/Managed/Stellar.LoggingSystem/LoggerCatalog.cs b/src/Managed/Stellar.LoggingSystem/LoggerCatalog.cs new file mode 100644 index 0000000..93bec7f --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/LoggerCatalog.cs @@ -0,0 +1,64 @@ +using Stellar.Kernel; +using Stellar.Kernel.LoggingSystem; +using Stellar.Core.Data.Catalog; + +namespace Stellar.LoggingSystem; + +/// +/// The loggers of one engine, by name: the sinks the default logger writes into. +/// +public sealed class LoggerCatalog() + : Catalog(StringComparer.OrdinalIgnoreCase), ILoggerCatalog +{ + /// + /// Gets the key of a logger: its name, or the text of its identifier. + /// + /// A logger; one with a label () is named by it. + /// The key of . + public static string NameOf(ILogger logger) + { + return logger is ILabeled labeled ? labeled.Label.Name : logger.UID.ToString(); + } + + /// + /// Adds a logger under its name. + /// + /// The logger. + /// true if it was added; false if the name is taken. + /// Thrown if is null. + /// Thrown for a : it routes to the catalog. + public bool Add(ILogger logger) + { + ArgumentNullException.ThrowIfNull(logger); + return TryAdd(NameOf(logger), logger); + } + + /// + /// Takes out the logger under the name of this one. + /// + /// The logger. + /// true if there was one. + /// Thrown if is null. + public bool Remove(ILogger logger) + { + ArgumentNullException.ThrowIfNull(logger); + return Remove(NameOf(logger)); + } + + /// + protected override string NormalizeKey(string key) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException("A logger needs a name", nameof(key)); + return key; + } + + /// + protected override void Validate(string key, ILogger value) + { + base.Validate(key, value); + + if (value is Logger) + throw new ArgumentException("The default logger routes to the catalog: it cannot be in it", nameof(value)); + } +} diff --git a/src/Managed/Stellar.LoggingSystem/LoggerFormats.cs b/src/Managed/Stellar.LoggingSystem/LoggerFormats.cs deleted file mode 100644 index 2260390..0000000 --- a/src/Managed/Stellar.LoggingSystem/LoggerFormats.cs +++ /dev/null @@ -1,185 +0,0 @@ -using Stellar.Kernel.LoggingSystem; - -namespace Stellar.LoggingSystem; - -/// -/// TODO: summary -/// -public sealed class LoggerFormats -{ - /// - /// TODO: summary - /// - public LogFormat Info { get; init; } = new() - { - Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", - ColorizedFormat = "\e[32m{0}\e[0m" + - "\e[31m:\e[0m" + - "\e[2;32m{1}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[1;38m{2}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[36m{3}\e[0m" + - "\e[31m:\e[0m" + - "\e[36m{4}\e[0m " + - // "\e[31m:\e[0m" + - // "\e[36m{5}\e[0m " + - - "\e[31m-\e[0m " + - - "\e[1;38m{6}\e[0m" - }; - - /// - /// TODO: summary - /// - public LogFormat Debug { get; init; } = new() - { - Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", - ColorizedFormat = "\e[32m{0}\e[0m" + - "\e[31m:\e[0m" + - "\e[2;32m{1}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[1;33m{2}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[36m{3}\e[0m" + - "\e[31m:\e[0m" + - "\e[36m{4}\e[0m " + - // "\e[31m:\e[0m" + - // "\e[36m{5}\e[0m " + - - "\e[31m-\e[0m " + - - "\e[1;33m{6}\e[0m" - }; - - /// - /// TODO: summary - /// - public LogFormat Success { get; init; } = new() - { - Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", - ColorizedFormat = "\e[32m{0}\e[0m" + - "\e[31m:\e[0m" + - "\e[2;32m{1}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[1;32m{2}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[36m{3}\e[0m" + - "\e[31m:\e[0m" + - "\e[36m{4}\e[0m " + - // "\e[31m:\e[0m" + - // "\e[36m{5}\e[0m " + - - "\e[31m-\e[0m " + - - "\e[1;32m{6}\e[0m" - }; - - /// - /// TODO: summary - /// - public LogFormat Warning { get; init; } = new() - { - Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", - ColorizedFormat = "\e[32m{0}\e[0m" + - "\e[31m:\e[0m" + - "\e[2;32m{1}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[1;34m{2}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[36m{3}\e[0m" + - "\e[31m:\e[0m" + - "\e[36m{4}\e[0m " + - // "\e[31m:\e[0m" + - // "\e[36m{5}\e[0m " + - - "\e[31m-\e[0m " + - - "\e[1;34m{6}\e[0m" - }; - - /// - /// TODO: summary - /// - public LogFormat Error { get; init; } = new() - { - Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", - ColorizedFormat = "\e[32m{0}\e[0m" + - "\e[31m:\e[0m" + - "\e[2;32m{1}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[1;31m{2}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[36m{3}\e[0m" + - "\e[31m:\e[0m" + - "\e[36m{4}\e[0m" + - // "\e[31m:\e[0m" + - // "\e[36m{5}\e[0m " + - - "\e[31m-\e[0m " + - - "\e[1;38m{6}\e[0m" - }; - - /// - /// TODO: summary - /// - public LogFormat Exception { get; init; } = new() - { - Format = "{0}:{1} | {2} | {3}:{4}:{5} - {6}", - ColorizedFormat = "\e[32m{0}\e[0m" + - "\e[31m:\e[0m" + - "\e[2;32m{1}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[1;31m{2}\e[0m " + - - "\e[31m|\e[0m " + - - "\e[36m{3}\e[0m" + - "\e[31m:\e[0m" + - "\e[36m{4}\e[0m " + - // "\e[31m:\e[0m" + - // "\e[36m{5}\e[0m " + - - "\e[31m-\e[0m " + - - "\e[1;31m{6}\e[0m" - }; - - /// - /// TODO: summary - /// - public LogFormat GetFormat(LogLevel level) => level switch - { - LogLevel.Info => Info, - LogLevel.Debug => Debug, - LogLevel.Success => Success, - LogLevel.Warning => Warning, - LogLevel.Error => Error, - LogLevel.Exception => Exception, - _ => throw new ArgumentOutOfRangeException(nameof(level), level, null) - }; -} diff --git a/src/Managed/Stellar.LoggingSystem/LoggerNames.cs b/src/Managed/Stellar.LoggingSystem/LoggerNames.cs new file mode 100644 index 0000000..e8b8509 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/LoggerNames.cs @@ -0,0 +1,22 @@ +namespace Stellar.LoggingSystem; + +/// +/// The names of the loggers of this module. +/// +public static class LoggerNames +{ + /// + /// The default logger, which routes to the others. + /// + public const string Default = "Default"; + + /// + /// The logger of the console. + /// + public const string Console = "Console"; + + /// + /// The logger of the file. + /// + public const string File = "File"; +} diff --git a/src/Managed/Stellar.LoggingSystem/LoggingSettings.cs b/src/Managed/Stellar.LoggingSystem/LoggingSettings.cs new file mode 100644 index 0000000..ef91ab3 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/LoggingSettings.cs @@ -0,0 +1,110 @@ +using Stellar.Kernel.Configuration; +using Stellar.Kernel.FileSystem; +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem; + +/// +/// What the module reads from the settings of the application: the Runtime section of .stellar.project, +/// or the command line (--stellar:LogPath=logs/game.log). Every setting may be missing. +/// +/// A value that cannot be read is told in and left at its default: a typing error in +/// the settings of logging never stops an engine. +public sealed class LoggingSettings +{ + /// The setting of the file of the log. + public const string LogPathName = "LogPath"; + + /// The setting of the least serious level of the console. + public const string LogLevelName = "LogLevel"; + + /// The setting of the least serious level of the file. + public const string LogFileLevelName = "LogFileLevel"; + + private readonly List _problems = []; + + /// + /// Gets the path of the log in the file system of the engine, if LogPath is domain://path. + /// + public FilePath? EnginePath { get; } + + /// + /// Gets the full path of the log on the disk, if LogPath is a path of the machine. A relative one starts at + /// the folder of the application. + /// + public string? DiskPath { get; } + + /// + /// Gets the least serious level of the console. + /// + public LogLevel ConsoleLevel { get; } + + /// + /// Gets the least serious level of the file. + /// + public LogLevel FileLevel { get; } + + /// + /// Gets what could not be read. + /// + public IReadOnlyList Problems => _problems; + + /// + /// Reads the settings. + /// + /// The configuration of the application. + /// Where a relative disk path starts; the folder of the application if null. + public LoggingSettings(RuntimeConfiguration configuration, string? baseDirectory = null) + { + ArgumentNullException.ThrowIfNull(configuration); + + ConsoleLevel = Level(configuration, LogLevelName, LogLevel.Debug); + FileLevel = Level(configuration, LogFileLevelName, LogLevel.Info); + + string? text = Find(configuration, LogPathName); + if (text is null) return; + + if (text.Contains(FilePath.DomainSeparator, StringComparison.Ordinal)) + { + if (FilePath.TryParse(text, out FilePath path) && !path.IsRoot) EnginePath = path; + else _problems.Add($"{LogPathName}: '{text}' is not the path of a file, expected domain://path"); + return; + } + + try + { + string full = Path.GetFullPath(text, baseDirectory ?? AppContext.BaseDirectory); + if (Path.GetFileName(full).Length > 0) DiskPath = full; + else _problems.Add($"{LogPathName}: '{text}' is a folder, expected a file"); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException + or PathTooLongException) + { + _problems.Add($"{LogPathName}: '{text}' is not a path: {exception.Message}"); + } + } + + private static string? Find(RuntimeConfiguration configuration, string name) + { + // The settings of a configuration made by hand may tell case apart + foreach ((string key, string value) in configuration.Settings) + if (string.Equals(key, name, StringComparison.OrdinalIgnoreCase)) + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + return null; + } + + private LogLevel Level(RuntimeConfiguration configuration, string name, LogLevel fallback) + { + string? text = Find(configuration, name); + if (text is null) return fallback; + + // Names only: Enum.TryParse alone takes any number, and lists of names + if (Enum.GetNames().Contains(text, StringComparer.OrdinalIgnoreCase)) + return Enum.Parse(text, true); + + _problems.Add( + $"{name}: '{text}' is not a level, expected one of {string.Join(", ", Enum.GetNames())}"); + return fallback; + } +} diff --git a/src/Managed/Stellar.LoggingSystem/LoggingSystemEntryPoint.cs b/src/Managed/Stellar.LoggingSystem/LoggingSystemEntryPoint.cs new file mode 100644 index 0000000..3dc5a38 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/LoggingSystemEntryPoint.cs @@ -0,0 +1,106 @@ +using Stellar.Kernel.Configuration; +using Stellar.Kernel.EntryPoint; +using Stellar.Kernel.FileSystem; +using Stellar.Kernel.Lifecycle; +using Stellar.Kernel.LoggingSystem; +using Stellar.Kernel.Services; +using Stellar.LoggingSystem.Sink; + +namespace Stellar.LoggingSystem; + +/// +/// Publishes the logger of the engine and its catalog, with a console and, if the settings name one, a file. +/// +/// The configuration of the application (). +[StellarEntryPoint] +public sealed class LoggingSystemEntryPoint(RuntimeConfiguration configuration) + : StellarEntryPoint(LoggingSystemModule.Id, configuration) +{ + private LoggerCatalog? _catalog; + private Logger? _logger; + private IServiceCatalog? _services; + private ConsoleLogger? _console; + private FileLogger? _file; + + private static Stream? OpenEngine(IServiceCatalog services, FilePath path) + { + // Nobody published a file system, or mounted the domain, yet: the logger keeps the lines and asks again + if (services.Find() is not { } files || !files.Domains.Contains(path.Domain)) return null; + + FilePath directory = path.Parent; + if (!directory.IsRoot) files.CreateDirectory(directory); + return files.Open(path, FileOpenOptions.Append); + } + + private static Stream OpenDisk(string path) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + // Can be read while the engine runs + return new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read); + } + + private static FileLogger? MakeFile(LoggingSettings settings, IServiceCatalog services, IEngineInstance engine) + { + if (settings.EnginePath is { } path) + return new FileLogger(engine, () => OpenEngine(services, path), minimumLevel: settings.FileLevel); + if (settings.DiskPath is { } disk) + return new FileLogger(engine, () => OpenDisk(disk), minimumLevel: settings.FileLevel); + return null; + } + + /// + public override int Run(ref readonly TContext context) + { + if (context.Services is not { } services || context.Engine is not { } engine) return 1; + + var settings = new LoggingSettings(RuntimeConfiguration); + _services = services; + _catalog = new LoggerCatalog(); + _logger = new Logger(_catalog); + + _console = new ConsoleLogger(engine, minimumLevel: settings.ConsoleLevel); + _catalog.Add(_console); + + _file = MakeFile(settings, services, engine); + if (_file is not null) _catalog.Add(_file); + + services.Set(_catalog); + services.Set(_logger); + + _logger.Info($"Logging started: {_catalog.Count} logger(s)"); + foreach (string problem in settings.Problems) _logger.Warning(problem); + return 0; + } + + /// + public override void RequestStop(ref readonly TContext context) + { + _logger?.Info("Logging stopped"); + Withdraw(); + _logger?.Stop(); + + foreach (ILogger sink in _catalog?.Values ?? []) + sink.Stop(); + } + + /// + public override void Dispose() + { + Withdraw(); + _logger?.Stop(); + + // Its own only: the loggers other modules added are theirs + _console?.Stop(); + _file?.Dispose(); + } + + private void Withdraw() + { + if (_services is not { } services) return; + _services = null; + + // Another module may have put its own there since + if (ReferenceEquals(services.Find(), _logger)) services.Remove(); + if (ReferenceEquals(services.Find(), _catalog)) services.Remove(); + } +} diff --git a/src/Managed/Stellar.LoggingSystem/Sink/ConsoleLogger.cs b/src/Managed/Stellar.LoggingSystem/Sink/ConsoleLogger.cs new file mode 100644 index 0000000..a99c1ac --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/Sink/ConsoleLogger.cs @@ -0,0 +1,63 @@ +using Stellar.Kernel.Lifecycle; +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem.Sink; + +/// +/// Writes messages to the console. +/// +public class ConsoleLogger + : LoggerBase +{ + private readonly IEngineInstance _engine; + private readonly TextWriter _output; + private readonly bool _colorized; + private readonly Lock _gate = new(); + + /// Makes a console logger. + /// The engine it tells about. + /// Where it writes; the standard output if null. + /// + /// Whether to color the lines; if null, only those of a standard output that is not redirected, unless + /// NO_COLOR is set. + /// + /// The formats of the lines; if null. + /// The least serious level it takes. + public ConsoleLogger( + IEngineInstance engine, + TextWriter? output = null, + bool? colorized = null, + LoggerFormat? format = null, + LogLevel minimumLevel = LogLevel.Debug + ) : base(LoggerNames.Console, true, format, minimumLevel) + { + _engine = engine ?? throw new ArgumentNullException(nameof(engine)); + _output = output ?? Console.Out; + _colorized = colorized ?? (output is null + && !Console.IsOutputRedirected + && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NO_COLOR"))); + } + + /// + protected override void Write(string message, LogLevel? level) + { + string line = level is { } known + ? LoggerTextFormatter.Format(Format.ForLevel(known), _colorized, known, message, Label.Name, _engine) + : message; + + lock (_gate) + { + _output.WriteLine(line); + } + } + + /// + public override void Stop() + { + base.Stop(); + lock (_gate) + { + _output.Flush(); + } + } +} diff --git a/src/Managed/Stellar.LoggingSystem/Sink/FileLogger.cs b/src/Managed/Stellar.LoggingSystem/Sink/FileLogger.cs new file mode 100644 index 0000000..3a1d01b --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/Sink/FileLogger.cs @@ -0,0 +1,191 @@ +using System.Text; + +using Stellar.Kernel.Lifecycle; +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem.Sink; + +/// +/// Writes messages to a stream, opened at the first of them. +/// +/// +/// While there is nowhere to write yet (the file system of the engine comes later), the lines are kept and written +/// once there is. A stream that fails is told once and given up until . +/// +public class FileLogger + : LoggerBase, IDisposable +{ + /// + /// The most lines kept while there is nowhere to write; the oldest are dropped first. + /// + public const int MaxPending = 1024; + + private readonly IEngineInstance _engine; + private readonly Func _open; + private readonly bool _autoFlush; + private readonly TextWriter? _fallback; + private readonly Lock _gate = new(); + private readonly Queue _pending = new(); + + private StreamWriter? _writer; + private long _dropped; + private bool _failed; + + /// Makes a file logger. + /// The engine it tells about. + /// Opens the stream; null from it means there is nowhere to write yet. + /// Whether every line is flushed at once; errors always are. + /// The formats of the lines; if null. + /// The least serious level it takes. + /// Where its own failure is told; the error output if null. + public FileLogger( + IEngineInstance engine, + Func open, + bool autoFlush = true, + LoggerFormat? format = null, + LogLevel minimumLevel = LogLevel.Info, + TextWriter? fallback = null + ) : base(LoggerNames.File, true, format, minimumLevel) + { + _engine = engine ?? throw new ArgumentNullException(nameof(engine)); + _open = open ?? throw new ArgumentNullException(nameof(open)); + _autoFlush = autoFlush; + _fallback = fallback; + } + + private void Tell(string message) + { + try + { + (_fallback ?? Console.Error).WriteLine($"[Stellar.LoggingSystem] {message}"); + } + catch + { + // There is nobody left to tell + } + } + + private bool TryOpen() + { + if (_writer is not null) return true; + if (_open() is not { } stream) return false; + + _writer = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = _autoFlush }; + + if (_dropped > 0) _writer.WriteLine($"[{_dropped} message(s) were dropped before the log could be opened]"); + _dropped = 0; + while (_pending.TryDequeue(out string? line)) _writer.WriteLine(line); + return true; + } + + private void Close() + { + StreamWriter? writer = _writer; + _writer = null; + writer?.Dispose(); + } + + private void Fail(Exception exception) + { + _failed = true; + _pending.Clear(); + _dropped = 0; + + try + { + Close(); + } + catch + { + // Closing a broken stream may fail as writing did + } + + Tell($"The file logger failed: {exception}"); + } + + private void Keep(string line) + { + if (_pending.Count == MaxPending) + { + _pending.Dequeue(); + _dropped++; + } + + _pending.Enqueue(line); + } + + /// + protected override void Write(string message, LogLevel? level) + { + string line = level is { } known + ? LoggerTextFormatter.Format(Format.ForLevel(known), false, known, message, Label.Name, _engine) + : message; + + lock (_gate) + { + if (_failed) return; + + try + { + if (!TryOpen()) + { + Keep(line); + return; + } + + _writer!.WriteLine(line); + if (!_autoFlush && level is LogLevel.Error or LogLevel.Exception) _writer.Flush(); + } + catch (Exception exception) + { + Fail(exception); + } + } + } + + /// + /// Takes messages again, also after a failure. + /// + public override void Start() + { + lock (_gate) + { + _failed = false; + } + + base.Start(); + } + + /// + /// Closes the stream; lines that had nowhere to go till now are told about. + /// + public override void Stop() + { + base.Stop(); + + lock (_gate) + { + try + { + if (_pending.Count > 0 && !TryOpen()) + { + Tell($"{_pending.Count + _dropped} message(s) were not written: the log could not be opened"); + _pending.Clear(); + _dropped = 0; + } + + Close(); + } + catch (Exception exception) + { + Fail(exception); + } + } + } + + /// + public void Dispose() + { + Stop(); + } +} diff --git a/src/Managed/Stellar.LoggingSystem/Sink/LogCaller.cs b/src/Managed/Stellar.LoggingSystem/Sink/LogCaller.cs new file mode 100644 index 0000000..c862e06 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/Sink/LogCaller.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; + +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem.Sink; + +/// +/// Finds who logs: the first method on the stack that does not belong to logging. Nothing is counted in frames, so +/// it does not depend on how the code was compiled or on how many loggers a message goes through. +/// +internal static class LogCaller +{ + private const string UnknownType = "UnknownType"; + private const string UnknownMethod = "UnknownMethod"; + + public static (string Type, string Method) Find() + { + foreach (StackFrame frame in new StackTrace(false).GetFrames()) + { + if (frame.GetMethod() is not { DeclaringType: { } type } method) continue; + if (type.Assembly == typeof(LogCaller).Assembly || type == typeof(LoggerExtensions)) continue; + + // A loop of an async method or a lambda: d__0.MoveNext, <>c.b__0 + string name = Original(type.Name) ?? Original(method.Name) ?? method.Name; + while (type.Name.StartsWith('<') && type.DeclaringType is { } outer) type = outer; + + return (type.FullName ?? type.Name, name); + } + + return (UnknownType, UnknownMethod); + } + + private static string? Original(string name) + { + int end = name.IndexOf('>'); + return name.StartsWith('<') && end > 1 ? name[1..end] : null; + } +} diff --git a/src/Managed/Stellar.LoggingSystem/Sink/LoggerTextFormatter.cs b/src/Managed/Stellar.LoggingSystem/Sink/LoggerTextFormatter.cs new file mode 100644 index 0000000..cc0db75 --- /dev/null +++ b/src/Managed/Stellar.LoggingSystem/Sink/LoggerTextFormatter.cs @@ -0,0 +1,54 @@ +using System.Globalization; + +using Stellar.Kernel.Lifecycle; +using Stellar.Kernel.LoggingSystem; +using Stellar.Kernel.Timing; + +namespace Stellar.LoggingSystem.Sink; + +/// +/// Makes the line of a message. +/// +public static class LoggerTextFormatter +{ + /// + /// Makes the line of a message; the placeholders are those of . + /// + /// The format of the level. + /// Whether to use the colorized format, if there is one. + /// The level of the message. + /// The message. + /// The name of the logger. + /// The engine whose name and clock go into the line. + /// The line, without a line end. + public static string Format( + LogFormat format, bool colorized, LogLevel level, string message, + string loggerName, IEngineInstance engine + ) + { + string text = colorized ? format.ColorizedFormat ?? format.Format : format.Format; + DateTime now = DateTime.Now; + IClock clock = engine.Time.Engine; + + // Walking the stack is most of the price of a line: only for the formats that show it + (string type, string method) = text.Contains("{8") || text.Contains("{9") + ? LogCaller.Find() + : (string.Empty, string.Empty); + + return string.Format( + CultureInfo.InvariantCulture, // cultures + text, // format + now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), // 0 + now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture), // 1 + clock.Name, // 2 + TimeSpan.FromSeconds(clock.Time).ToString(@"hh\:mm\:ss\.fff", CultureInfo.InvariantCulture), // 3 + level, // 4 + engine.Name, // 5 + loggerName, // 6 + Environment.CurrentManagedThreadId, // 7 + type, // 8 + method, // 9 + message // 10 + ); + } +} diff --git a/tests/Stellar.LoggingSystem.Tests/EntryPointTests.cs b/tests/Stellar.LoggingSystem.Tests/EntryPointTests.cs new file mode 100644 index 0000000..475ff05 --- /dev/null +++ b/tests/Stellar.LoggingSystem.Tests/EntryPointTests.cs @@ -0,0 +1,229 @@ +using System.Text; + +using Stellar.Core.EntryPoints; +using Stellar.Core.Services; +using Stellar.Kernel.Configuration; +using Stellar.Kernel.Data.Catalog; +using Stellar.Kernel.EntryPoint; +using Stellar.Kernel.FileSystem; +using Stellar.Kernel.LoggingSystem; +using Stellar.Kernel.Services; + +namespace Stellar.LoggingSystem.Tests; + +public sealed class EntryPointTests + : IDisposable +{ + private readonly ServiceCatalog _services = new(); + private readonly TempFolder _folder = new(); + + public void Dispose() + { + _folder.Dispose(); + } + + private static LoggingSystemEntryPoint Make(params (string Name, string Value)[] settings) + { + return new LoggingSystemEntryPoint(new RuntimeConfiguration + { Settings = settings.ToDictionary(it => it.Name, it => it.Value) }); + } + + private static int Run(LoggingSystemEntryPoint entryPoint, ServiceCatalog services) + { + var context = new RunContext(null, services: services, engine: Stub.Engine()); + return entryPoint.Run(in context); + } + + private static void Stop(LoggingSystemEntryPoint entryPoint) + { + var context = new StopContext(null, StopReason.Regular); + entryPoint.RequestStop(in context); + entryPoint.Dispose(); + } + + // A file system with one domain, mounted when it is told to + private static IFileSystem Files(List calls, Func mounted, MemoryStream written) + { + var domain = Stub.Of((member, args) => + { + calls.Add($"{member} {args[0]}"); + return member == nameof(IDomain.Open) ? written : null; + }); + IReadOnlyCatalog domains = Stub.Of>((member, _) => + member == "Contains" ? mounted() : domain); + return Stub.Of((_, _) => domains); + } + + [Fact] + public void Run_PublishesTheLoggerAndTheCatalog_AndStop_TakesThemBack() + { + LoggingSystemEntryPoint entryPoint = Make(); + Run(entryPoint, _services).Should().Be(0); + + _services.Find().Should().BeOfType(); + _services.Get().Keys.Should().Equal(LoggerNames.Console); + + Stop(entryPoint); + _services.Find().Should().BeNull(); + _services.Find().Should().BeNull(); + } + + [Fact] + public void Run_OutsideAnEngine_DoesNotStart_AndStillStops() + { + LoggingSystemEntryPoint entryPoint = Make(); + var nothing = new RunContext(null); + entryPoint.Run(in nothing).Should().NotBe(0); + var withoutEngine = new RunContext(null, services: _services); + entryPoint.Run(in withoutEngine).Should().NotBe(0); + + _services.Count.Should().Be(0); + FluentActions.Invoking(() => Stop(entryPoint)).Should().NotThrow(); + } + + [Fact] + public void APathOfTheDisk_NeedsNoFileSystem() + { + string path = Path.Combine(_folder.Path, "logs", "game.log"); + LoggingSystemEntryPoint entryPoint = Make(("LogPath", path)); + Run(entryPoint, _services); + _services.Get().Error("hello"); + + // Can be read while the engine runs + using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) + { + reader.ReadToEnd().Should().Contain("hello"); + } + + Stop(entryPoint); + File.ReadAllText(path).Should().Contain("Logging started: 2").And.Contain("Logging stopped"); + } + + [Fact] + public void ALogOfTheDisk_IsAppendedTo() + { + string path = Path.Combine(_folder.Path, "game.log"); + + for (int run = 0; run < 2; run++) + { + LoggingSystemEntryPoint entryPoint = Make(("LogPath", path)); + Run(entryPoint, _services); + Stop(entryPoint); + } + + File.ReadAllText(path).Split("Logging started").Should().HaveCount(3); + } + + [Fact] + public void APathOfTheEngine_WaitsForTheFileSystemAndForItsDomain() + { + List calls = new(); + bool mounted = false; + var written = new MemoryStream(); + LoggingSystemEntryPoint entryPoint = Make(("LogPath", "user://logs/game.log")); + Run(entryPoint, _services); + var logger = _services.Get(); + + logger.Error("before the file system"); + _services.Set(Files(calls, () => mounted, written)); + logger.Error("before the domain"); + calls.Should().BeEmpty(); + + mounted = true; + logger.Error("after"); + Stop(entryPoint); + + calls.Should().Equal("CreateDirectory logs", "Open logs/game.log"); + Encoding.UTF8.GetString(written.ToArray()).Should().MatchRegex( + "(?s)Logging started.*before the file system.*before the domain.*after.*Logging stopped"); + } + + [Fact] + public void Levels_ComeFromTheSettings() + { + string path = Path.Combine(_folder.Path, "game.log"); + LoggingSystemEntryPoint entryPoint = Make(("LogPath", path), ("LogFileLevel", "Error")); + Run(entryPoint, _services); + _services.Get().Warning("too quiet"); + _services.Get().Error("loud"); + Stop(entryPoint); + + File.ReadAllText(path).Should().Contain("loud").And.NotContain("too quiet").And.NotContain("started"); + } + + [Fact] + public void ABadSetting_DoesNotStopTheEngine() + { + LoggingSystemEntryPoint entryPoint = Make(("LogPath", "://"), ("LogLevel", "loud")); + + Run(entryPoint, _services).Should().Be(0); + _services.Get().Keys.Should().Equal(LoggerNames.Console); + Stop(entryPoint); + } + + [Fact] + public void AFileThatCannotBeOpened_DoesNotStopTheEngine() + { + // A folder where the file should be + LoggingSystemEntryPoint entryPoint = Make(("LogPath", _folder.Path)); + + Run(entryPoint, _services).Should().Be(0); + _services.Get().Invoking(logger => logger.Error("m")).Should().NotThrow(); + Stop(entryPoint); + } + + [Fact] + public void ALoggerOfAnotherModule_HearsTheEngine_AndIsStopped() + { + LoggingSystemEntryPoint entryPoint = Make(); + Run(entryPoint, _services); + var foreign = new RecordingLogger("Foreign"); + _services.Get().TryAdd("Foreign", foreign).Should().BeTrue(); + + _services.Get().Info("m"); + Stop(entryPoint); + + foreign.Lines.Should().Equal("Info:m", "Info:Logging stopped"); + foreign.IsActive.Should().BeFalse(); + } + + [Fact] + public void Stop_LeavesTheLoggerAnotherModulePublished() + { + LoggingSystemEntryPoint entryPoint = Make(); + Run(entryPoint, _services); + var other = new RecordingLogger("Other"); + _services.Set(other); + + Stop(entryPoint); + + _services.Find().Should().BeSameAs(other); + } + + [Fact] + public void Dispose_WithoutAStop_TakesEverythingBack() + { + LoggingSystemEntryPoint entryPoint = Make(); + Run(entryPoint, _services); + + entryPoint.Dispose(); + entryPoint.Dispose(); + + _services.Find().Should().BeNull(); + } + + [Fact] + public void TwoEngines_HaveLoggersOfTheirOwn() + { + LoggingSystemEntryPoint first = Make(); + LoggingSystemEntryPoint second = Make(); + var other = new ServiceCatalog(); + Run(first, _services); + Run(second, other); + + other.Get().Should().NotBeSameAs(_services.Get()); + Stop(first); + other.Find().Should().NotBeNull(); + Stop(second); + } +} diff --git a/tests/Stellar.LoggingSystem.Tests/LoggerTests.cs b/tests/Stellar.LoggingSystem.Tests/LoggerTests.cs new file mode 100644 index 0000000..63c5fea --- /dev/null +++ b/tests/Stellar.LoggingSystem.Tests/LoggerTests.cs @@ -0,0 +1,294 @@ +using Stellar.Kernel; +using Stellar.Kernel.LoggingSystem; +using Stellar.Kernel.Quantization; + +namespace Stellar.LoggingSystem.Tests; + +public class LoggerTests +{ + private readonly StringWriter _fallback = new(); + private readonly LoggerCatalog _catalog = new(); + + private Logger Logger(params RecordingLogger[] sinks) + { + foreach (RecordingLogger sink in sinks) _catalog.Add(sink).Should().BeTrue(); + return new Logger(_catalog, _fallback); + } + + [Fact] + public void EveryLogger_HasAnIdentifierOfItsOwn_AndALabelWithIt() + { + var a = new RecordingLogger("A"); + var b = new RecordingLogger("B"); + + a.UID.Should().NotBe(b.UID); + a.Label.Name.Should().Be("A"); + a.Label.UID.Should().Be(a.UID); + a.FindMeta().Should().BeSameAs(a.Meta); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void AName_IsNeeded(string name) + { + FluentActions.Invoking(() => new RecordingLogger(name)).Should().Throw(); + } + + [Fact] + public void Format_CanBeReplaced() + { + var sink = new RecordingLogger("A"); + sink.Format.Should().Be(LoggerFormat.Default); + + LoggerFormat format = LoggerFormat.Default with { Info = new LogFormat("{10}") }; + sink.Format = format; + + sink.Format.Should().Be(format); + } + + [Fact] + public void Format_IsNeverSeenHalfWritten() + { + var sink = new RecordingLogger("A"); + int torn = 0; + + Parallel.For(0, 20_000, index => + { + if (index % 2 == 0) + { + var one = new LogFormat(index.ToString()); + sink.Format = new LoggerFormat(one, one, one, one, one, one); + return; + } + + LoggerFormat format = sink.Format; + if (format != LoggerFormat.Default && format.Info != format.Exception) Interlocked.Increment(ref torn); + }); + + torn.Should().Be(0); + } + + [Fact] + public void MinimumLevel_TakesTheLevelAndEveryOneMoreSerious() + { + var sink = new RecordingLogger("A", LogLevel.Success); + + foreach (LogLevel level in Enum.GetValues()) sink.Log(level, "m"); + sink.Lines.Should().Equal("Success:m", "Warning:m", "Error:m", "Exception:m"); + + sink.MinimumLevel = LogLevel.Exception; + sink.Log(LogLevel.Error, "lost"); + sink.Lines.Should().HaveCount(4); + } + + [Fact] + public void AMessageWithoutFormat_IsTurnedAwayByNoLevel() + { + var sink = new RecordingLogger("A", LogLevel.Exception); + sink.LogWithoutFormat("raw"); + sink.Lines.Should().Equal(":raw"); + } + + [Fact] + public void NoMessage_IsIgnored() + { + var sink = new RecordingLogger("A"); + sink.Log(LogLevel.Error, null!); + sink.LogWithoutFormat(null!); + sink.Lines.Should().BeEmpty(); + } + + [Fact] + public void AStoppedLogger_TakesNothing_TillItStarts() + { + var sink = new RecordingLogger("A"); + sink.Stop(); + sink.IsActive.Should().BeFalse(); + sink.Log(LogLevel.Error, "lost"); + sink.LogWithoutFormat("lost"); + sink.Start(); + sink.Log(LogLevel.Error, "kept"); + + sink.Lines.Should().Equal("Error:kept"); + } + + [Fact] + public void Logger_GivesAMessageToEverySinkThatTakesItsLevel() + { + var all = new RecordingLogger("All"); + var serious = new RecordingLogger("Serious", LogLevel.Warning); + Logger logger = Logger(all, serious); + + logger.Log(LogLevel.Debug, "d"); + logger.Log(LogLevel.Error, "e"); + logger.LogWithoutFormat("raw"); + + all.Lines.Should().Equal("Debug:d", "Error:e", ":raw"); + serious.Lines.Should().Equal("Error:e", ":raw"); + } + + [Fact] + public void Extensions_LogAtTheirLevels() + { + var sink = new RecordingLogger("A"); + Logger logger = Logger(sink); + + logger.Debug("m"); + logger.Info("m"); + logger.Success("m"); + logger.Warning("m"); + logger.Error("m"); + logger.Separator(); + logger.Exception("doing", new InvalidOperationException("why")); + + sink.Lines[..6].Should().Equal("Debug:m", "Info:m", "Success:m", "Warning:m", "Error:m", ":"); + sink.Lines[6].Should().StartWith("Exception:doing").And.Contain("InvalidOperationException").And.Contain("why"); + } + + [Fact] + public void Logger_SurvivesABrokenSink() + { + var healthy = new RecordingLogger("Healthy"); + Logger(new RecordingLogger("Broken", fails: true), healthy).Log(LogLevel.Info, "m"); + + healthy.Lines.Should().Equal("Info:m"); + _fallback.ToString().Should().Contain("broken"); + } + + [Fact] + public void Logger_SurvivesABrokenFallback() + { + _catalog.Add(new RecordingLogger("Broken", fails: true)); + var closed = new StreamWriter(new MemoryStream()); + closed.Dispose(); + + new Logger(_catalog, closed).Invoking(logger => logger.Log(LogLevel.Info, "m")).Should().NotThrow(); + } + + [Fact] + public void Logger_WithoutSinks_TellsOnlyWhatIsSerious() + { + Logger logger = Logger(); + logger.Info("quiet"); + logger.Warning("loud"); + + _fallback.ToString().Should().Contain("loud").And.NotContain("quiet"); + } + + [Fact] + public void ASinkThatLogs_DoesNotComeBackToItself() + { + Logger? logger = null; + var sink = new RecordingLogger("Talkative") { OnWrite = () => logger!.Error("again") }; + logger = Logger(sink); + + logger.Info("m"); + + sink.Lines.Should().Equal("Info:m"); + _fallback.ToString().Should().Contain("reentrant").And.Contain("again"); + + // And the next message goes through as usual + logger.Info("n"); + sink.Lines.Should().Equal("Info:m", "Info:n"); + } + + [Fact] + public void TwoEngines_LogInsideOneAnother() + { + var inner = new RecordingLogger("Inner"); + var innerCatalog = new LoggerCatalog(); + innerCatalog.Add(inner); + var innerLogger = new Logger(innerCatalog, _fallback); + + Logger(new RecordingLogger("Outer") { OnWrite = () => innerLogger.Info("from outer") }).Info("m"); + + inner.Lines.Should().Equal("Info:from outer"); + } + + [Fact] + public void Logger_TakesMessagesFromManyThreads() + { + var sink = new RecordingLogger("A"); + Logger logger = Logger(sink); + + Parallel.For(0, 1000, index => logger.Info(index.ToString())); + + sink.Lines.Should().HaveCount(1000).And.OnlyHaveUniqueItems(); + _fallback.ToString().Should().BeEmpty(); + } + + [Fact] + public void Logger_NeedsACatalog() + { + FluentActions.Invoking(() => new Logger(null!)).Should().Throw(); + } + + [Fact] + public void Catalog_NamesInAnyCase() + { + var sink = new RecordingLogger("Audio"); + _catalog.Add(sink).Should().BeTrue(); + + _catalog.Get("AUDIO").Should().BeSameAs(sink); + _catalog.Add(new RecordingLogger("audio")).Should().BeFalse(); + _catalog.Remove(sink).Should().BeTrue(); + _catalog.Remove(sink).Should().BeFalse(); + _catalog.Count.Should().Be(0); + } + + [Fact] + public void Catalog_RefusesTheDefaultLogger_NoLogger_AndNoName() + { + _catalog.Invoking(it => it.Add(new Logger(it))).Should().Throw(); + _catalog.Invoking(it => it.Add(null!)).Should().Throw(); + _catalog.Invoking(it => it.Remove((ILogger)null!)).Should().Throw(); + _catalog.Invoking(it => it.TryAdd(" ", new RecordingLogger("A"))).Should().Throw(); + } + + [Fact] + public void Catalog_NamesALoggerOfAnotherModule_ByItsLabel_OrItsIdentifier() + { + LoggerCatalog.NameOf(new LabeledLogger(Label.New("Foreign"))).Should().Be("Foreign"); + + var plain = new PlainLogger(); + LoggerCatalog.NameOf(plain).Should().Be(plain.UID.ToString()); + } + + private class PlainLogger + : ILogger + { + public virtual Identifier UID { get; } = Identifier.New(); + public IMetaQuant Meta => throw new NotSupportedException(); + public IReadOnlyList Metas => []; + + public TMeta? FindMeta() + where TMeta : class, IMetaQuant + { + return null; + } + + public void Log(LogLevel level, string message) + { + } + + public void LogWithoutFormat(string message) + { + } + + public void Start() + { + } + + public void Stop() + { + } + } + + private sealed class LabeledLogger(Label label) + : PlainLogger, ILabeled + { + public Label Label => label; + public override Identifier UID => label.UID; + } +} diff --git a/tests/Stellar.LoggingSystem.Tests/LoggingSettingsTests.cs b/tests/Stellar.LoggingSystem.Tests/LoggingSettingsTests.cs new file mode 100644 index 0000000..52aee3b --- /dev/null +++ b/tests/Stellar.LoggingSystem.Tests/LoggingSettingsTests.cs @@ -0,0 +1,101 @@ +using Stellar.Kernel.Configuration; +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem.Tests; + +public class LoggingSettingsTests +{ + private static readonly string Base = Path.Combine(Path.GetTempPath(), "game"); + + private static LoggingSettings Read(params (string Name, string Value)[] settings) + { + return new LoggingSettings( + new RuntimeConfiguration { Settings = settings.ToDictionary(it => it.Name, it => it.Value) }, Base); + } + + [Fact] + public void Nothing_IsTheDefault() + { + LoggingSettings settings = Read(); + + settings.EnginePath.Should().BeNull(); + settings.DiskPath.Should().BeNull(); + settings.ConsoleLevel.Should().Be(LogLevel.Debug); + settings.FileLevel.Should().Be(LogLevel.Info); + settings.Problems.Should().BeEmpty(); + } + + [Theory] + [InlineData("LogPath")] + [InlineData("logPath")] + [InlineData("LOGPATH")] + public void Names_AreInAnyCase(string name) + { + Read((name, "user://logs/game.log")).EnginePath!.Value.ToString().Should().Be("user://logs/game.log"); + } + + [Fact] + public void ARelativePath_StartsAtTheApplication() + { + LoggingSettings settings = Read(("LogPath", "logs/game.log")); + + settings.DiskPath.Should().Be(Path.GetFullPath("logs/game.log", Base)); + settings.EnginePath.Should().BeNull(); + } + + [Fact] + public void AFullPath_IsTakenAsItIs() + { + string full = Path.GetFullPath("somewhere/game.log", Path.GetTempPath()); + Read(("LogPath", full)).DiskPath.Should().Be(full); + } + + [Theory] + [InlineData("://x")] + [InlineData("user://")] + [InlineData("user://../out.log")] + [InlineData("logs/")] + [InlineData("bad\0path")] + public void ABadPath_IsAProblem_NotAFailure(string path) + { + LoggingSettings settings = Read(("LogPath", path)); + + settings.EnginePath.Should().BeNull(); + settings.DiskPath.Should().BeNull(); + settings.Problems.Should().ContainSingle().Which.Should().StartWith("LogPath"); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void AnEmptyPath_IsNone(string path) + { + LoggingSettings settings = Read(("LogPath", path)); + + settings.DiskPath.Should().BeNull(); + settings.Problems.Should().BeEmpty(); + } + + [Fact] + public void Levels_AreNames() + { + LoggingSettings settings = Read(("LogLevel", "warning"), ("LogFileLevel", "Error")); + + settings.ConsoleLevel.Should().Be(LogLevel.Warning); + settings.FileLevel.Should().Be(LogLevel.Error); + settings.Problems.Should().BeEmpty(); + } + + [Theory] + [InlineData("loud")] + [InlineData("3")] + [InlineData("99")] + [InlineData("Debug,Info")] + public void ABadLevel_IsAProblem_AndTheDefault(string level) + { + LoggingSettings settings = Read(("LogLevel", level)); + + settings.ConsoleLevel.Should().Be(LogLevel.Debug); + settings.Problems.Should().ContainSingle().Which.Should().Contain("Warning"); + } +} diff --git a/tests/Stellar.LoggingSystem.Tests/SinkTests.cs b/tests/Stellar.LoggingSystem.Tests/SinkTests.cs new file mode 100644 index 0000000..b9f325b --- /dev/null +++ b/tests/Stellar.LoggingSystem.Tests/SinkTests.cs @@ -0,0 +1,330 @@ +using System.Text; +using System.Text.RegularExpressions; + +using Stellar.Kernel.LoggingSystem; +using Stellar.LoggingSystem.Sink; + +namespace Stellar.LoggingSystem.Tests; + +public class SinkTests +{ + private static readonly LoggerFormat Plain = Same(new LogFormat("{4}|{10}", "\e[1m{4}|{10}\e[0m")); + private static readonly LoggerFormat Caller = Same(new LogFormat("{8}.{9}")); + + private readonly StringWriter _fallback = new(); + + private static LoggerFormat Same(LogFormat format) + { + return new LoggerFormat(format, format, format, format, format, format); + } + + private FileLogger File(Func open, bool autoFlush = true) + { + return new FileLogger(Stub.Engine(), open, autoFlush, Plain, LogLevel.Info, _fallback); + } + + private static string Text(MemoryStream stream) + { + return Encoding.UTF8.GetString(stream.ToArray()).ReplaceLineEndings("\n"); + } + + private static string Line(string format, double seconds = 0) + { + return LoggerTextFormatter.Format(new LogFormat(format), false, LogLevel.Info, "{hi}", "File", + Stub.Engine(seconds)); + } + + // ---- The line + + [Fact] + public void Formatter_FillsThePlaceholders() + { + Line("{2} {3} {4} {5} {6} {7} {10}", 3723.5).Should() + .Be($"Engine 01:02:03.500 Info Main File {Environment.CurrentManagedThreadId} {{hi}}"); + } + + [Fact] + public void Formatter_WritesDateAndTime() + { + Regex.IsMatch(Line("{0} {1}"), @"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3}$").Should().BeTrue(); + } + + [Fact] + public void ACaller_IsFoundThroughTheRouterAndTheExtensions() + { + var output = new StringWriter(); + var catalog = new LoggerCatalog(); + catalog.Add(new ConsoleLogger(Stub.Engine(), output, false, Caller)); + + new Logger(catalog).Info("m"); + + output.ToString().Trim().Should() + .Be($"{typeof(SinkTests).FullName}.{nameof(ACaller_IsFoundThroughTheRouterAndTheExtensions)}"); + } + + [Fact] + public async Task ACaller_InAnAsyncMethod_IsTheMethodAsWritten() + { + await Task.Yield(); + var output = new StringWriter(); + new ConsoleLogger(Stub.Engine(), output, false, Caller).Info("m"); + + output.ToString().Trim().Should() + .Be($"{typeof(SinkTests).FullName}.{nameof(ACaller_InAnAsyncMethod_IsTheMethodAsWritten)}"); + } + + [Fact] + public void ACaller_InALambda_IsTheMethodAroundIt() + { + var output = new StringWriter(); + var logger = new ConsoleLogger(Stub.Engine(), output, false, Caller); + Action log = () => logger.Info("m"); + log(); + + output.ToString().Trim().Should() + .Be($"{typeof(SinkTests).FullName}.{nameof(ACaller_InALambda_IsTheMethodAroundIt)}"); + } + + [Fact] + public void TheDefaultFormats_WorkAtEveryLevel() + { + foreach (LogLevel level in Enum.GetValues()) + foreach (bool colorized in new[] { false, true }) + LoggerTextFormatter + .Format(LoggerFormat.Default.ForLevel(level), colorized, level, "message", "File", Stub.Engine()) + .Should().Contain("message").And.Contain(level.ToString()); + } + + [Fact] + public void AnUnknownLevel_HasNoFormat() + { + FluentActions.Invoking(() => LoggerFormat.Default.ForLevel((LogLevel)99)).Should().Throw(); + } + + // ---- The console + + [Theory] + [InlineData(null, "Info|m")] + [InlineData(false, "Info|m")] + [InlineData(true, "\e[1mInfo|m\e[0m")] + public void Console_ColorsAnOutputOfItsOwn_OnlyWhenAsked(bool? colorized, string expected) + { + var output = new StringWriter(); + new ConsoleLogger(Stub.Engine(), output, colorized, Plain).Info("m"); + output.ToString().Trim().Should().Be(expected); + } + + [Fact] + public void AColorizedLine_WithoutAColorizedFormat_IsPlain() + { + var output = new StringWriter(); + new ConsoleLogger(Stub.Engine(), output, true, Same(new LogFormat("{10}"))).Info("m"); + output.ToString().Trim().Should().Be("m"); + } + + [Fact] + public void Console_WritesLinesWhole_FromManyThreads() + { + var output = new StringWriter(); + var logger = new ConsoleLogger(Stub.Engine(), output, false, Plain); + + Parallel.For(0, 500, index => logger.Info(index.ToString())); + + output.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries) + .Should().BeEquivalentTo(Enumerable.Range(0, 500).Select(index => $"Info|{index}")); + } + + [Fact] + public void Sinks_NeedAnEngineAndAStream() + { + FluentActions.Invoking(() => new ConsoleLogger(null!)).Should().Throw(); + FluentActions.Invoking(() => new FileLogger(null!, () => null)).Should().Throw(); + FluentActions.Invoking(() => new FileLogger(Stub.Engine(), null!)).Should().Throw(); + } + + // ---- The file + + [Fact] + public void File_OpensOnce_AtTheFirstMessageItTakes() + { + var stream = new MemoryStream(); + int opened = 0; + FileLogger file = File(() => + { + opened++; + return stream; + }); + + file.Debug("below the level"); + opened.Should().Be(0); + + file.Info("a"); + file.Error("b"); + file.LogWithoutFormat("raw"); + file.Stop(); + + opened.Should().Be(1); + Text(stream).Should().Be("Info|a\nError|b\nraw\n"); + } + + [Fact] + public void File_WithoutAutoFlush_FlushesErrors() + { + var stream = new MemoryStream(); + FileLogger file = File(() => stream, false); + + file.Info("a"); + Text(stream).Should().BeEmpty(); + file.Error("b"); + Text(stream).Should().Be("Info|a\nError|b\n"); + file.Dispose(); + } + + [Fact] + public void File_KeepsTheLines_TillThereIsSomewhereToWrite() + { + var stream = new MemoryStream(); + bool ready = false; + FileLogger file = File(() => ready ? stream : null); + + file.Info("a"); + file.LogWithoutFormat("b"); + ready = true; + file.Info("c"); + + Text(stream).Should().Be("Info|a\nb\nInfo|c\n"); + } + + [Fact] + public void File_ThatCouldBeOpenedOnlyAtTheEnd_IsWrittenThen() + { + var stream = new MemoryStream(); + bool ready = false; + FileLogger file = File(() => ready ? stream : null); + + file.Info("a"); + ready = true; + file.Stop(); + + Text(stream).Should().Be("Info|a\n"); + _fallback.ToString().Should().BeEmpty(); + } + + [Fact] + public void File_WithNowhereToWrite_SaysHowMuchWasLost() + { + FileLogger file = File(() => null); + file.Info("a"); + file.Info("b"); + file.Stop(); + + _fallback.ToString().Should().Contain("2 message(s) were not written"); + } + + [Fact] + public void File_KeepsTheLatestLines_AndSaysHowManyItDropped() + { + var stream = new MemoryStream(); + bool ready = false; + FileLogger file = File(() => ready ? stream : null); + + for (int index = 0; index < FileLogger.MaxPending + 3; index++) file.Info(index.ToString()); + ready = true; + file.Info("last"); + + string[] lines = Text(stream).Split('\n', StringSplitOptions.RemoveEmptyEntries); + lines.Should().HaveCount(FileLogger.MaxPending + 2); + lines[0].Should().Contain("3 message(s) were dropped"); + lines[1].Should().Be("Info|3"); + lines[^1].Should().Be("Info|last"); + } + + [Fact] + public void File_ThatFails_IsToldOnce_AndTriesAgainWhenStarted() + { + var stream = new MemoryStream(); + bool broken = true; + FileLogger file = File(() => broken ? throw new IOException("no disk") : stream); + + file.Info("a"); + file.Info("b"); + _fallback.ToString().Split("no disk").Should().HaveCount(2); + + broken = false; + file.Info("still given up"); + file.Start(); + file.Info("c"); + + Text(stream).Should().Be("Info|c\n"); + } + + [Fact] + public void AStreamThatFailsToWriteAndToClose_BreaksNothing() + { + FileLogger file = File(() => new BrokenStream()); + + file.Invoking(it => it.Info("a")).Should().NotThrow(); + file.Invoking(it => it.Stop()).Should().NotThrow(); + _fallback.ToString().Should().Contain("The file logger failed"); + } + + [Fact] + public void File_StartsAgainAfterAStop() + { + List streams = new(); + FileLogger file = File(() => + { + streams.Add(new MemoryStream()); + return streams[^1]; + }); + + file.Info("a"); + file.Stop(); + file.Info("lost"); + file.Start(); + file.Info("b"); + file.Dispose(); + file.Dispose(); + + streams.Select(Text).Should().Equal("Info|a\n", "Info|b\n"); + } + + [Fact] + public void File_WritesUtf8WithoutAMark() + { + var stream = new MemoryStream(); + File(() => stream).Info("звезда"); + stream.ToArray().Should().StartWith(Encoding.UTF8.GetBytes("Info|звезда")); + } + + [Fact] + public void File_WritesLinesWhole_FromManyThreads() + { + var stream = new MemoryStream(); + FileLogger file = File(() => stream); + + Parallel.For(0, 500, index => file.Info(index.ToString())); + + Text(stream).Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Should().BeEquivalentTo(Enumerable.Range(0, 500).Select(index => $"Info|{index}")); + } + + private sealed class BrokenStream + : MemoryStream + { + public override void Write(ReadOnlySpan buffer) + { + throw new IOException("broken"); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new IOException("broken"); + } + + public override void Flush() + { + throw new IOException("broken"); + } + } +} diff --git a/tests/Stellar.LoggingSystem.Tests/TestSupport.cs b/tests/Stellar.LoggingSystem.Tests/TestSupport.cs new file mode 100644 index 0000000..a6a3f26 --- /dev/null +++ b/tests/Stellar.LoggingSystem.Tests/TestSupport.cs @@ -0,0 +1,90 @@ +using System.Reflection; + +using Stellar.Kernel.Lifecycle; +using Stellar.Kernel.LoggingSystem; + +namespace Stellar.LoggingSystem.Tests; + +/// +/// Remembers what it was given, or fails. +/// +internal sealed class RecordingLogger(string name, LogLevel minimumLevel = LogLevel.Debug, bool fails = false) + : LoggerBase(name, minimumLevel: minimumLevel) +{ + private readonly List _lines = []; + + public Action? OnWrite { get; init; } + + public string[] Lines + { + get + { + lock (_lines) + { + return _lines.ToArray(); + } + } + } + + protected override void Write(string message, LogLevel? level) + { + if (fails) throw new InvalidOperationException("broken"); + lock (_lines) + { + _lines.Add($"{level}:{message}"); + } + + OnWrite?.Invoke(); + } +} + +/// +/// An implementation of a contract that answers with a delegate: the engine is made of contracts only. +/// +public class Stub + : DispatchProxy +{ + private Func _answer = (_, _) => null; + + public static T Of(Func answer) + where T : class + { + T proxy = Create(); + ((Stub)(object)proxy)._answer = answer; + return proxy; + } + + protected override object? Invoke(MethodInfo? method, object?[]? args) + { + return _answer(method!.Name, args ?? []); + } + + /// An engine with a name and a clock. + public static IEngineInstance Engine(double seconds = 0) + { + var clock = Of((member, _) => member == "get_Name" ? "Engine" : seconds); + var time = Of((_, _) => clock); + return Of((member, _) => member == "get_Time" ? time : "Main"); + } +} + +/// +/// A folder of its own, gone with the test. +/// +internal sealed class TempFolder + : IDisposable +{ + public string Path { get; } = + System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Stellar.LoggingSystem.Tests", + Guid.NewGuid().ToString("N")); + + public TempFolder() + { + Directory.CreateDirectory(Path); + } + + public void Dispose() + { + Directory.Delete(Path, true); + } +} From 2ceefdcf2c45dd3f948e392b1411a45c80fc1820 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Wed, 25 Nov 2026 19:26:15 +0700 Subject: [PATCH 4/9] [SLS] grant the pull request guard its permissions --- .github/workflows/restrict-master-prs.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/restrict-master-prs.yml b/.github/workflows/restrict-master-prs.yml index b07b852..665d43f 100644 --- a/.github/workflows/restrict-master-prs.yml +++ b/.github/workflows/restrict-master-prs.yml @@ -4,6 +4,11 @@ on: pull_request_target: types: [opened, reopened] +permissions: + contents: read + pull-requests: write + issues: write + jobs: restrict: uses: QuantumDevTeam/.github/.github/workflows/restrict-master-prs.yml@master From c8e2e7bcdebfe94145196ac94526c5c1e4d9a8b5 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Wed, 25 Nov 2026 19:41:27 +0700 Subject: [PATCH 5/9] [SLS] check the marks with the workflow of the core --- .github/workflows/marks.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .github/workflows/marks.yml diff --git a/.github/workflows/marks.yml b/.github/workflows/marks.yml new file mode 100644 index 0000000..ce1e719 --- /dev/null +++ b/.github/workflows/marks.yml @@ -0,0 +1,15 @@ +name: Marks + +# The marks in the comments of the code, checked by the workflow of the core (Docs/Engine/Marks.md there). + +on: + push: + branches: [develop, master] + pull_request: + +permissions: + contents: read + +jobs: + marks: + uses: QuantumDevTeam/StellarEngine-Core/.github/workflows/marks.yml@develop From 9a1eec82a47bf46cd224470ba2ae2da31525ac7a Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Wed, 25 Nov 2026 20:25:32 +0700 Subject: [PATCH 6/9] [SCRIPTS] [SDK] build and test on every pull request --- .github/workflows/tests.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .github/workflows/tests.yml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..c9fa495 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,15 @@ +name: Tests + +# The module built and tested on the core, by the workflow of the core. + +on: + push: + branches: [develop, master] + pull_request: + +permissions: + contents: read + +jobs: + tests: + uses: QuantumDevTeam/StellarEngine-Core/.github/workflows/tests.yml@develop From a74c5bc25ea167c062e172d3ea9e9ef868f4de91 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Thu, 26 Nov 2026 02:44:45 +0700 Subject: [PATCH 7/9] [SLS] versioning --- Stellar.LoggingSystem.stellar.module | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stellar.LoggingSystem.stellar.module b/Stellar.LoggingSystem.stellar.module index 18d24a3..0ba8b1f 100644 --- a/Stellar.LoggingSystem.stellar.module +++ b/Stellar.LoggingSystem.stellar.module @@ -1,7 +1,7 @@ { "$schema": "https://quantumdevteam.github.io/StellarEngine-Core/schemas/stellar.module.schema.json", "Id": "Stellar.LoggingSystem", - "Version": "0.9.0", + "Version": "0.11.0", "Level": "CoreModule", "Description": "logging system of the engine", "Dependencies": [] From e66afc2222edda5f4f6c00b446ac99ee710a4b83 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Thu, 26 Nov 2026 04:34:32 +0700 Subject: [PATCH 8/9] [SCRIPTS] [SDK] run the tests by hand, take Stellar.Sdk 0.4.2 --- .github/workflows/tests.yml | 5 ++++- global.json | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c9fa495..73cfede 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,11 +1,14 @@ name: Tests # The module built and tested on the core, by the workflow of the core. +# By itself only on the way into master; on any other branch by hand (Run workflow). on: + workflow_dispatch: push: - branches: [develop, master] + branches: [master] pull_request: + branches: [master] permissions: contents: read diff --git a/global.json b/global.json index f4183af..6d9e576 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "Stellar.Sdk": "0.4.1" + "Stellar.Sdk": "0.4.2" } } From c91bb9234c259190a2c41bacdf15ef21c3a3f880 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Sat, 28 Nov 2026 21:01:14 +0200 Subject: [PATCH 9/9] [DOCS] publish the documentation to the docs site --- .github/workflows/docs.yml | 108 ++++++++++++++++++++++++++++++------- Docs/index.md | 5 +- Docs/toc.yml | 7 +-- Template/public/main.css | 67 ----------------------- docfx.json | 30 +---------- prometheus.json | 15 ++++++ 6 files changed, 111 insertions(+), 121 deletions(-) delete mode 100644 Template/public/main.css create mode 100644 prometheus.json diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index ae87db5..55300e0 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,23 +1,27 @@ name: Docs -# Builds the documentation site of the module from Docs/ with DocFX (docfx.json) and publishes it to GitHub Pages. -# Pull requests and manual runs on other branches only build; the site is deployed from master only. -# Repository setting required once: Settings -> Pages -> Source = "GitHub Actions". +# Publishes the documentation of this repository to GitHub Pages for the Prometheus site (the team site). +# GitHub Pages is only the storage of the site: static files (the installer, the schemas), the documentation as data +# (bundle/) and a small embed that redirects to the site when the site is up. +# +# This file is a thin wrapper and does not need updates: the steps (ci.py, the bundle builder, the embed) are +# downloaded from the site on every run (/docs-kit.zip), so they are always the same version as the site. +# What to build is described by the repository itself in prometheus.json (format prometheus-repo/1, see the DOCS +# page of the site); without it: Docs/ and the API of the projects in docfx.json. +# If the site is down, the static files and a page that leads to the site are published; the next run fixes the rest. +# +# Repository settings: +# Settings -> Pages -> Source = "GitHub Actions" (once) +# Variables (optional): PROMETHEUS_SITE (https://notagood.org by default), +# PROMETHEUS_PROJECT, PROMETHEUS_TITLE (override prometheus.json) +# Secrets (optional): PROMETHEUS_SYNC_KEY an API key of the site with the "sync" scope: the site learns about +# the new build at once instead of on its next check +# Pull requests and manual runs on other branches only build; Pages is deployed from master only. on: push: branches: [master] - paths: - - 'Docs/**' - - 'README.md' - - 'docfx.json' - - '.github/workflows/docs.yml' pull_request: - paths: - - 'Docs/**' - - 'README.md' - - 'docfx.json' - - '.github/workflows/docs.yml' workflow_dispatch: permissions: @@ -31,39 +35,95 @@ env: DOCFX_VERSION: '2.81.0' DOTNET_NOLOGO: 'true' DOTNET_CLI_TELEMETRY_OPTOUT: 'true' + PROMETHEUS_SITE: ${{ vars.PROMETHEUS_SITE || 'https://notagood.org' }} + PROMETHEUS_PROJECT: ${{ vars.PROMETHEUS_PROJECT }} + PROMETHEUS_TITLE: ${{ vars.PROMETHEUS_TITLE }} + OUT: artifacts/pages jobs: build: - name: Build site - runs-on: ubuntu-latest + name: Build + runs-on: ubuntu-latest # pwsh, python3 and bash are there: "prepare" scripts may use any of them steps: - name: Checkout uses: actions/checkout@v5 - # The global.json of a module pins Stellar.Sdk, not the .NET SDK - name: Setup .NET + if: hashFiles('global.json') != '' + uses: actions/setup-dotnet@v5 + with: + global-json-file: global.json + + - name: Setup .NET (no global.json) + if: hashFiles('global.json') == '' uses: actions/setup-dotnet@v5 with: dotnet-version: '9.0.x' + # Installed outside the checkout so a repository NuGet.config (a local feed) is not involved. - name: Install DocFX working-directory: ${{ runner.temp }} run: dotnet tool install docfx --version "$DOCFX_VERSION" --tool-path "$RUNNER_TEMP/docfx" - - name: Build documentation - run: '"$RUNNER_TEMP/docfx/docfx" build docfx.json --warningsAsErrors' + - name: Prometheus + id: prometheus + continue-on-error: true + run: | + set -euo pipefail + # NuGet wants the local feed folder of an installation to exist, even empty + mkdir -p packages + curl -fsSL --retry 2 "$PROMETHEUS_SITE/docs-kit.zip" -o "$RUNNER_TEMP/kit.zip" + unzip -q -o "$RUNNER_TEMP/kit.zip" -d "$RUNNER_TEMP/kit" + python3 -m pip install --quiet pyyaml + python3 "$RUNNER_TEMP/kit/ci.py" --out "$OUT" --docfx "$RUNNER_TEMP/docfx/docfx" + + # The site is down or the build failed: publish the static files and a page that leads to the site. + # Self-contained on purpose (no kit): the installer and the schemas keep their addresses whatever happens. + - name: Fallback + if: steps.prometheus.outcome == 'failure' + run: | + echo "::warning title=Prometheus::The documentation was not built (is $PROMETHEUS_SITE up?); publishing the static files only" + mkdir -p "$OUT" && touch "$OUT/.nojekyll" + python3 - <<'PY' + import glob, html, json, os, re, shutil + out = os.environ["OUT"] + cfg = json.load(open("prometheus.json", encoding="utf-8-sig")) if os.path.isfile("prometheus.json") else {} + static = cfg.get("static") or next((a.get("docfx") if isinstance(a, dict) else a for a in cfg.get("api") or []), None) \ + or ("docfx.json" if os.path.isfile("docfx.json") else None) + for config in ([static] if isinstance(static, str) else static or []): + if not os.path.isfile(config): + continue + base = os.path.dirname(os.path.abspath(config)) + for r in json.load(open(config, encoding="utf-8-sig")).get("build", {}).get("resource", []): + src, dest = os.path.join(base, r.get("src", "")), os.path.join(out, r.get("dest", "")) + for pattern in r.get("files", []): + for f in glob.glob(os.path.join(src, pattern), recursive=True): + if os.path.isfile(f): + t = os.path.join(dest, os.path.relpath(f, src)) + os.makedirs(os.path.dirname(t), exist_ok=True) + shutil.copy2(f, t) + repo = os.environ.get("GITHUB_REPOSITORY", "").rsplit("/", 1)[-1] + project = os.environ.get("PROMETHEUS_PROJECT") or cfg.get("project") or re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-") + url = html.escape(f"{os.environ['PROMETHEUS_SITE'].rstrip('/')}/docs/{project}") + title = html.escape(os.environ.get("PROMETHEUS_TITLE") or cfg.get("title") or repo) + with open(os.path.join(out, "index.html"), "w", encoding="utf-8") as f: + f.write(f'{title}' + f'' + f'

{title} documentation

') + PY - name: Upload Pages artifact if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master' uses: actions/upload-pages-artifact@v5 with: - path: artifacts/docs/site + path: ${{ env.OUT }} deploy: name: Deploy to GitHub Pages if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master' needs: build runs-on: ubuntu-latest + # Never cancel a deployment that is already running. concurrency: group: pages cancel-in-progress: false @@ -77,3 +137,13 @@ jobs: - name: Deploy id: deployment uses: actions/deploy-pages@v5 + + # The site would notice the new bundle on its next check anyway; this makes it immediate. + - name: Nudge the site + continue-on-error: true + env: + KEY: ${{ secrets.PROMETHEUS_SYNC_KEY }} + run: | + if [ -z "$KEY" ]; then echo "::notice::PROMETHEUS_SYNC_KEY is not set: the site picks the docs up on its next check"; exit 0; fi + sleep 30 # Pages needs a moment to serve the new files + curl -fsS -X POST -H "Authorization: Bearer $KEY" "$PROMETHEUS_SITE/api/v1/sync" diff --git a/Docs/index.md b/Docs/index.md index a5a49b3..192bf14 100644 --- a/Docs/index.md +++ b/Docs/index.md @@ -2,8 +2,7 @@ logging system of the engine -A `CoreModule` module of [StellarEngine](https://quantumdevteam.github.io/StellarEngine-Mono/). Its site is https://quantumdevteam.github.io/Stellar.LoggingSystem/, built from the Markdown -files of `Docs/` with DocFX; the whole engine, with every module, is on the [site of the engine](https://quantumdevteam.github.io/StellarEngine-Mono/). +A `CoreModule` module of [StellarEngine](prometheus:stellar-engine). Its documentation is on the [docs site](prometheus:stellar-logging), built from the Markdown files of `Docs/`; the whole engine, with every module, is on the [site of the engine](prometheus:stellar-engine). ## Using it @@ -37,4 +36,4 @@ module starts and take it out when it stops. The catalog never disposes what it stellar modules build Stellar.LoggingSystem --tests ``` -See [the README](../README.md) for the layout of the module. +See [the README](https://github.com/QuantumDevTeam/Stellar.LoggingSystem#readme) for the layout of the module. diff --git a/Docs/toc.yml b/Docs/toc.yml index 89c53bd..a23cb58 100644 --- a/Docs/toc.yml +++ b/Docs/toc.yml @@ -1,7 +1,8 @@ -# Navigation of the documentation site of the module (DocFX). Paths are relative to this file. + +# Navigation of the documentation of the module (the bundle of the site). Paths are relative to this file. - name: Home href: index.md - name: README - href: ../README.md + href: https://github.com/QuantumDevTeam/Stellar.LoggingSystem#readme - name: StellarEngine - href: https://quantumdevteam.github.io/StellarEngine-Mono/ + href: prometheus:stellar-engine diff --git a/Template/public/main.css b/Template/public/main.css deleted file mode 100644 index 3e66746..0000000 --- a/Template/public/main.css +++ /dev/null @@ -1,67 +0,0 @@ -/* - The theme of the StellarEngine sites, over the "modern" template of DocFX: the sites of the core and of the - orchestra list this folder last in "template", the template of a module carries a copy. -*/ - -:root { - --stellar-accent: #8a63ff; - --stellar-accent-strong: #6d3df5; -} - -[data-bs-theme="dark"] { - --stellar-accent: #a98bff; - --stellar-accent-strong: #c4b0ff; -} - -/* The brand: the icon and the name side by side, a fixed size, room before the menu */ -.navbar-brand { - display: inline-flex; - align-items: center; - gap: 0.55rem; - margin-right: 1.75rem; - font-weight: 600; - letter-spacing: 0.01em; - white-space: nowrap; -} - -/* The icon is wide (Shared/Branding/stellar_icon.svg: the emblem without the name): fixed height, its own width */ -.navbar-brand #logo { - height: 34px; - width: auto; - max-width: 84px; - flex: none; - object-fit: contain; -} - -/* Entries of the menu stay on one line */ -.navbar-nav .nav-link { - white-space: nowrap; -} - -/* A thin line under the header instead of a block */ -header .navbar { - border-bottom: 1px solid var(--bs-border-color-translucent); -} - -/* Links and the active entry in the accent of the logo */ -article a, -.toc a.active, -.navbar-nav .nav-link.active { - color: var(--stellar-accent); -} - -article a:hover { - color: var(--stellar-accent-strong); -} - -/* Code blocks of one command (the installer) read better a little larger */ -article pre > code { - font-size: 0.92em; -} - -/* Wide tables of the docs scroll inside the page instead of pushing it */ -article table { - display: block; - max-width: 100%; - overflow-x: auto; -} diff --git a/docfx.json b/docfx.json index 7862755..d651cee 100644 --- a/docfx.json +++ b/docfx.json @@ -1,40 +1,12 @@ { "$schema": "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json", "build": { - "content": [ - { - "src": "Docs", - "files": [ - "**/*.md", - "toc.yml" - ] - }, - { - "files": [ - "README.md" - ] - } - ], "resource": [ { "files": [ "Branding/Logo.svg" ] } - ], - "output": "artifacts/docs/site", - "template": [ - "default", - "modern", - "Template" - ], - "globalMetadata": { - "_appName": "Stellar.LoggingSystem", - "_appTitle": "Stellar.LoggingSystem", - "_appFooter": "Stellar.LoggingSystem, a module of StellarEngine", - "_appLogoPath": "Branding/Logo.svg", - "_appFaviconPath": "Branding/Logo.svg", - "_enableSearch": true - } + ] } } diff --git a/prometheus.json b/prometheus.json new file mode 100644 index 0000000..a5d4251 --- /dev/null +++ b/prometheus.json @@ -0,0 +1,15 @@ +{ + "format": "prometheus-repo/1", + "project": "stellar-logging", + "title": "Stellar.LoggingSystem", + "version": { + "file": "Stellar.LoggingSystem.stellar.module", + "regex": "\"Version\"\\s*:\\s*\"([^\"]+)\"" + }, + "docs": [ + { + "path": "Docs" + } + ], + "static": "docfx.json" +}