PrimaLogger 2.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package PrimaLogger --version 2.0.0
                    
NuGet\Install-Package PrimaLogger -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PrimaLogger" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="PrimaLogger" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="PrimaLogger" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add PrimaLogger --version 2.0.0
                    
#r "nuget: PrimaLogger, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package PrimaLogger@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=PrimaLogger&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=PrimaLogger&version=2.0.0
                    
Install as a Cake Tool

PrimaLogger v2.0

Упрощенная обёртка над Serilog с конфигурацией через appsettings.json. Поддержка Console, File и Elasticsearch с автоматическим определением совместимости.

🚀 Быстрый старт

Настройка в Program.cs

using PrimaLogger.Configuration;

var builder = Host.CreateApplicationBuilder(args);

// Добавляем PrimaLogger
builder.Services.AddPrimaLogger(builder.Configuration);

var host = builder.Build();
host.Run();

Конфигурация в appsettings.json

{
  "Logging": {
    "PrimaLogger": {
      "ApplicationName": "MyApp",
      "Console": {
        "Enabled": true,
        "MinimumLevel": "Information"
      },
      "File": {
        "Path": "logs/app-.log",
        "MinimumLevel": "Debug"
      }
    }
  }
}

Использование в коде

public class UserController : ControllerBase
{
    private readonly ILogger<UserController> _logger;
    
    public UserController(ILogger<UserController> logger)
    {
        _logger = logger;
    }
    
    public IActionResult Login(string userId)
    {
        _logger.LogInformation("User {UserId} attempting login", userId);
        return Ok();
    }
}

Полная конфигурация

{
  "Logging": {
    "PrimaLogger": {
      "ApplicationName": "MyWebApp",
      "CustomProperties": {
        "Environment": "Production",
        "Version": "1.0.0",
        "ServiceName": "api-service"
      },
      "Console": {
        "Enabled": true,
        "MinimumLevel": "Information",
        "OutputTemplate": "{Timestamp:HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
      },
      "File": {
        "Path": "logs/app-.log",
        "MinimumLevel": "Debug",
        "OutputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{ThreadId}] {Message:lj}{NewLine}{Exception}",
        "RollingInterval": "Day",
        "FileSizeLimitBytes": 104857600,
        "RetainedFileCountLimit": 31,
        "RollOnFileSizeLimit": true,
        "Shared": false,
        "Encoding": "UTF-8"
      },
      "ErrorFile": {
        "Path": "logs/errors-.log",
        "MinimumLevel": "Error",
        "RollingInterval": "Day",
        "RetainedFileCountLimit": 90
      },
      "Elasticsearch": {
        "MinimumLevel": "Information",
        "Options": {
          "Nodes": [
            "https://elasticsearch-01.domain.com:9200",
            "https://elasticsearch-02.domain.com:9200"
          ],
          "DataStreamName": "logs-mywebapp-production",
          "BootstrapMethod": "Silent",
          "ApiKey": "",
          "BufferOptions": {
            "ConcurrentConsumers": 4,
            "InboundBufferMaxSize": 500000,
            "OutboundBufferMaxSize": 5000
          }
        }
      }
    }
  }
}

Автоматическая совместимость с Elasticsearch

  • Elasticsearch >= 7.9: Современный режим с Data Streams
  • Elasticsearch 7.3-7.8: Legacy режим с индексами
  • Elasticsearch < 7.3 или недоступен: Автоматическое отключение с предупреждением

Уровни логирования

Уровень Назначение Использование
Verbose Максимальная детализация Глубокая отладка
Debug Отладочная информация Разработка
Information Общая информация Нормальная работа
Warning Предупреждения Потенциальные проблемы
Error Ошибки Проблемы в работе
Fatal Критические ошибки Аварийное завершение

Шаблоны вывода (Output Templates)

Консоль - простой

"[{Level:u3}] {Message:lj}{NewLine}{Exception}"

Результат: [INF] User logged in successfully

Файл - с контекстом

"{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}"

Результат: 2024-01-15 14:30:25.123 [INF] [1] MyApp.Controllers.UserController: User logged in successfully

Основные переменные

  • {Timestamp} - время события
  • {Level} - уровень логирования
  • {Message} - текст сообщения
  • {ThreadId} - ID потока
  • {SourceContext} - имя класса/логгера
  • {Application} - название приложения
  • {Environment} - окружение
  • {Exception} - информация об исключении

Ротация файлов

По времени

{
  "RollingInterval": "Day",        // Hour, Day, Month, Year
  "RetainedFileCountLimit": 30     // Хранить 30 файлов
}

По размеру

{
  "FileSizeLimitBytes": 104857600,  // 100MB
  "RollOnFileSizeLimit": true,
  "RetainedFileCountLimit": 10
}

Elasticsearch настройки

Производительность

{
  "BufferOptions": {
    "ConcurrentConsumers": 4,        // 4 потока отправки
    "InboundBufferMaxSize": 500000,  // Буфер входящих
    "OutboundBufferMaxSize": 5000    // Размер пакета
  }
}

Аутентификация

{
  "ApiKey": "your-api-key",          // Рекомендуется
  "Username": "user",                // Альтернатива
  "Password": "pass"
}

🔍 Значения по умолчанию

Параметр Значение по умолчанию
ApplicationName "webapp"
Console.MinimumLevel Information
File.MinimumLevel Information
File.RollingInterval Day
File.FileSizeLimitBytes 100MB
File.RetainedFileCountLimit 31
Elasticsearch.BootstrapMethod Failure
BufferOptions.OutboundBufferMaxSize 1000

Синки отключены по умолчанию

Если секция отсутствует в конфигурации, соответствующий sink отключен:

{
  "Logging": {
    "PrimaLogger": {
      "ApplicationName": "MyApp"
      // Console, File, ErrorFile, Elasticsearch - все отключены
    }
  }
}

Глобальный минимальный уровень

Автоматически выбирается самый низкий уровень из всех включенных sink'ов.

Elasticsearch проверка при старте

При запуске приложения выполняется проверка доступности и версии Elasticsearch (таймаут 5 секунд).

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.1.0 237 7/26/2025
2.0.6 370 7/25/2025
2.0.5 380 7/25/2025
2.0.4 377 7/25/2025
2.0.3 432 7/24/2025
2.0.2 116 7/17/2025
2.0.1 109 7/17/2025
2.0.0 115 7/17/2025
1.1.0 111 7/16/2025
1.0.9 112 7/16/2025
1.0.8 113 7/16/2025
1.0.7 116 7/16/2025
1.0.6 109 7/16/2025
1.0.5 112 7/16/2025
1.0.4 115 7/16/2025
1.0.3 114 7/16/2025
1.0.2 115 7/15/2025
1.0.1 114 7/15/2025
1.0.0 113 7/15/2025

v2.0.0: Упрощенная версия
           - Убраны builder API и preset'ы
           - Конфигурация только через appsettings.json
           - Автоматический fallback для Elasticsearch
           - Упрощенная архитектура