Repository navigation
Expand file tree
/
Copy pathFileLogger.cs
More file actions
159 lines (135 loc) · 4.67 KB
/
Copy pathFileLogger.cs
File metadata and controls
159 lines (135 loc) · 4.67 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
namespace RunCommandsService;
public class FileLogger : ILogger
{
private readonly string _name;
private readonly FileLoggerOptions _options;
private static readonly object _lock = new object();
private static DateTime _lastCleanupUtc = DateTime.MinValue;
public FileLogger(string name, FileLoggerOptions options)
{
_name = name;
_options = options;
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None && logLevel >= _options.MinLevel;
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
return;
var logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _options.LogDirectory);
var message = formatter(state, exception);
var formattedMessage = $"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} [{logLevel}] {message}";
if (exception != null)
{
formattedMessage += $"\nException: {exception}\nStackTrace: {exception.StackTrace}";
}
lock (_lock)
{
try
{
if (!Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
var todayStr = DateTime.UtcNow.ToString("yyyy-MM-dd");
var logFile = Path.Combine(logDirectory, $"log_{todayStr}.txt");
// Check size limit and rotate if needed
if (_options.FileSizeLimit > 0 && File.Exists(logFile))
{
var fi = new FileInfo(logFile);
if (fi.Length >= _options.FileSizeLimit)
{
var timestamp = DateTime.UtcNow.ToString("HHmmss_fff");
var rolled = Path.Combine(logDirectory, $"log_{todayStr}_{timestamp}.txt");
try
{
File.Move(logFile, rolled, overwrite: true);
}
catch
{
// If move fails, continue appending to current logFile
}
}
}
File.AppendAllText(logFile, formattedMessage + Environment.NewLine);
// Run cleanup periodically (at most once every 1 hour)
if ((DateTime.UtcNow - _lastCleanupUtc).TotalHours >= 1)
{
_lastCleanupUtc = DateTime.UtcNow;
CleanupOldLogsInternal(logDirectory);
}
}
catch
{
// Prevent logger from throwing to callers
}
}
}
private void CleanupOldLogsInternal(string logDirectory)
{
if (_options.RetainDays <= 0) return;
try
{
var cutoff = DateTime.UtcNow.AddDays(-_options.RetainDays);
var files = Directory.GetFiles(logDirectory, "log_*.txt")
.Select(f => new FileInfo(f))
.Where(f => f.LastWriteTimeUtc < cutoff);
foreach (var file in files)
{
try
{
file.Delete();
}
catch
{
// Ignore deletion errors for locked files
}
}
}
catch
{
// Ignore directory search errors
}
}
}
public class FileLoggerOptions
{
public string LogDirectory { get; set; } = "Logs";
public long FileSizeLimit { get; set; } = 10 * 1024 * 1024; // 10MB default
public int RetainDays { get; set; } = 30;
public LogLevel MinLevel { get; set; } = LogLevel.Information;
}
public class FileLoggerProvider : ILoggerProvider
{
private readonly FileLoggerOptions _options;
public FileLoggerProvider(FileLoggerOptions options)
{
_options = options;
}
public ILogger CreateLogger(string categoryName)
{
return new FileLogger(categoryName, _options);
}
public void Dispose()
{
}
}
public static class FileLoggerExtensions
{
public static ILoggingBuilder AddFileLogger(this ILoggingBuilder builder, Action<FileLoggerOptions> configure)
{
var options = new FileLoggerOptions();
configure(options);
builder.AddProvider(new FileLoggerProvider(options));
return builder;
}
}