Это быстрый старт без погружения в теорию о том, как логировать сообщения в OpenSearch
Установка зависимостей
NLog.Targets.OpenSearch
NLog.Web.AspNetCore
Serilog
Serilog.AspNetCore
Serilog.Sinks.Console
Serilog.Sinks.Invoitrade.OpenSearch
Нужные зависимости Важное замечание: я установил именно Serilog.Sinks.Invoitrade.OpenSearch, а не Serilog.Sinks.OpenSearch, так на момент написания статьи последний имеет ошибки при запуске
Запуск Docker образов с OpenSearch.
Cоздаём файлик docker-compose.yml с следующим кодом
--- services: opensearch-node1: image: opensearchproject/opensearch:latest container_name: opensearch-node1 environment: - cluster.name=opensearch-cluster - node.name=opensearch-node1 - discovery.seed_hosts=opensearch-node1 - cluster.initial_cluster_manager_nodes=opensearch-node1 - bootstrap.memory_lock=true # along with the memlock settings below, disables swapping - OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m # minimum and maximum Java heap size, recommend setting both to 50% of system RAM - OPENSEARCH_INITIAL_ADMIN_PASSWORD=shaydullinDA123@superMyPassword # Sets the demo admin user password when using demo configuration, required for OpenSearch 2.12 and higher ulimits: memlock: soft: -1 hard: -1 nofile: soft: 65536 # maximum number of open files for the OpenSearch user, set to at least 65536 on modern systems hard: 65536 volumes: - opensearch-data1:/usr/share/opensearch/data ports: - 9200:9200 - 9600:9600 # required for Performance Analyzer networks: - opensearch-net opensearch-dashboards: image: opensearchproject/opensearch-dashboards:latest container_name: opensearch-dashboards ports: - 5601:5601 expose: - '5601' environment: OPENSEARCH_HOSTS: '["https://opensearch-node1:9200"]' networks: - opensearch-net volumes: opensearch-data1: networks: opensearch-net:
Запускаем его с помощью команды docker-compose up
Теперь перейдем к коду
using System.Net; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Events; using Serilog.Sinks.OpenSearch; using AutoRegisterTemplateVersion = Serilog.Sinks.OpenSearch.AutoRegisterTemplateVersion; using CertificateValidations = OpenSearch.Net.CertificateValidations; var builder = WebApplication.CreateBuilder(args); builder.Logging.ClearProviders(); Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg)); ServicePointManager.ServerCertificateValidationCallback = (o, certificate, chain, errors) => true; ServicePointManager.ServerCertificateValidationCallback = CertificateValidations.AllowAll; var logger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.OpenSearch(new OpenSearchSinkOptions(new Uri("https://localhost:9200")) { AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6, MinimumLogEventLevel = LogEventLevel.Verbose, TypeName = "_doc", InlineFields = false, ModifyConnectionSettings = x => x.BasicAuthentication("admin", "shaydullinDA123@superMyPassword") .ServerCertificateValidationCallback(CertificateValidations.AllowAll) .ServerCertificateValidationCallback((o, certificate, chain, errors) => true), IndexFormat = "my-index-{0:yyyy.MM.dd}", }) .CreateLogger(); builder.Logging.ClearProviders(); builder.Logging.AddSerilog(logger); var app = builder.Build(); app.Logger.LogInformation("starting up"); app.Run();
31 строчка кода:
x.BasicAuthentication("admin", "shaydullinDA123@superMyPassword")
Обратим внимание на 31 строчку: пароль у нас берется тот, который мы сами поставили в docker-compose (13 строчка). Если будете менять, ставьте такой же сложный, чтобы все точно работало
docker-compose.yaml (13 строчка где мы ставим пароль):
OPENSEARCH_INITIAL_ADMIN_PASSWORD=shaydullinDA123@superMyPassword
Проверим логирование через OpenSearch Dashboard
Заходим по http://localhost:5601
Выбираем Dashboards Management
Index Patterns -> Create Index
Создаем индекс паттерн. В нашем случае это my-index-*, так как после звездочки идет дата и время создания документа. Это задается в 34 строчке нашего кода:
IndexFormat = "my-index-{0:yyyy.MM.dd}"
Теперь переходим в discover
Вводим наш pattern и все - мы можем просматривать все логи нашего приложения