huorswords / Microsoft.Extensions.Logging.Log4Net.AspNetCore

Allows to configure Log4net as Microsoft Extensions Logging handler on any ASP.NET Core application. Original code proposal by @anuraj --> https://dotnetthoughts.net/how-to-use-log4net-with-aspnetcore-for-logging/
Apache License 2.0
249 stars 123 forks source link

How to add SMTPAppender #123

Closed Alvin-Prasla closed 2 years ago

Alvin-Prasla commented 2 years ago

Anyone knows how to use SMTPAppender for sending email when Error occurs. I had used below custom code but in .NET 6.0 I am unable to call custom AddLog4Net method. Ref: https://laptrinhx.com/c-net-core-3-0-and-log4net-with-email-alerts-3481421569/

Log4netExtensions.cs

namespace Utility.Log
{
    public static class Log4netExtensions
    {
        private static readonly string LOG_CONFIG_FILE = @"./Utility/Log/log4net.config";
        private static readonly string SMTP_APPENDER = @"/log4net/appender[@type='log4net.Helper.Core.SMTPAppender']";

        public static ILoggerFactory AddLog4Net(this ILoggerFactory factory)
        {
            factory.AddProvider(new Log4NetProvider(LOG_CONFIG_FILE, SMTP_APPENDER));
            return factory;
        }
    }

Program.cs

using Utility.Log;

var builder = WebApplication.CreateBuilder(args);

// Logging
builder.Logging.ClearProviders();
builder.Logging.AddLog4Net();  // <--- I need to call custom code added in Log4netExtensions.cs

Thanks

Alvin-Prasla commented 2 years ago

Figured out. Below worked for me. I added a method in Log4netExtensions.cs class

Log4netExtensions.cs

namespace Utility.Log
{
    public static class Log4netExtensions
    {
        private static readonly string LOG_CONFIG_FILE = @"./Utility/Log/log4net.config";
        private static readonly string SMTP_APPENDER = @"/log4net/appender[@type='log4net.Helper.Core.SMTPAppender']";

        public static ILoggerFactory AddLog4Net(this ILoggerFactory factory)
        {
            factory.AddProvider(new Log4NetProvider(LOG_CONFIG_FILE, SMTP_APPENDER));
            return factory;
        }

        public static ILoggingBuilder AddLog4Net(this ILoggingBuilder builder)
        {
            builder.Services.AddSingleton<ILoggerProvider>(new Log4NetProvider(LOG_CONFIG_FILE, SMTP_APPENDER));
            return builder;
        }
    }
}