SeemGen/Services/SimpleLogger.cs

71 lines
2.3 KiB
C#

using BLAIzor.Data;
using BLAIzor.Models;
using System;
namespace BLAIzor.Services
{
public class SimpleLogger : ISimpleLogger
{
private readonly ApplicationDbContext _dbContext;
private readonly IWebHostEnvironment _env;
private LogLevel _currentLevel = LogLevel.Info;
private bool _consoleEnabled = true;
public SimpleLogger(ApplicationDbContext dbContext, IWebHostEnvironment env)
{
_dbContext = dbContext;
_env = env;
}
public void SetLevel(LogLevel level) => _currentLevel = level;
public void EnableConsole(bool enabled) => _consoleEnabled = enabled;
public Task InfoAsync(string message, string? details = null) =>
LogAsync(LogLevel.Info, message, details);
public Task WarnAsync(string message, string? details = null) =>
LogAsync(LogLevel.Warning, message, details);
public Task ErrorAsync(string message, string? details = null) =>
LogAsync(LogLevel.Error, message, details);
private async Task LogAsync(LogLevel level, string message, string? details)
{
if (level < _currentLevel || _currentLevel == LogLevel.None)
return;
var log = new AppLog
{
Severity = level.ToString(),
Message = message,
Details = details,
Timestamp = DateTime.UtcNow
};
if (_env.IsProduction())
{
_dbContext.Logs.Add(log);
await _dbContext.SaveChangesAsync();
}
if (_consoleEnabled)
{
var color = Console.ForegroundColor;
Console.ForegroundColor = level switch
{
LogLevel.Info => ConsoleColor.Gray,
LogLevel.Warning => ConsoleColor.Yellow,
LogLevel.Error => ConsoleColor.Red,
_ => ConsoleColor.White
};
Console.WriteLine($"[{log.Timestamp:HH:mm:ss}] [{log.Severity}] {log.Message}");
if (!string.IsNullOrWhiteSpace(details))
Console.WriteLine($" > {details}");
Console.ForegroundColor = color;
}
}
}
}