Skip to content

Commit 3341367

Browse files
make serilog work with version dotnet 8 (#247)
Co-authored-by: Mano Toth <[email protected]> Co-authored-by: Mano Toth <[email protected]>
1 parent bd6f10b commit 3341367

File tree

1 file changed

+95
-33
lines changed

1 file changed

+95
-33
lines changed

guides/send-logs-from-dotnet.mdx

+95-33
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ logoId: 'dotnet'
88
---
99

1010
import Prerequisites from "/snippets/standard-prerequisites.mdx"
11+
import ReplaceDatasetToken from "/snippets/replace-dataset-token.mdx"
1112

1213
<Prerequisites />
1314
{/* list separator */}
@@ -49,11 +50,11 @@ public static class AxiomLogger
4950
var client = new HttpClient();
5051

5152
// Specify the Axiom dataset name and construct the API endpoint URL
52-
var datasetName = "YOUR-DATASET-NAME"; // Replace with your actual dataset name
53+
var datasetName = "DATASET-NAME"; // Replace with your actual dataset name
5354
var axiomUri = $"https://api.axiom.co/v1/datasets/{datasetName}/ingest";
5455

5556
// Replace with your Axiom API token
56-
var apiToken = "YOUR-API-TOKEN"; // Ensure your API token is correct
57+
var apiToken = "API-TOKEN"; // Ensure your API token is correct
5758
5859
// Create an array of log entries, including the timestamp, message, and log level
5960
var logEntries = new[]
@@ -91,6 +92,8 @@ public static class AxiomLogger
9192
}
9293
```
9394

95+
<ReplaceDatasetToken />
96+
9497
### Configure the main program
9598

9699
Now that the Axiom logger is in place, update the main program so it can be used. Open the `Program.cs` file and replace its contents with the following code:
@@ -214,9 +217,10 @@ Add Serilog and the necessary extensions to your project. You need the `Serilog`
214217

215218
```bash
216219
dotnet add package Serilog
220+
dotnet add package Serilog.Sinks.Console
217221
dotnet add package Serilog.Sinks.Http
218-
dotnet add package Serilog.Formatting.Json
219222
dotnet add package Serilog.Formatting.Elasticsearch
223+
dotnet add package Microsoft.Extensions.Configuration
220224
```
221225

222226
### Configure Serilog
@@ -226,39 +230,90 @@ In your `Program.cs` or a startup configuration file, set up Serilog to use the
226230
```csharp
227231
using Serilog;
228232
using Serilog.Formatting.Elasticsearch;
233+
using Serilog.Sinks.Http;
234+
using System.Net.Http;
235+
using System.Net.Http.Headers;
236+
using System.IO;
237+
using Microsoft.Extensions.Configuration;
229238

230-
Log.Logger = new LoggerConfiguration()
231-
.WriteTo.Http(
232-
requestUri: "https://api.axiom.co/v1/datasets/YOUR-DATASET-NAME/ingest",
233-
textFormatter: new ElasticsearchJsonFormatter(renderMessageTemplate: false, inlineFields: true),
234-
httpClient: new HttpClient
235-
{
236-
DefaultRequestHeaders =
237-
{
238-
{ "Authorization", "Bearer YOUR-API-TOKEN" }
239-
}
240-
})
241-
.CreateLogger();
239+
public class AxiomConfig
240+
{
241+
public const string DatasetName = "DATASET_NAME";
242+
public const string ApiToken = "API_TOKEN";
243+
public const string ApiUrl = "https://api.axiom.co/v1/datasets";
244+
}
242245

243-
class Program
246+
public class AxiomHttpClient : IHttpClient
244247
{
245-
static async Task Main(string[] args)
248+
private readonly HttpClient _httpClient;
249+
250+
public AxiomHttpClient()
246251
{
247-
Log.Information("Application started");
248-
await SimulateOperations();
249-
Log.Information($"CLR version: {Environment.Version}");
250-
Log.Information("Application shutting down");
252+
_httpClient = new HttpClient();
253+
_httpClient.DefaultRequestHeaders.Authorization =
254+
new AuthenticationHeaderValue("Bearer", AxiomConfig.ApiToken);
255+
}
256+
257+
public void Configure(IConfiguration configuration)
258+
{
259+
}
260+
261+
public async Task<HttpResponseMessage> PostAsync(string requestUri, Stream contentStream, CancellationToken cancellationToken = default)
262+
{
263+
var content = new StreamContent(contentStream);
264+
content.Headers.Add("Content-Type", "application/json");
265+
return await _httpClient.PostAsync(requestUri, content, cancellationToken).ConfigureAwait(false);
266+
}
267+
268+
public void Dispose()
269+
{
270+
_httpClient?.Dispose();
271+
}
272+
}
273+
274+
public class Program
275+
{
276+
public static async Task Main(string[] args)
277+
{
278+
Log.Logger = new LoggerConfiguration()
279+
.MinimumLevel.Debug()
280+
.WriteTo.Console()
281+
.WriteTo.Http(
282+
requestUri: $"{AxiomConfig.ApiUrl}/{AxiomConfig.DatasetName}/ingest",
283+
queueLimitBytes: null,
284+
textFormatter: new ElasticsearchJsonFormatter(renderMessageTemplate: false, inlineFields: true),
285+
httpClient: new AxiomHttpClient()
286+
)
287+
.CreateLogger();
288+
289+
try
290+
{
291+
Log.Information("Application started on .NET 8");
292+
await SimulateOperations();
293+
Log.Information($"Runtime version: {Environment.Version}");
294+
Log.Information("Application shutting down");
295+
}
296+
catch (Exception ex)
297+
{
298+
Log.Fatal(ex, "Application terminated unexpectedly");
299+
}
300+
finally
301+
{
302+
await Log.CloseAndFlushAsync();
303+
}
251304
}
252305

253306
static async Task SimulateOperations()
254307
{
255308
Log.Debug("Starting operations");
256309
Log.Debug("Connecting to database");
257-
await Task.Delay(500); // Simulated delay
310+
await Task.Delay(500);
258311
Log.Information("Connected to database successfully");
312+
259313
Log.Debug("Retrieving user data");
260314
await Task.Delay(1000);
261315
Log.Information("Retrieved 100 user records");
316+
262317
Log.Debug("Updating user preferences");
263318
await Task.Delay(800);
264319
Log.Information("Updated user preferences successfully");
@@ -271,41 +326,46 @@ class Program
271326
}
272327
catch (Exception ex)
273328
{
274-
Log.Error($"Payment processing failed: {ex.Message}");
329+
Log.Error(ex, "Payment processing failed: {ErrorMessage}", ex.Message);
275330
}
276331

277332
Log.Debug("Sending email notifications");
278333
await Task.Delay(1200);
279334
Log.Information("Sent 50 email notifications");
280-
Log.Warning("Detected high memory usage");
335+
336+
Log.Warning("Detected high memory usage: {UsagePercentage}%", 85);
281337
await Task.Delay(500);
282338
Log.Information("Memory usage normalized");
339+
283340
Log.Debug("Operations completed");
284341
}
285342
}
286343
```
287344

345+
<ReplaceDatasetToken />
346+
288347
### Project file configuration
289348

290349
Ensure your `axiomlogs.csproj` file is configured with the package references. The file should look like this:
291350

292351
```xml
293352
<Project Sdk="Microsoft.NET.Sdk">
294-
295353
<PropertyGroup>
296354
<OutputType>Exe</OutputType>
297-
<TargetFramework>net6.0</TargetFramework>
355+
<TargetFramework>net8.0</TargetFramework>
298356
<ImplicitUsings>enable</ImplicitUsings>
299357
<Nullable>enable</Nullable>
358+
<AssemblyName>SerilogApp</AssemblyName>
359+
<RootNamespace>SerilogApp</RootNamespace>
300360
</PropertyGroup>
301361

302362
<ItemGroup>
303-
<PackageReference Include="Serilog" Version="2.10.0" />
304-
<PackageReference Include="Serilog.Sinks.Http" Version="5.0.0" />
305-
<PackageReference Include="Serilog.Formatting.Json" Version="3.1.0" />
306-
<PackageReference Include="Serilog.Formatting.Elasticsearch" Version="8.4.1" />
363+
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
364+
<PackageReference Include="Serilog" Version="3.1.1" />
365+
<PackageReference Include="Serilog.Formatting.Elasticsearch" Version="10.0.0" />
366+
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
367+
<PackageReference Include="Serilog.Sinks.Http" Version="9.0.0" />
307368
</ItemGroup>
308-
309369
</Project>
310370
```
311371

@@ -348,8 +408,8 @@ Set up NLog by creating an `NLog.config` file or configuring it programmatically
348408
flushTimeout="5000">
349409
<target xsi:type="HTTP"
350410
name="axiom"
351-
url="https://api.axiom.co/v1/datasets/YOUR-DATASET-NAME/ingest"
352-
HttpHeaders="Authorization: Bearer YOUR-API-TOKEN"
411+
url="https://api.axiom.co/v1/datasets/DATASET_NAME/ingest"
412+
HttpHeaders="Authorization: Bearer API_TOKEN"
353413
contentType="application/json">
354414
<layout xsi:type="JsonLayout" includeAllProperties="true">
355415
<attribute name="timestamp" layout="${date:universalTime=true:format=o}" />
@@ -367,6 +427,8 @@ Set up NLog by creating an `NLog.config` file or configuring it programmatically
367427
</nlog>
368428
```
369429

430+
<ReplaceDatasetToken />
431+
370432
### Configure the main program
371433

372434
Update the main program to use `NLog`. In your `Program.cs` file:

0 commit comments

Comments
 (0)