Created
September 21, 2026 12:04
-
-
Save sunmeat/916e52a909fa6bde2efe0838405b4eac to your computer and use it in GitHub Desktop.
ручний спосіб логування у файл
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // у чистому Microsoft.Extensions.Logging немає вбудованого файлового провайдера, але можна написати свій: | |
| // Soccer.Infrastructure/Logging/FileLoggerProvider.cs | |
| public sealed class FileLoggerProvider : ILoggerProvider | |
| { | |
| private readonly StreamWriter _writer; | |
| private readonly object _lock = new(); | |
| public FileLoggerProvider(string path) | |
| { | |
| Directory.CreateDirectory(Path.GetDirectoryName(path)!); | |
| _writer = new StreamWriter(path, append: true) { AutoFlush = true }; | |
| } | |
| public ILogger CreateLogger(string categoryName) => | |
| new FileLogger(categoryName, _writer, _lock); | |
| public void Dispose() => _writer.Dispose(); | |
| } | |
| public sealed class FileLogger : ILogger | |
| { | |
| private readonly string _category; | |
| private readonly StreamWriter _writer; | |
| private readonly object _lock; | |
| public FileLogger(string category, StreamWriter writer, object @lock) | |
| { | |
| _category = category; | |
| _writer = writer; | |
| _lock = @lock; | |
| } | |
| public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null; | |
| public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information; | |
| public void Log<TState>( | |
| LogLevel logLevel, EventId eventId, TState state, | |
| Exception? exception, Func<TState, Exception?, string> formatter) | |
| { | |
| if (!IsEnabled(logLevel)) return; | |
| var line = $"{DateTime.UtcNow:O} [{logLevel}] {_category}: {formatter(state, exception)}"; | |
| if (exception != null) line += Environment.NewLine + exception; | |
| lock (_lock) _writer.WriteLine(line); | |
| } | |
| } | |
| // і потім реєстрація в Program.cs: | |
| // builder.Logging.AddProvider(new FileLoggerProvider("logs/app.log")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment