Bryan Dellinger
Bryan Dellinger

Reputation: 5304

adding nlog to .net core 3.0

adding nlog to .net core 3.0 application results in

'IServiceCollection' does not contain a definition for 'ConfigureLoggerService' and no accessible extension method 'ConfigureLoggerService' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

for Nuget I have

NLog.Extensions.Logging v1.6.1
NLog.Web.AspNetCore v4.9.0

in startup.cs

 public Startup(IConfiguration config)
        {
            LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
            Configuration = config;
        }

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
            services.AddMvc();
            services.AddTransient<ICwopaAgencyFileRepository, CwopaAgencyFileRepository>();
            services.AddTransient<ICurrentUserRepository, CurrentUserRepository>();
            services.AddTransient<IUserRepository, UserRepository>();
            services.AddTransient<IRevenueReceivedRepository, RevenueReceivedRepository>();
            services.AddTransient<ILesseeRepository, LesseeRepository>();
            services.AddTransient<ITractLesseeJunctionRepository, TractLesseeJunctionRepository>();
            services.AddTransient<IPadRepository, PadRepository>();
            services.AddTransient<IWellRepository, WellRepository>();
            services.AddTransient<IWellOperarationRepository, WellOperationRepository>();
            services.AddTransient<IRoyaltyRepository, RoyaltyRepository>();
            services.AddTransient<IRoyaltyAdjustmentCardViewModelRepository, RoyaltyAdjustmentCardViewModelRepository>();
            services.AddSingleton<ILoggerManager, LoggerService>();
            string conString = Configuration["ConnectionStrings:DefaultConnection"];
            services.AddDbContext<DataContext>(options =>
                options.UseSqlServer(conString));
            services.ConfigureLoggerService();
            services.AddMvc(option => option.EnableEndpointRouting = false);
            services.AddMemoryCache();
            services.AddSession();
        }

here is my csproj file

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
    <PackageReference Include="NLog" Version="4.6.8" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Migrations\" />
  </ItemGroup>

</Project>

Upvotes: 1

Views: 2214

Answers (2)

Here are my steps:

1. Create a static class called ExceptionMiddlewareExtensions
2. Within ExceptionMiddlewareExtensions create a static function called ConfigureExpectionHandler.  
3. In the start.cs - public void Configure - add the ILogger interface
4. In the start.cs, setup the dependency injection for ILogger, in ConfigureServices(IServiceCollection services).  Create a serviceProvider then GetService based on ILogger<MyClassName>>(). Create a service singleton(type(ILogger),logger)
5. In the controller code, throw new Exception with message upon error condition

Create an Extension directory with the following class

public static class ExceptionMiddlewareExtensions
    {
        //public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger)
        public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILogger logger)
        {
                app.UseExceptionHandler(appError =>
                {
                    appError.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = "application/json";
                        var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                        if (contextFeature != null)
                        {
                            logger.LogError($"Something went wrong: {contextFeature.Error}");
                            await context.Response.WriteAsync(new ErrorDetails()
                            {
                                StatusCode = context.Response.StatusCode,
                                Message = String.Format("Error: {0}", contextFeature.Error.Message)
                            }.ToString());
                        }
                    });
                });
            }
    }

In Startup.cs added the following line

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger logger)
        {
            app.ConfigureExceptionHandler(logger);
        }

In startup.cs add the following singleton

 public void ConfigureServices(IServiceCollection services)
        {
            var serviceProvider = services.BuildServiceProvider();
            var logger = serviceProvider.GetService<ILogger<ApplicationLogs>>();
            services.AddSingleton(typeof(ILogger), logger);
        }

in logs directory add the following class

public class ApplicationLogs
    {
    }

In the controller throw the Exception

public async Task<IActionResult> AddLoginView([FromBody] LoginView param)
{
    if (error_condition)
    {
        throw new Exception("The user error messages");
    }
}

Upvotes: -1

Jesus Santander
Jesus Santander

Reputation: 313

if you're following this tutorial, don't forget add this method extension

public static void ConfigureLoggerService(this IServiceCollection services)
{
    services.AddSingleton<ILoggerManager, LoggerManager>();
}

because you're calling it in this line

services.ConfigureLoggerService();

Also, you can considere removing it, because you're registering this service LoggerService with the interface ILoggerManager.

Upvotes: 5

Related Questions