-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicExample.cs
More file actions
81 lines (64 loc) · 2.39 KB
/
BasicExample.cs
File metadata and controls
81 lines (64 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Example: Basic Structured Logging with dotnet-logging-kit
// This example demonstrates core logging functionality.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using JG.Logging.Extensions;
using JG.Logging.Formatters;
using JG.Logging.Internal;
using JG.Logging.Sinks;
var services = new ServiceCollection();
// Configure structured logging
services.AddStructuredLogging(options =>
{
options.SetMinimumLevel(LogLevel.Information);
// Console output with plain text formatting
options.AddConsoleSink(new PlainTextFormatter());
// File output with JSON formatting and daily rotation
var logsDir = Path.Combine(Directory.GetCurrentDirectory(), "logs");
options.AddFileSink(
directory: logsDir,
fileNamePrefix: "example",
rollingInterval: JG.Logging.Sinks.RollingInterval.Day,
maxBackupFiles: 7
);
// Add enrichers for context
options.AddStandardEnrichers(includeVersion: true, versionType: typeof(Program));
});
var sp = services.BuildServiceProvider();
var logger = sp.GetRequiredService<ILogger<Program>>();
// Example 1: Basic logging
logger.LogInformation("Application started");
// Example 2: Logging with correlation ID
using (CorrelationIdProvider.SetCorrelationId(Guid.NewGuid().ToString()))
{
logger.LogInformation("Processing user request");
// Simulate async operation
await Task.Delay(100);
logger.LogInformation("Request completed");
}
// Example 3: Scoped context for request-specific data
using (logger.BeginScope(null))
{
ScopeContextProvider.AddPropertyToCurrentScope("UserId", "user-123");
ScopeContextProvider.AddPropertyToCurrentScope("RequestPath", "/api/users");
logger.LogInformation("Handling API request");
}
// Example 4: Error logging with exceptions
try
{
throw new InvalidOperationException("Example error for demonstration");
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred during processing");
}
// Example 5: Structured data with enrichment
using (logger.BeginScope(null))
{
ScopeContextProvider.AddPropertyToCurrentScope("Operation", "DatabaseQuery");
ScopeContextProvider.AddPropertyToCurrentScope("Duration", "125ms");
logger.LogInformation("Query executed successfully");
}
logger.LogInformation("Application shutting down");
// Dispose to ensure file sinks are flushed
await sp.DisposeAsync();