【问题标题】:adding nlog to .net core 3.0将 nlog 添加到 .net core 3.0
【发布时间】:2019-12-10 18:24:32
【问题描述】:

将 nlog 添加到 .net core 3.0 应用程序会导致

“IServiceCollection”不包含对 'ConfigureLoggerService' 并且没有可访问的扩展方法 'ConfigureLoggerService' 接受类型的第一个参数 可以找到“IServiceCollection”(您是否缺少 using 指令 还是程序集参考?)

对于 Nuget 我有

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

在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();
        }

这是我的 csproj 文件

<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>

【问题讨论】:

  • 您是否包含正确的命名空间?
  • 你有一个主要的NLog 包吗?它是NLog.Extensions.Logging 的一部分,但他们的GitHub 说的是NLog 包。请分享您的csproj 文件
  • 刚安装,没用
  • 我包含了我的 csproj 文件
  • ConfigureLoggerService 不是 NLog 的方法。认为您正在使用一些损坏的教程。试试看这里:github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

标签: c# asp.net-core-mvc nuget nlog


【解决方案1】:

如果你关注这个tutorial,别忘了添加这个方法扩展

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

因为你在这一行调用它

services.ConfigureLoggerService();

另外,您可以考虑将其删除,因为您正在使用接口ILoggerManager 注册此服务LoggerService

【讨论】:

  • 我删除了它(services.ConfigureLoggerServices()),它记录得很好。谢谢。
【解决方案2】:

这是我的步骤:

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

使用以下类创建一个扩展目录

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());
                        }
                    });
                });
            }
    }

在 Startup.cs 添加以下行

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

在 startup.cs 添加以下单例

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

在logs目录下添加如下类

public class ApplicationLogs
    {
    }

在控制器中抛出异常

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多