SeemGen/Services/SimpleLogger.cs

82 lines
2.7 KiB
C#

using BLAIzor.Data;
using BLAIzor.Models;
using Microsoft.EntityFrameworkCore;
using System;
namespace BLAIzor.Services
{
public class SimpleLogger : ISimpleLogger
{
private readonly IDbContextFactory<ApplicationDbContext> _dbFactory;
private readonly IWebHostEnvironment _env;
private LogLevel _currentLevel = LogLevel.Info;
private bool _consoleEnabled = true;
public SimpleLogger(IDbContextFactory<ApplicationDbContext> dbFactory, IWebHostEnvironment env)
{
_dbFactory = dbFactory;
_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.IsDevelopment())
{
await using var db = await _dbFactory.CreateDbContextAsync();
log = new AppLog
{
Severity = level.ToString(),
Message = message,
Details = details,
Timestamp = DateTime.UtcNow
};
db.Logs.Add(log);
await db.SaveChangesAsync();
}
if (_consoleEnabled)
{
var color = Console.ForegroundColor;
Console.ForegroundColor = level switch
{
LogLevel.Info => ConsoleColor.Green,
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;
}
}
}
}