constrain file logger size

This commit is contained in:
Shaun Walker 2021-09-17 09:17:42 -04:00
parent b5bba1fd11
commit 406a15c5bd

View File

@ -45,6 +45,8 @@ namespace Oqtane.Infrastructure
} }
string folder = Path.Combine(_environment.ContentRootPath, "Content", "Log"); string folder = Path.Combine(_environment.ContentRootPath, "Content", "Log");
var filepath = Path.Combine(folder, "error.log");
long size = 0;
// ensure directory exists // ensure directory exists
if (!Directory.Exists(folder)) if (!Directory.Exists(folder))
@ -52,18 +54,25 @@ namespace Oqtane.Infrastructure
Directory.CreateDirectory(folder); Directory.CreateDirectory(folder);
} }
var filepath = Path.Combine(folder, "error.log"); if (File.Exists(filepath))
{
var fileinfo = new FileInfo(filepath);
size = fileinfo.Length;
// only retain an error log for the current day as it is intended for development purposes // only retain an error log for the current day as it is intended for development purposes
if (File.Exists(filepath) && File.GetLastWriteTimeUtc(filepath).Date < DateTime.UtcNow.Date) if (fileinfo.LastWriteTimeUtc.Date < DateTime.UtcNow.Date)
{ {
File.Delete(filepath); File.Delete(filepath);
} }
}
var logentry = string.Format("{0} [{1}] {2} {3}", "[" + DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss+00:00") + "]", logLevel.ToString(), formatter(state, exception), exception != null ? exception.StackTrace : ""); // do not allow the log to exceed 1 MB
if (size < 1000000)
{
try try
{ {
var logentry = string.Format("{0} [{1}] {2} {3}", "[" + DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss+00:00") + "]", logLevel.ToString(), formatter(state, exception), exception != null ? exception.StackTrace : "");
using (var streamWriter = new StreamWriter(filepath, true)) using (var streamWriter = new StreamWriter(filepath, true))
{ {
streamWriter.WriteLine(logentry); streamWriter.WriteLine(logentry);
@ -75,4 +84,5 @@ namespace Oqtane.Infrastructure
} }
} }
} }
}
} }