ILogger Provider Error: Microsoft.Extensions.Logging.File - Need Assistance

79 views Asked by At

The error: Error CS1061 'ILoggerFactory' does not contain a definition for 'AddFile' and no accessible extension method 'AddFile' accepting a first argument of type 'ILoggerFactory' could be found (are you missing a using directive or an assembly reference?)

My code:

using Microsoft.Extensions.Logging;

namespace Css.Test.Infrastructure.Logger

{
    
    public class MyLogger : ILoggerService
    {
        private readonly ILogger _logger;

        
        public MyLogger(ILoggerFactory loggerFactory, Type type)
        {
            
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }
            
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

           
            var name = type.Name;
            var categoryName = $"{type.Namespace}.{nameof(MyLogger)}.{name}";

            
            loggerFactory.AddFile(Path.Combine(Directory.GetCurrentDirectory(), "mylog.txt"));

            
            _logger = loggerFactory.CreateLogger(categoryName);
        }

        
        public void LogError(Exception exception, string? instance = null)
        {
            
            _logger.LogError(exception, $"Instance: {instance ?? "Default"}");
        }

        
        public void LogWarning(string message, string? instance = null)
        {
            
            _logger.LogWarning($"Message: {message}, Instance: {instance ?? "Default"}");
        }

        
        public void LogTrace(string message, string? instance = null)
        {
            
            _logger.LogTrace($"Message: {message}, Instance: {instance ?? "Default"}");
        }

        
        public void LogInformation(string message, string? instance = null)
        {
           
            _logger.LogInformation($"Message: {message}, Instance: {instance ?? "Default"}");
        }
    }
}

I want to use ILogger from Microsoft.Extensions.Logging, and I added the solution Install-Package Microsoft.Extensions.Logging.File to add file logging, but the error persists.

1

There are 1 answers

2
Suman jha On

The AddFile method is not a part of Microsoft.Extensions.Logging package, but it's a part of the Serilog.Extensions.Logging.File try using that and it should resolve the issue. You have to install the package and include it inside of the the code:

using Serilog.Extensions.Logging.File.