@@ -8,6 +8,7 @@ logoId: 'dotnet'
8
8
---
9
9
10
10
import Prerequisites from " /snippets/standard-prerequisites.mdx"
11
+ import ReplaceDatasetToken from " /snippets/replace-dataset-token.mdx"
11
12
12
13
<Prerequisites />
13
14
{ /* list separator */ }
@@ -49,11 +50,11 @@ public static class AxiomLogger
49
50
var client = new HttpClient ();
50
51
51
52
// 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
53
54
var axiomUri = $" https://api.axiom.co/v1/datasets/{datasetName }/ingest" ;
54
55
55
56
// 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
57
58
58
59
// Create an array of log entries, including the timestamp, message, and log level
59
60
var logEntries = new []
@@ -91,6 +92,8 @@ public static class AxiomLogger
91
92
}
92
93
```
93
94
95
+ <ReplaceDatasetToken />
96
+
94
97
### Configure the main program
95
98
96
99
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`
214
217
215
218
``` bash
216
219
dotnet add package Serilog
220
+ dotnet add package Serilog.Sinks.Console
217
221
dotnet add package Serilog.Sinks.Http
218
- dotnet add package Serilog.Formatting.Json
219
222
dotnet add package Serilog.Formatting.Elasticsearch
223
+ dotnet add package Microsoft.Extensions.Configuration
220
224
```
221
225
222
226
### Configure Serilog
@@ -226,39 +230,90 @@ In your `Program.cs` or a startup configuration file, set up Serilog to use the
226
230
``` csharp
227
231
using Serilog ;
228
232
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 ;
229
238
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
+ }
242
245
243
- class Program
246
+ public class AxiomHttpClient : IHttpClient
244
247
{
245
- static async Task Main (string [] args )
248
+ private readonly HttpClient _httpClient ;
249
+
250
+ public AxiomHttpClient ()
246
251
{
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
+ }
251
304
}
252
305
253
306
static async Task SimulateOperations ()
254
307
{
255
308
Log .Debug (" Starting operations" );
256
309
Log .Debug (" Connecting to database" );
257
- await Task .Delay (500 ); // Simulated delay
310
+ await Task .Delay (500 );
258
311
Log .Information (" Connected to database successfully" );
312
+
259
313
Log .Debug (" Retrieving user data" );
260
314
await Task .Delay (1000 );
261
315
Log .Information (" Retrieved 100 user records" );
316
+
262
317
Log .Debug (" Updating user preferences" );
263
318
await Task .Delay (800 );
264
319
Log .Information (" Updated user preferences successfully" );
@@ -271,41 +326,46 @@ class Program
271
326
}
272
327
catch (Exception ex )
273
328
{
274
- Log .Error ($ " Payment processing failed: {ex .Message } " );
329
+ Log .Error (ex , " Payment processing failed: {ErrorMessage} " , ex .Message );
275
330
}
276
331
277
332
Log .Debug (" Sending email notifications" );
278
333
await Task .Delay (1200 );
279
334
Log .Information (" Sent 50 email notifications" );
280
- Log .Warning (" Detected high memory usage" );
335
+
336
+ Log .Warning (" Detected high memory usage: {UsagePercentage}%" , 85 );
281
337
await Task .Delay (500 );
282
338
Log .Information (" Memory usage normalized" );
339
+
283
340
Log .Debug (" Operations completed" );
284
341
}
285
342
}
286
343
```
287
344
345
+ <ReplaceDatasetToken />
346
+
288
347
### Project file configuration
289
348
290
349
Ensure your ` axiomlogs.csproj ` file is configured with the package references. The file should look like this:
291
350
292
351
``` xml
293
352
<Project Sdk =" Microsoft.NET.Sdk" >
294
-
295
353
<PropertyGroup >
296
354
<OutputType >Exe</OutputType >
297
- <TargetFramework >net6 .0</TargetFramework >
355
+ <TargetFramework >net8 .0</TargetFramework >
298
356
<ImplicitUsings >enable</ImplicitUsings >
299
357
<Nullable >enable</Nullable >
358
+ <AssemblyName >SerilogApp</AssemblyName >
359
+ <RootNamespace >SerilogApp</RootNamespace >
300
360
</PropertyGroup >
301
361
302
362
<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" />
307
368
</ItemGroup >
308
-
309
369
</Project >
310
370
```
311
371
@@ -348,8 +408,8 @@ Set up NLog by creating an `NLog.config` file or configuring it programmatically
348
408
flushTimeout =" 5000" >
349
409
<target xsi : type =" HTTP"
350
410
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 "
353
413
contentType =" application/json" >
354
414
<layout xsi : type =" JsonLayout" includeAllProperties =" true" >
355
415
<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
367
427
</nlog >
368
428
```
369
429
430
+ <ReplaceDatasetToken />
431
+
370
432
### Configure the main program
371
433
372
434
Update the main program to use ` NLog ` . In your ` Program.cs ` file:
0 commit comments