🎯 Exemples recommandés
Balanced sample collections from various categories for you to explore
Gestion d'Erreurs Windows - Exemples C#
Exemples complets de gestion d'erreurs en C# pour plateforme Windows incluant gestion d'exceptions, journalisation et validation de paramètres
💻 Gestion d'Exceptions avec Try-Catch csharp
🟢 simple
⭐⭐
Gestion d'exceptions de base et avancée utilisant les blocs try-catch en C#
⏱️ 20 min
🏷️ csharp, exception, error, windows
Prerequisites:
Basic C# syntax, Understanding of exceptions
using System;
using System.IO;
using System.Collections.Generic;
class ExceptionHandlingExamples
{
// 1. Basic try-catch example
public static void BasicTryCatch()
{
Console.WriteLine("=== Basic Try-Catch Example ===");
try
{
// This will throw a DivideByZeroException
int result = 10 / 0;
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Caught DivideByZeroException: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Caught general exception: {ex.Message}");
}
finally
{
Console.WriteLine("Finally block always executes");
}
}
// 2. Multiple catch blocks
public static void MultipleCatchBlocks()
{
Console.WriteLine("
=== Multiple Catch Blocks Example ===");
string[] testCases = { "123", "abc", null, "" };
foreach (string testCase in testCases)
{
try
{
Console.WriteLine($"
Processing: {testCase ?? "null"}");
int number = int.Parse(testCase);
int result = 100 / number;
Console.WriteLine($"Success! Result: {result}");
}
catch (FormatException ex)
{
Console.WriteLine($"Format Exception: {ex.Message}");
}
catch (ArgumentNullException ex)
{
Console.WriteLine($"Argument Null Exception: {ex.Message}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Divide By Zero Exception: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected Exception: {ex.Message}");
}
}
}
// 3. Nested try-catch
public static void NestedTryCatch()
{
Console.WriteLine("
=== Nested Try-Catch Example ===");
try
{
Console.WriteLine("Outer try block started");
try
{
Console.WriteLine("Inner try block started");
// Attempt to read a non-existent file
string content = File.ReadAllText("nonexistent.txt");
Console.WriteLine("File read successfully");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Inner catch - File not found: {ex.Message}");
throw new InvalidOperationException("File processing failed", ex);
}
Console.WriteLine("Outer try block continued");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Outer catch - Invalid operation: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($"Inner exception: {ex.InnerException.Message}");
}
}
}
// 4. Custom exception class
public class InvalidAgeException : Exception
{
public InvalidAgeException() : base("Age must be between 0 and 150") { }
public InvalidAgeException(string message) : base(message) { }
public InvalidAgeException(string message, Exception inner) : base(message, inner) { }
}
public static void CustomExceptions()
{
Console.WriteLine("
=== Custom Exceptions Example ===");
List<int> ages = { 25, -5, 200, 30 };
foreach (int age in ages)
{
try
{
ValidateAge(age);
Console.WriteLine($"Age {age} is valid");
}
catch (InvalidAgeException ex)
{
Console.WriteLine($"Invalid age {age}: {ex.Message}");
}
}
}
private static void ValidateAge(int age)
{
if (age < 0 || age > 150)
{
throw new InvalidAgeException($"Age {age} is not valid. Must be between 0 and 150.");
}
}
// 5. Exception filters (C# 6.0+)
public static void ExceptionFilters()
{
Console.WriteLine("
=== Exception Filters Example ===");
string[] urls = {
"https://valid.example.com",
"invalid-url",
"http://timeout.example.com"
};
foreach (string url in urls)
{
try
{
// Simulate HTTP request
if (url.StartsWith("https://valid"))
{
Console.WriteLine($"Successfully connected to {url}");
}
else if (url == "invalid-url")
{
throw new UriFormatException("Invalid URI format");
}
else
{
throw new TimeoutException("Connection timeout");
}
}
catch (Exception ex) when (ex is UriFormatException)
{
Console.WriteLine($"URI Error for {url}: {ex.Message}");
}
catch (Exception ex) when (ex is TimeoutException)
{
Console.WriteLine($"Timeout Error for {url}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Error for {url}: {ex.Message}");
}
}
}
// 6. Using statement for resource management
public static void UsingStatement()
{
Console.WriteLine("
=== Using Statement Example ===");
try
{
// Create a test file
File.WriteAllText("test.txt", "Hello, World!");
// Using statement ensures proper disposal
using (StreamReader reader = new StreamReader("test.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine($"File content: {content}");
} // reader is automatically disposed here
// Try to use the disposed reader (this would fail if we tried)
Console.WriteLine("File reader properly disposed");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
// Cleanup
if (File.Exists("test.txt"))
{
File.Delete("test.txt");
Console.WriteLine("Test file cleaned up");
}
}
}
// 7. Async exception handling
public static async Task AsyncExceptionHandling()
{
Console.WriteLine("
=== Async Exception Handling Example ===");
List<string> urls = {
"https://valid.example.com",
"invalid-url",
"https://timeout.example.com"
};
foreach (string url in urls)
{
try
{
string result = await SimulateHttpRequestAsync(url);
Console.WriteLine($"Success: {result}");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP Error for {url}: {ex.Message}");
}
catch (TaskCanceledException ex)
{
Console.WriteLine($"Timeout for {url}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error for {url}: {ex.Message}");
}
}
}
private static async Task<string> SimulateHttpRequestAsync(string url)
{
await Task.Delay(100); // Simulate network delay
if (url == "invalid-url")
{
throw new HttpRequestException("Invalid URL format");
}
if (url.Contains("timeout"))
{
throw new TaskCanceledException("Request timed out");
}
return $"Response from {url}";
}
// 8. Aggregate exception handling
public static void AggregateExceptionHandling()
{
Console.WriteLine("
=== Aggregate Exception Example ===");
List<Task> tasks = new List<Task>();
// Create multiple tasks that might fail
tasks.Add(Task.Run(() => {
throw new InvalidOperationException("Task 1 failed");
}));
tasks.Add(Task.Run(() => {
throw new ArgumentException("Task 2 failed");
}));
tasks.Add(Task.Run(() => {
Console.WriteLine("Task 3 completed successfully");
}));
try
{
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All tasks completed successfully");
}
catch (AggregateException ex)
{
Console.WriteLine($"AggregateException caught with {ex.InnerExceptions.Count} inner exceptions:");
foreach (Exception innerEx in ex.InnerExceptions)
{
Console.WriteLine($" - {innerEx.GetType().Name}: {innerEx.Message}");
}
// Handle individual exceptions
ex.Handle(innerEx =>
{
if (innerEx is InvalidOperationException)
{
Console.WriteLine($"Handled InvalidOperationException: {innerEx.Message}");
return true; // Exception handled
}
else if (innerEx is ArgumentException)
{
Console.WriteLine($"Handled ArgumentException: {innerEx.Message}");
return true; // Exception handled
}
return false; // Exception not handled
});
}
}
static void Main(string[] args)
{
Console.WriteLine("=== C# Exception Handling Examples ===
");
try
{
BasicTryCatch();
MultipleCatchBlocks();
NestedTryCatch();
CustomExceptions();
ExceptionFilters();
UsingStatement();
Console.WriteLine("
=== Async Examples ===");
AsyncExceptionHandling().GetAwaiter().GetResult();
Console.WriteLine("
=== Parallel Processing Examples ===");
AggregateExceptionHandling();
Console.WriteLine("
All exception handling examples completed successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error in main program: {ex.Message}");
}
}
}
💻 Validation de Paramètres csharp
🟢 simple
⭐⭐
Techniques complètes de validation de paramètres incluant vérifications nulles, validation de plage et règles personnalisées
⏱️ 30 min
🏷️ csharp, validation, parameters, windows
Prerequisites:
C# exception handling, LINQ basics, Regular expressions
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
// Custom validation exception
public class ValidationException : Exception
{
public ValidationException(string message) : base(message) { }
public ValidationException(string message, Exception inner) : base(message, inner) { }
}
// Validation helper class
public static class Validator
{
// 1. Null and empty checks
public static void NotNull(object value, string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName, $"Parameter '{parameterName}' cannot be null");
}
}
public static void NotNullOrEmpty(string value, string parameterName)
{
NotNull(value, parameterName);
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException($"Parameter '{parameterName}' cannot be null or empty", parameterName);
}
}
public static void NotNullOrWhiteSpace(string value, string parameterName)
{
NotNull(value, parameterName);
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException($"Parameter '{parameterName}' cannot be null, empty, or whitespace", parameterName);
}
}
// 2. Range validation
public static void InRange(int value, int min, int max, string parameterName)
{
if (value < min || value > max)
{
throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter '{parameterName}' must be between {min} and {max}");
}
}
public static void InRange(double value, double min, double max, string parameterName)
{
if (value < min || value > max)
{
throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter '{parameterName}' must be between {min} and {max}");
}
}
public static void Positive(int value, string parameterName)
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter '{parameterName}' must be positive");
}
}
public static void NonNegative(int value, string parameterName)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter '{parameterName}' must be non-negative");
}
}
// 3. String validation
public static void Length(string value, int minLength, int maxLength, string parameterName)
{
NotNull(value, parameterName);
if (value.Length < minLength || value.Length > maxLength)
{
throw new ArgumentException($"Parameter '{parameterName}' length must be between {minLength} and {maxLength} characters", parameterName);
}
}
public static void Matches(string value, string pattern, string parameterName)
{
NotNull(value, parameterName);
NotNull(pattern, nameof(pattern));
if (!Regex.IsMatch(value, pattern))
{
throw new ArgumentException($"Parameter '{parameterName}' does not match the required pattern: {pattern}", parameterName);
}
}
public static void Email(string value, string parameterName)
{
NotNull(value, parameterName);
string emailPattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
Matches(value, emailPattern, parameterName);
}
public static void PhoneNumber(string value, string parameterName)
{
NotNull(value, parameterName);
string phonePattern = @"^\+?[1-9]\d{1,14}$";
if (!Regex.IsMatch(value, phonePattern))
{
throw new ArgumentException($"Parameter '{parameterName}' is not a valid phone number", parameterName);
}
}
// 4. Collection validation
public static void NotEmpty<T>(IEnumerable<T> collection, string parameterName)
{
NotNull(collection, parameterName);
if (!collection.GetEnumerator().MoveNext())
{
throw new ArgumentException($"Parameter '{parameterName}' cannot be empty", parameterName);
}
}
public static void Count<T>(IEnumerable<T> collection, int minCount, int maxCount, string parameterName)
{
NotNull(collection, parameterName);
int count = 0;
foreach (var item in collection)
{
count++;
}
if (count < minCount || count > maxCount)
{
throw new ArgumentException($"Parameter '{parameterName}' must contain between {minCount} and {maxCount} items", parameterName);
}
}
// 5. Date validation
public static void InFuture(DateTime value, string parameterName)
{
if (value <= DateTime.Now)
{
throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter '{parameterName}' must be in the future");
}
}
public static void InPast(DateTime value, string parameterName)
{
if (value >= DateTime.Now)
{
throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter '{parameterName}' must be in the past");
}
}
public static void Between(DateTime value, DateTime min, DateTime max, string parameterName)
{
if (value < min || value > max)
{
throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter '{parameterName}' must be between {min:yyyy-MM-dd} and {max:yyyy-MM-dd}");
}
}
// 6. Custom validation
public static void Custom<T>(T value, Func<T, bool> validationFunc, string errorMessage, string parameterName)
{
NotNull(validationFunc, nameof(validationFunc));
NotNull(value, parameterName);
if (!validationFunc(value))
{
throw new ValidationException($"Parameter '{parameterName}' validation failed: {errorMessage}");
}
}
}
// User class with validation
public class User
{
public string Id { get; }
public string Name { get; }
public string Email { get; }
public int Age { get; }
public DateTime BirthDate { get; }
public string PhoneNumber { get; }
public User(string name, string email, int age, DateTime birthDate, string phoneNumber)
{
// Validate all parameters
Validator.NotNullOrWhiteSpace(name, nameof(name));
Validator.Length(name, 2, 50, nameof(name));
Validator.Email(email, nameof(email));
Validator.InRange(age, 0, 150, nameof(age));
Validator.InPast(birthDate, nameof(birthDate));
Validator.PhoneNumber(phoneNumber, nameof(phoneNumber));
// Additional custom validation
Validator.Custom(age, a => CalculateAge(birthDate) == a, "Age does not match birth date", nameof(age));
// Assign properties
Id = Guid.NewGuid().ToString();
Name = name.Trim();
Email = email.ToLowerInvariant();
Age = age;
BirthDate = birthDate;
PhoneNumber = phoneNumber;
}
private static int CalculateAge(DateTime birthDate)
{
int age = DateTime.Now.Year - birthDate.Year;
if (birthDate > DateTime.Now.AddYears(-age))
{
age--;
}
return age;
}
public override string ToString()
{
return $"User: {Name}, Email: {Email}, Age: {Age}, Phone: {PhoneNumber}";
}
}
// Order class with validation
public class Order
{
public string OrderId { get; }
public List<OrderItem> Items { get; }
public DateTime OrderDate { get; }
public decimal TotalAmount { get; }
public string CustomerEmail { get; }
public Order(List<OrderItem> items, string customerEmail)
{
Validator.NotEmpty(items, nameof(items));
Validator.Count(items, 1, 100, nameof(items));
Validator.Email(customerEmail, nameof(customerEmail));
// Validate each item
foreach (var item in items)
{
Validator.Positive(item.Quantity, nameof(item.Quantity));
Validator.Positive(item.Price, nameof(item.Price));
}
OrderId = "ORD-" + Guid.NewGuid().ToString("N")[..8].ToUpper();
Items = new List<OrderItem>(items);
OrderDate = DateTime.Now;
TotalAmount = CalculateTotal();
CustomerEmail = customerEmail.ToLowerInvariant();
}
private decimal CalculateTotal()
{
decimal total = 0;
foreach (var item in Items)
{
total += item.Quantity * item.Price;
}
return total;
}
public override string ToString()
{
return $"Order {OrderId}: {Items.Count} items, Total: {TotalAmount:C}";
}
}
public class OrderItem
{
public string ProductName { get; }
public int Quantity { get; }
public decimal Price { get; }
public OrderItem(string productName, int quantity, decimal price)
{
Validator.NotNullOrWhiteSpace(productName, nameof(productName));
Validator.Length(productName, 1, 100, nameof(productName));
Validator.Positive(quantity, nameof(quantity));
Validator.Positive(price, nameof(price));
ProductName = productName;
Quantity = quantity;
Price = price;
}
}
// Validation examples class
public class ValidationExamples
{
// 1. Basic parameter validation
public static void BasicValidation()
{
Console.WriteLine("=== Basic Parameter Validation ===");
// Valid cases
try
{
Validator.NotNull("hello", "test");
Console.WriteLine("✓ NotNull validation passed");
Validator.InRange(25, 0, 100, "age");
Console.WriteLine("✓ Range validation passed");
Validator.Positive(10, "count");
Console.WriteLine("✓ Positive validation passed");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
// Invalid cases
try
{
Validator.NotNull(null, "test");
}
catch (ArgumentNullException ex)
{
Console.WriteLine($"✓ NotNull validation failed as expected: {ex.Message}");
}
try
{
Validator.InRange(150, 0, 100, "age");
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"✓ Range validation failed as expected: {ex.Message}");
}
}
// 2. String validation
public static void StringValidation()
{
Console.WriteLine("\n=== String Validation ===");
// Valid cases
try
{
Validator.NotNullOrEmpty("Hello World", "message");
Console.WriteLine("✓ NotNullOrEmpty validation passed");
Validator.Length("Test", 2, 10, "text");
Console.WriteLine("✓ Length validation passed");
Validator.Email("[email protected]", "email");
Console.WriteLine("✓ Email validation passed");
Validator.Matches("ABC123", @"^[A-Z]{3}[0-9]{3}$", "code");
Console.WriteLine("✓ Pattern validation passed");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
// Invalid cases
try
{
Validator.Email("invalid-email", "email");
}
catch (ArgumentException ex)
{
Console.WriteLine($"✓ Email validation failed as expected: {ex.Message}");
}
}
// 3. Collection validation
public static void CollectionValidation()
{
Console.WriteLine("\n=== Collection Validation ===");
// Valid cases
var validList = new List<string> { "item1", "item2", "item3" };
try
{
Validator.NotEmpty(validList, "items");
Console.WriteLine("✓ NotEmpty validation passed");
Validator.Count(validList, 1, 10, "items");
Console.WriteLine("✓ Count validation passed");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
// Invalid cases
try
{
Validator.NotEmpty(new List<string>(), "items");
}
catch (ArgumentException ex)
{
Console.WriteLine($"✓ NotEmpty validation failed as expected: {ex.Message}");
}
}
// 4. Date validation
public static void DateValidation()
{
Console.WriteLine("\n=== Date Validation ===");
// Valid cases
try
{
Validator.InPast(DateTime.Now.AddDays(-1), "pastDate");
Console.WriteLine("✓ Past date validation passed");
Validator.InFuture(DateTime.Now.AddDays(1), "futureDate");
Console.WriteLine("✓ Future date validation passed");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
// Invalid cases
try
{
Validator.InFuture(DateTime.Now.AddDays(-1), "futureDate");
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"✓ Future date validation failed as expected: {ex.Message}");
}
}
// 5. Custom validation
public static void CustomValidation()
{
Console.WriteLine("\n=== Custom Validation ===");
// Valid case
try
{
Validator.Custom("12345", value => value.Length == 5 && value.All(char.IsDigit), "Must be 5 digits", "zipCode");
Console.WriteLine("✓ Custom validation passed");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
// Invalid case
try
{
Validator.Custom("abc", value => value.All(char.IsDigit), "Must contain only digits", "number");
}
catch (ValidationException ex)
{
Console.WriteLine($"✓ Custom validation failed as expected: {ex.Message}");
}
}
// 6. Object validation
public static void ObjectValidation()
{
Console.WriteLine("\n=== Object Validation ===");
// Valid user creation
try
{
var user = new User(
"John Doe",
"[email protected]",
30,
new DateTime(1993, 5, 15),
"+1234567890"
);
Console.WriteLine($"✓ Valid user created: {user}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
// Invalid user creation
try
{
var invalidUser = new User(
"", // Invalid name
"invalid-email", // Invalid email
-5, // Invalid age
DateTime.Now.AddDays(1), // Invalid birth date
"123" // Invalid phone
);
}
catch (Exception ex)
{
Console.WriteLine($"✓ User validation failed as expected: {ex.Message}");
}
// Valid order creation
try
{
var items = new List<OrderItem>
{
new OrderItem("Product 1", 2, 19.99m),
new OrderItem("Product 2", 1, 29.99m)
};
var order = new Order(items, "[email protected]");
Console.WriteLine($"✓ Valid order created: {order}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
}
// 7. Method with comprehensive validation
public static void ProcessUserData(string name, string email, int age, string[] preferences)
{
Console.WriteLine("\n=== Processing User Data ===");
try
{
// Validate input parameters
Validator.NotNullOrWhiteSpace(name, nameof(name));
Validator.Length(name, 2, 50, nameof(name));
Validator.Email(email, nameof(email));
Validator.InRange(age, 18, 120, nameof(age));
Validator.NotNull(preferences, nameof(preferences));
Validator.Count(preferences, 1, 10, nameof(preferences));
foreach (var pref in preferences)
{
Validator.NotNullOrWhiteSpace(pref, nameof(preferences));
Validator.Length(pref, 1, 50, nameof(preferences));
}
Console.WriteLine($"✓ Processing data for: {name} ({email}), Age: {age}");
Console.WriteLine($"✓ Preferences: {string.Join(", ", preferences)}");
// Process the data (simulation)
Console.WriteLine("✓ User data processed successfully");
}
catch (Exception ex)
{
Console.WriteLine($"✗ Validation failed: {ex.Message}");
throw;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== C# Parameter Validation Examples ===\n");
try
{
// Run all validation examples
ValidationExamples.BasicValidation();
ValidationExamples.StringValidation();
ValidationExamples.CollectionValidation();
ValidationExamples.DateValidation();
ValidationExamples.CustomValidation();
ValidationExamples.ObjectValidation();
Console.WriteLine("\n=== Method Validation Examples ===");
// Valid case
try
{
ValidationExamples.ProcessUserData(
"Alice Smith",
"[email protected]",
25,
new[] { "reading", "travel", "music" }
);
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error in valid case: {ex.Message}");
}
// Invalid case
try
{
ValidationExamples.ProcessUserData(
"", // Invalid name
"invalid-email", // Invalid email
15, // Invalid age
new string[] { } // Invalid preferences
);
}
catch (Exception ex)
{
Console.WriteLine($"✓ Method validation failed as expected: {ex.Message}");
}
Console.WriteLine("\nAll parameter validation examples completed successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error in main program: {ex.Message}");
}
}
}
💻 Implémentation de Journalisation csharp
🟡 intermediate
⭐⭐⭐
Créer un système de journalisation personnalisé avec différents niveaux et destinations de sortie
⏱️ 25 min
🏷️ csharp, logging, file, threading, windows
Prerequisites:
C# file I/O, Threading basics, Exception handling
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
// Enum for log levels
public enum LogLevel
{
Debug = 0,
Info = 1,
Warning = 2,
Error = 3,
Critical = 4
}
// Custom logger class
public class Logger
{
private readonly string _logFilePath;
private readonly LogLevel _minLogLevel;
private readonly object _lockObject = new object();
public Logger(string logFilePath, LogLevel minLogLevel = LogLevel.Info)
{
_logFilePath = logFilePath;
_minLogLevel = minLogLevel;
// Ensure log directory exists
string logDirectory = Path.GetDirectoryName(logFilePath);
if (!string.IsNullOrEmpty(logDirectory) && !Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
// Write initial log entry
LogInfo($"Logger initialized. Log file: {_logFilePath}, Min level: {_minLogLevel}");
}
// Core logging method
private void WriteLog(LogLevel level, string message, Exception exception = null)
{
if (level < _minLogLevel)
return;
lock (_lockObject)
{
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string levelStr = level.ToString().ToUpper().PadRight(8);
string threadId = Thread.CurrentThread.ManagedThreadId.ToString();
string logEntry = $"[{timestamp}] [{levelStr}] [T:{threadId}] {message}";
if (exception != null)
{
logEntry += $"\nException: {exception.GetType().Name}: {exception.Message}";
logEntry += $"\nStackTrace: {exception.StackTrace}";
}
// Write to console
Console.WriteLine(logEntry);
// Write to file
try
{
File.AppendAllText(_logFilePath, logEntry + Environment.NewLine);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to write to log file: {ex.Message}");
}
}
}
// Convenience methods for different log levels
public void LogDebug(string message)
{
WriteLog(LogLevel.Debug, message);
}
public void LogInfo(string message)
{
WriteLog(LogLevel.Info, message);
}
public void LogWarning(string message)
{
WriteLog(LogLevel.Warning, message);
}
public void LogError(string message, Exception exception = null)
{
WriteLog(LogLevel.Error, message, exception);
}
public void LogCritical(string message, Exception exception = null)
{
WriteLog(LogLevel.Critical, message, exception);
}
}
// Logger factory for managing multiple loggers
public static class LoggerFactory
{
private static readonly Dictionary<string, Logger> _loggers = new Dictionary<string, Logger>();
private static readonly object _lockObject = new object();
public static Logger GetLogger(string name, LogLevel minLogLevel = LogLevel.Info)
{
lock (_lockObject)
{
if (!_loggers.ContainsKey(name))
{
string logPath = $"logs/{name}_{DateTime.Now:yyyyMMdd}.log";
_loggers[name] = new Logger(logPath, minLogLevel);
}
return _loggers[name];
}
}
public static void CloseAllLoggers()
{
lock (_lockObject)
{
foreach (var logger in _loggers.Values)
{
logger.LogInfo("Logger shutting down");
}
_loggers.Clear();
}
}
}
// Example usage class
public class LoggingExamples
{
private readonly Logger _logger;
public LoggingExamples()
{
_logger = LoggerFactory.GetLogger("LoggingExamples");
}
// 1. Basic logging examples
public void BasicLogging()
{
_logger.LogInfo("Starting basic logging examples");
_logger.LogDebug("This is a debug message - only visible in debug mode");
_logger.LogInfo("This is an info message - normal operation information");
_logger.LogWarning("This is a warning - potential issue detected");
try
{
// Simulate an error
throw new InvalidOperationException("This is a simulated error");
}
catch (Exception ex)
{
_logger.LogError("An error occurred during processing", ex);
}
_logger.LogCritical("This is a critical message - system may be unstable");
}
// 2. Logging in different methods
public void MethodWithLogging(string parameter)
{
_logger.LogDebug($"Entering MethodWithLogging with parameter: {parameter}");
try
{
if (string.IsNullOrEmpty(parameter))
{
_logger.LogWarning("Empty parameter provided");
return;
}
if (parameter.Length < 3)
{
throw new ArgumentException("Parameter must be at least 3 characters long");
}
_logger.LogInfo($"Successfully processed parameter: {parameter}");
// Simulate some work
Thread.Sleep(100);
}
catch (Exception ex)
{
_logger.LogError($"Failed to process parameter: {parameter}", ex);
throw;
}
finally
{
_logger.LogDebug("Exiting MethodWithLogging");
}
}
// 3. Performance logging
public void PerformanceLogging()
{
_logger.LogInfo("Starting performance measurement");
var startTime = DateTime.Now;
try
{
// Simulate some work
for (int i = 0; i < 1000; i++)
{
double result = Math.Sqrt(i);
if (i % 100 == 0)
{
_logger.LogDebug($"Processed {i} items, current result: {result:F2}");
}
}
var duration = DateTime.Now - startTime;
_logger.LogInfo($"Performance test completed in {duration.TotalMilliseconds:F2}ms");
}
catch (Exception ex)
{
_logger.LogError("Performance test failed", ex);
}
}
// 4. Logging from multiple threads
public void MultiThreadedLogging()
{
_logger.LogInfo("Starting multi-threaded logging test");
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 5; i++)
{
int threadId = i;
Thread thread = new Thread(() =>
{
for (int j = 0; j < 10; j++)
{
_logger.LogInfo($"Thread {threadId} - Message {j}");
Thread.Sleep(50);
}
});
threads.Add(thread);
thread.Start();
}
// Wait for all threads to complete
foreach (var thread in threads)
{
thread.Join();
}
_logger.LogInfo("Multi-threaded logging test completed");
}
// 5. Structured logging
public void StructuredLogging()
{
_logger.LogInfo("Starting structured logging examples");
// Log user action
string userId = "user123";
string action = "login";
string ip = "192.168.1.100";
_logger.LogInfo($"User action - ID: {userId}, Action: {action}, IP: {ip}");
// Log business event
string orderId = "ORD-001";
decimal amount = 99.99m;
string status = "completed";
_logger.LogInfo($"Order processed - ID: {orderId}, Amount: {amount:C}, Status: {status}");
// Log system metrics
double cpuUsage = 75.5;
long memoryUsage = 1024 * 1024 * 512; // 512 MB
int activeConnections = 42;
_logger.LogInfo($"System metrics - CPU: {cpuUsage:F1}%, Memory: {memoryUsage / 1024 / 1024}MB, Connections: {activeConnections}");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== C# Logging Examples ===\n");
try
{
// Create examples instance
var examples = new LoggingExamples();
// Run different logging examples
examples.BasicLogging();
Console.WriteLine();
examples.MethodWithLogging("Hello");
examples.MethodWithLogging("Hi");
examples.MethodWithLogging(""); // This will log a warning
Console.WriteLine();
try
{
examples.MethodWithLogging("AB"); // This will throw an exception
}
catch
{
Console.WriteLine("Expected exception caught");
}
Console.WriteLine();
examples.PerformanceLogging();
Console.WriteLine();
examples.MultiThreadedLogging();
Console.WriteLine();
examples.StructuredLogging();
Console.WriteLine("\nAll logging examples completed!");
Console.WriteLine($"Check the 'logs' directory for log files.");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
// Clean up
LoggerFactory.CloseAllLoggers();
}
}
}