Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Галкин Александр, Орлов Никита #20

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/scripts/run-tests-core.sh
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ declare -i was_retried=0

# retry for max 10s (5*2s)
for _ in $(seq 1 5); do
if echo 'dockerelk' | nc -q0 "$ip_ls" 50000; then
if echo 'dockerelk' | nc -q0 "$ip_ls" 49999; then
break
fi

Expand Down
3 changes: 2 additions & 1 deletion Pages/Index.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public IndexModel(ILogger<IndexModel> logger)

public void OnGet()
{

var myName = "..."; // ваше имя
_logger.LogInformation("Sample log. My name is {MyName}", myName);
}
}
73 changes: 57 additions & 16 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,66 @@
var builder = WebApplication.CreateBuilder(args);
using Elastic.Channels;
using Elastic.Ingest.Elasticsearch;
using Elastic.Ingest.Elasticsearch.DataStreams;
using Elastic.Serilog.Sinks;
using Elastic.Transport;
using Serilog;

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Elasticsearch([new Uri("http://localhost:9200")], opts =>
{
opts.DataStream = new DataStreamName("logs", "telemetry-logging", "demo");
opts.BootstrapMethod = BootstrapMethod.Failure;
opts.ConfigureChannel = channelOpts =>
{
channelOpts.BufferOptions = new BufferOptions
{
ExportMaxConcurrency = 10
};
};
}, transport =>
{
transport.Authentication(new BasicAuthentication("elastic", "changeme")); // Basic Auth
})
.Enrich.WithProperty("Environment", builder.Environment.EnvironmentName)
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
try
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// Add services to the container.
builder.Services.AddRazorPages();

builder.Host.UseSerilog();

builder.Services.AddSerilog(Log.Logger);
var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseAuthorization();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSerilogRequestLogging();

app.MapRazorPages();
app.UseRouting();

app.Run();
app.UseAuthorization();

app.MapRazorPages();

app.Run();
}
catch (Exception e)
{
Log.Fatal(e, "Exception occured during startup");
}
29 changes: 7 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,7 @@ Serilog можно конфигурировать через код, но зде
но все равно было бы неплохо зафиксировать что-то в логах.
А значит логирование надо сконфигурировать хотя бы минимальным образом еще до чтения конфигурации.

Оберни конфигурациию, создание и запуск приложения в try-catch и воспользуйся объектов `Log` для логирования. Добавь к нему
логирование в файл:
```csharp
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/start-host-log-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
```
Оберни конфигурациию, создание и запуск приложения в try-catch и воспользуйся объектов `Log` для логирования.
Теперь будет залогировано любое необработанное исключение, из-за которого упадет весь хост.
Но важно, что здесь до построения хоста добавляется логирование в `.logs/start-host-log-{current-date}.txt`.
Благодаря этому, если до обычного конфигурирования логирования произойдет исключение,
Expand Down Expand Up @@ -161,14 +154,13 @@ Password: changeme
### 3. Serilog + ELK
Теперь настроим отправку логов из нашего приложения в ELK.

Установи пакет Elastic.Serilog.Sinks.

Добавь к настройке лога внутри `AddSerilog` примерн следующий код:
Добавь к настройке лога следующий код:
```csharp
builder.Services.AddSerilog((_, lc) => lc.Enrich.FromLogContext()
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Elasticsearch([new Uri("http://localhost:9200")], opts =>
{
opts.DataStream = new DataStreamName("logs", "telemetry-loggin", "demo");
opts.DataStream = new DataStreamName("logs", "telemetry-logging", "demo");
opts.BootstrapMethod = BootstrapMethod.Failure;
opts.ConfigureChannel = channelOpts =>
{
Expand All @@ -180,20 +172,13 @@ builder.Services.AddSerilog((_, lc) => lc.Enrich.FromLogContext()
}, transport =>
{
transport.Authentication(new BasicAuthentication("elastic", "changeme")); // Basic Auth
// transport.Authentication(new ApiKey(base64EncodedApiKey)); // ApiKey
transport.OnRequestCompleted(d => Console.WriteLine($"es-req: {d.DebugInformation}"));
})
.Enrich.WithProperty("Environment", builder.Environment.EnvironmentName)
.ReadFrom.Configuration(builder.Configuration));

.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();
```
Подробнее про конфигурацию "трубы" до ELK можно прочитать [здесь](https://www.elastic.co/guide/en/ecs-logging/dotnet/current/serilog-data-shipper.html).

Замени `builder.Services.AddSerilog(...)` на
```csharp
builder.Services.AddSerilog(Log.Logger);
```

Теперь запусти приложение, потыкай по ссылкам. Проверь, что логирование в консоль не сломалось!
Открой Kibana, нажми на "бургер-меню" (три полоски слева) -> Analytics -> Discover. Проверь, что там есть твои логи.

Expand Down
8 changes: 1 addition & 7 deletions appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
"DetailedErrors": true
}
26 changes: 23 additions & 3 deletions appsettings.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
{
"Logging": {
"LogLevel": {
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": ".logs/log-.txt",
"formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true
}
},
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"
}
}
],
"MinimumLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
}
},
"AllowedHosts": "*"
Expand Down
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ services:
- ./logstash/pipeline:/usr/share/logstash/pipeline:ro,Z
ports:
- 5044:5044
- 50000:50000/tcp
- 50000:50000/udp
- 49999:49999/tcp
- 49999:49999/udp
- 9600:9600
environment:
LS_JAVA_OPTS: -Xms256m -Xmx256m
Expand Down
2 changes: 1 addition & 1 deletion logstash/pipeline/logstash.conf
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ input {
}

tcp {
port => 50000
port => 49999
}
}

Expand Down
6 changes: 6 additions & 0 deletions telemetry.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,10 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Elastic.Serilog.Sinks" Version="8.12.2" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
</ItemGroup>

</Project>