Kitpymes.Core.Logger

Logeo de errores para multiples proveedores

Build Status NuGet Status NuGet Download License Size Repo Last Commit

📋 Requerimientos

🔧 Instalación

Logger se puede instalar usando el administrador de paquetes Nuget o CLI dotnet.

Nuget

Install-Package Kitpymes.Core.Logger

CLI dotnet

dotnet add package Kitpymes.Core.Logger

⌨️ Código

public interface ILoggerService
{
    ILogger CreateLogger(string title);

    ILogger CreateLogger<TTitle>();
}
public interface ILogger
{
    ILogger Trace(string message);

	ILogger Trace(string message, object data);

	ILogger Debug(string message);

	ILogger Debug(string message, object data);

	ILogger Info(string message);

	ILogger Info(string message, object data);

	ILogger Info(string eventName, string templateMessage, params object[] propertyValues);

	ILogger Error(string message);

	ILogger Error(string message, object data);

	ILogger Error(string eventName, string templateMessage, params object[] propertyValues);

	ILogger Error(Exception exception);
}
public enum LoggerLevel
{
    Trace = 0,

    Debug = 1,

    Info = 2,

    Error = 3,
}
public enum LoggerFileInterval
{
    Infinite = 0,

    Year = 1,

    Month = 2,

    Day = 3,

    Hour = 4,

    Minute = 5,
}
{
    "LoggerSettings": {
        "SerilogSettings": {
            "Console": {
                "Enabled": null, // (bool) Default: false
                "MinimumLevel": null, // (string) Default: "Info" | Options: Trace, Debug, Info, Error
                "OutputTemplate": null // (string) Default: "{SourceContext}{NewLine}{Timestamp:HH:mm:ss:ff} [{Level:u3}] {Message:lj}{NewLine}"
            },
            "File": {
                "Enabled": null, // (bool) Default: false
                "FilePath": null, // (string) Default: "Logs\\.log"
                "Interval": null, // (string) Default: "Day" | Options: Infinite, Year, Month, Day, Hour, Minute
                "MinimumLevel": null // (string) Default: "Error" | Options: Info, Error
            },
            "Email": {
                "Enabled": null, // (bool) Default: false
                "UserName": null, // (string)
                "Password": null, // (string)
                "Server": null, // (string)
                "From": null, // (string)
                "To": null, // (string)
                "EnableSsl": null, // (bool) Default: true
                "Port": null, // (int) Default: 465
                "Subject": null, // (string) Default: "Log Error"
				"IsBodyHtml": null, // (bool) Default: false
                "MinimumLevel": null, // (string) Default: "Error" | Options: Info, Error,
                "OutputTemplate": null // (string) Default: "SourceContext: {SourceContext} | MachineName: {MachineName} | Process: {Process} | Thread: {Thread} => {NewLine}{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u}] {Message:lj}{NewLine}"
            }
        }
    }
}

Para utilizarlo con inyección de dependencia

Opción 1: configuración desde el appsetings

public void ConfigureServices(IServiceCollection services)
{
    services.LoadLogger(Configuration);
}

Opción 2: configuración manual

public void ConfigureServices(IServiceCollection services)
{
    services.LoadLogger(loggers =>
    {
        loggers.UseSerilog(serilog =>
        {
		    serilog
			    .AddConsole()
			    .AddFile()
			    .AddEmail
			    (
				    userName: "admin@app.com", 
				    password: "password",
				    server: "smtp.gmail.com",
				    from: "admin@app.com",
				    to: "error@app.com"
			    );
        });
    });
}

Ejemplo

using Kitpymes.Core.Logger.Abstractions;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Tests.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        //private readonly ILogger<WeatherForecastController> _logger;

        //public WeatherForecastController(ILogger<WeatherForecastController> logger)
        //{
        //    _logger = logger;
        //}

        private ILogger Logger { get; }

        public WeatherForecastController(ILoggerService logger)
        {
            Logger = logger.CreateLogger<WeatherForecastController>();
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            // Test
            Logger
               .Info("Get Summaries")
               .Info("Summary 1", Summaries[0])
               .Info("Summary 2", Summaries[1])
               .Info("Summary 3", Summaries[2])
               .Info("All Summaries", Summaries);

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

Para utilizarlo de forma estatica

Option 1

var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var logger = Log.UseSerilog(configuration).CreateLogger<Program>();

Option 2

var logger = Log.UseSerilog(serilog => 
{
	serilog
		.AddConsole()
		.AddFile()
		.AddEmail
		(
			userName: "admin@app.com", 
			password: "password",
			server: "smtp.gmail.com",
			from: "admin@app.com",
			to: "error@app.com"
		);
})
.CreateLogger<Program>();

Ejemplo

using Kitpymes.Core.Logger;
using Kitpymes.Core.Logger.Abstractions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;

namespace Tests.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var logger = Log.UseSerilog(serilog =>
            {
                serilog
                    .AddConsole
                    (
                        
                    )
                    .AddFile
                    (
                        minimumLevel: LoggerLevel.Info
                    )
                    .AddEmail
                    (
                        userName: "admin@app.com",
                        password: "password",
                        server: "smtp.gmail.com",
                        from: "admin@app.com",
                        to: "error@app.com"
                    );
            })
           .CreateLogger<Program>();

            try
            {
                logger.Info("Init Host...");

                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                logger.Error(ex);

                throw ex;
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                // (OPCIONAL)
                .ConfigureLogging(providers => providers.ClearProviders())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

🔩 Resultados

Resultado en la consola

Resultado en la consola

Resultado en los archivos

Resultado en los archivos

⚙️ Pruebas Unitarias

Cada proveedor de logeo de errores tiene su proyecto de test, se ejecutan desde el “Explorador de pruebas”

Tests

🛠️ Construido con

✒️ Autores

📄 Licencia

🎁 Gratitud


Kitpymes 😊