1、新建一个LocalFileLogger的类
public class LocalFileLogger : ILogger { private readonly string categoryName; private readonly string basePath; public LocalFileLogger(string categoryName) { this.categoryName = categoryName; string[] fieldstrs = Enum.GetNames(typeof(LogLevel)); foreach (var item in fieldstrs) { basePath = Directory.GetCurrentDirectory().Replace("\\", "/") + "/Logs/"+$"/{item}/"; if (Directory.Exists(basePath) == false) { Directory.CreateDirectory(basePath); } } basePath = Directory.GetCurrentDirectory().Replace("\\", "/") + "/Logs/"; } public IDisposable BeginScope<TState>(TState state) { return default!; } public bool IsEnabled(LogLevel logLevel) { if (logLevel != LogLevel.None) { return true; } else { return false; } } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { if (IsEnabled(logLevel)) { if (state != null && state.ToString() != null) { var logContent = state.ToString(); if (logContent != null) { if (exception != null) { var logMsg = new { message = logContent, error = new { exception?.Source, exception?.Message, exception?.StackTrace } }; logContent = System.Text.Json.JsonSerializer.Serialize(logMsg); } var log = new { CreateTime = DateTime.UtcNow, Category = categoryName, Level = logLevel.ToString(), Content = logContent }; string logStr = System.Text.Json.JsonSerializer.Serialize(log); string logPath=string.Empty; switch (logLevel) { case LogLevel.Trace: logPath= basePath + "/Trace/"+ DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; case LogLevel.Debug: logPath = basePath + "/Debug/" + DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; case LogLevel.Information: logPath = basePath + "/Information/" + DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; case LogLevel.Warning: logPath = basePath + "/Warning/" + DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; case LogLevel.Error: logPath = basePath + "/Error/" + DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; case LogLevel.Critical: logPath = basePath + "/Critical/" + DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; case LogLevel.None: logPath = basePath + "/None/" + DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; default: logPath = basePath + "/Start/" + DateTime.Now.ToString("yyyyMMddHH") + ".log"; break; } File.AppendAllTextAsync(logPath, logStr + Environment.NewLine, System.Text.Encoding.UTF8); } } } } }
2、新建LocalFileLoggerProvider
public class LocalFileLoggerProvider : ILoggerProvider { private readonly System.Collections.Concurrent.ConcurrentDictionary<string, LocalFileLogger> loggers = new(); public ILogger CreateLogger(string categoryName) { return loggers.GetOrAdd(categoryName, new LocalFileLogger(categoryName)); } public void Dispose() { loggers.Clear(); GC.SuppressFinalize(this); } }
最后在Program注册服务
标签:log,LogLevel,basePath,logPath,DateTime,ToString,ILogger,net6,日志 From: https://www.cnblogs.com/lisghxfdfgh/p/18160482