14

I am in the middle of studying the ASP.NET Core, and I have implemented logging with a file system successfully, but how about implementing logging feature with a database solution. How to pass EF context to my 'LoggerDatabaseProvider', and still have those two decoupled? The code below should clear some upfront questions:

Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddEntityFramework()
            .AddEntityFrameworkSqlServer()
            .AddDbContext<WorldContext>();

        services.AddTransient<WorldContextSeedData>();


        services.AddScoped<IWorldRepository, WorldRepository>();
        //this one adds service with Dependency Injection that calls 'MyLogger' constructor with two parameters, instead the default one parametereless constructor. 
        services.AddScoped<ILogger, LoggerFileProvider.Logger>(provider => new LoggerFileProvider.Logger("CustomErrors", Startup.Configuration["Data:LogFilePath"]));
        //services.AddScoped<ILogger, LoggerDatabaseProvider.Logger>(provider => new LoggerDatabaseProvider.Logger("CustomErrors"));
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WorldContextSeedData seeder)
    {
        string basePath = Startup.Configuration["Data:LogFilePath"];

        loggerFactory.AddProvider(new LoggerFileProvider(basePath));
        loggerFactory.AddProvider(new LoggerDatabaseProvider());

        app.UseStaticFiles();

        app.UseMvc(config =>
        {
            config.MapRoute(
                name: "Default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "App", action = "index" }
                );
        });

        seeder.EnsureSeedData();
    }

Here is my successfully implemented logger with text file:

public class LoggerFileProvider : ILoggerProvider
{
    private readonly string _logFilePath;

    public LoggerFileProvider(string logFilePath)
    {
        _logFilePath = logFilePath;
    }

    public ILogger CreateLogger(string categoryName)
    {
        return new Logger(categoryName, _logFilePath);
    }

    public void Dispose()
    {
    }

    public class Logger : ILogger
    {
        private readonly string _categoryName;
        private readonly string _path;

        public Logger(string categoryName, string logFilePath)
        {
            _path = logFilePath;
            _categoryName = categoryName;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            try
            {
                RecordMsg(logLevel, eventId, state, exception, formatter);
            }
            catch (Exception ex)
            {
                //this is being used in case of error 'the process cannot access the file because it is being used by another process', could not find a better way to resolve the issue
                RecordMsg(logLevel, eventId, state, exception, formatter);
            }
        }

        private void RecordMsg<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            string msg = $"{logLevel} :: {_categoryName} :: {formatter(state, exception)} :: username :: {DateTime.Now}";

            using (var writer = File.AppendText(_path))
            {
                writer.WriteLine(msg);
            }
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return new NoopDisposable();
        }

        private class NoopDisposable : IDisposable
        {
            public void Dispose()
            {
            }
        }
    }
}

But how about the very similar implementation, but with database solution? My WorldContext is utilized by EF to communicate with database, but if it would be easier I could utilize my repository. I would like to keep the context/repository decoupled from 'LoggerDatabaseProvider' that I am about to implement, so I could utilize it in other projects.

1
  • Why not use a DB logging provider that almost every logging framework out there has?
    – Brad
    Jul 28, 2016 at 2:03

2 Answers 2

21

Per specification, here is how I managed to implemented it, just in case someone would look for similar solution.

'Startup.cs':

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddEntityFramework()
        .AddEntityFrameworkSqlServer()
        .AddDbContext<WorldContext>();

    services.AddLogging();

    services.AddTransient<WorldContextSeedData>();

    services.AddScoped<IMailService, MailServiceDebug>();
    services.AddScoped<IWorldRepository, WorldRepository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WorldContextSeedData seeder, IWorldRepository worldRepo)
{
    string basePath = Startup.Configuration["Data:LogFilePath"];

    loggerFactory.AddProvider(new LoggerFileProvider(basePath));
    loggerFactory.AddProvider(new LoggerDatabaseProvider(worldRepo));

    app.UseStaticFiles();

    app.UseMvc(config =>
    {
        config.MapRoute(
            name: "Default",
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "App", action = "index" }
            );
    });

    seeder.EnsureSeedData();
}

Custom 'LoggerFileProvider.cs':

public class LoggerFileProvider : ILoggerProvider
{
    private readonly string _logFilePath;

    public LoggerFileProvider(string logFilePath)
    {
        _logFilePath = logFilePath;
    }

    public ILogger CreateLogger(string categoryName)
    {
        return new Logger(categoryName, _logFilePath);
    }

    public void Dispose()
    {
    }

    public class Logger : ILogger
    {
        private readonly string _categoryName;
        private readonly string _path;

        public Logger(string categoryName, string logFilePath)
        {
            _path = logFilePath;
            _categoryName = categoryName;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            try
            {
                RecordMsg(logLevel, eventId, state, exception, formatter);
            }
            catch (Exception ex)
            {
                //this is being used in case of error 'the process cannot access the file because it is being used by another process', could not find a better way to resolve the issue
                RecordMsg(logLevel, eventId, state, exception, formatter);
            }
        }

        private void RecordMsg<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            string msg = $"{logLevel} :: {_categoryName} :: {formatter(state, exception)} :: username :: {DateTime.Now}";

            using (var writer = File.AppendText(_path))
            {
                writer.WriteLine(msg);
            }
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return new NoopDisposable();
        }

        private class NoopDisposable : IDisposable
        {
            public void Dispose()
            {
            }
        }
    }
}

Custom 'LoggerDatabaseProvider.cs':

public class LoggerDatabaseProvider : ILoggerProvider
{
    private IWorldRepository _repo;

    public LoggerDatabaseProvider(IWorldRepository repo)
    {
        _repo = repo;
    }

    public ILogger CreateLogger(string categoryName)
    {
        return new Logger(categoryName, _repo);
    }

    public void Dispose()
    {
    }

    public class Logger : ILogger
    {
        private readonly string _categoryName;
        private readonly IWorldRepository _repo;

        public Logger(string categoryName, IWorldRepository repo)
        {
            _repo = repo;
            _categoryName = categoryName;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (logLevel == LogLevel.Critical || logLevel == LogLevel.Error || logLevel == LogLevel.Warning)
                RecordMsg(logLevel, eventId, state, exception, formatter);
        }

        private void RecordMsg<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            _repo.Log(new Log
            {
                LogLevel = logLevel.ToString(),
                CategoryName = _categoryName,
                Msg = formatter(state, exception),
                User = "username",
                Timestamp = DateTime.Now
            });
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return new NoopDisposable();
        }

        private class NoopDisposable : IDisposable
        {
            public void Dispose()
            {
            }
        }
    }
}
4
  • 2
    wow, I didn't know you could just add another parameter to Configure and DI will provide the value for you.
    – t3chb0t
    Aug 10, 2017 at 9:59
  • With Dependency Injection you can provide any number of Interface parameters in Configure, and those will be replaced with corresponding classes configured in ConfigureServices
    – lucas
    Aug 12, 2017 at 7:28
  • Lucas how did you set up your IWorldRepository? Is it a custom log object that you have contained in there?
    – JoeyD
    Nov 9, 2020 at 18:46
  • The practice is good. But something I don't know is, it is better if every logger has one individual database connection? Or another case, if we save the log into some MQ, it is better to share the MQ connection between the loggers, or one logger one connection. If we share the the connection between the threads, I don't know whether we need the lock. Update: To MQ, it is solved. Usually the MQ connection is thread safe, but the channel is not, at least it is true in RabbitMQ.
    – Bingoabs
    Apr 23, 2021 at 7:29
0

I have implemented database logging as well as a web ui for viewing the log.

My currently working example can use EF or it can use NoDb (file system storage). Note that there are other implementations of my ILogRepository in the github repo for other db platforms but those are not currently up to date or working, only the EF and NoDb ones are working right now.

You can see my DBLoggerProvider requires that I pass in an implementation of my ILogRepository into it's constructor

My EF implementation of ILogRepository is here

A few important points for using EF for logging, normally DbContext is scoped per request but logging can happen multiple times per request and errors can happen when you call SaveChanges on the context multiple times during a request. To solve this I don't use the injected DbContext for adding to the log, instead I inject the DbContextOptions so I can new up a transient DbContext each time I add to the log

using (var context = new LoggingDbContext(dbContextOptions))
{
    context.Add(logItem);
    context.SaveChanges();
}

also EF logs a lot of stuff internally and you need to filter that out so that adding to the log doesn't generate more log items as that will become an infinite loop of logging. This poses a bit of a problem if you were interested in seeing things logged by EF from elsewhere and I have not figured out a solution for that other than use more than one logger, ie use the console log to see things logged by EF but don't let EF logging log any EF related stuff.

If you want to see an app that uses this logger, especially you will want to see the startup code and note that the implementation of ILogRepository must be wired up in ConfigureServices, then add it to the method signature of Configure so it will be injected into that method allowing you to pass it into the DbLoggerProvider

So my project does decouple the repository from the DbLogProvider and should be a good example for you to look at in making your own logging implementation or you could use mine since it is open source and ready for use.

1
  • 3
    My EF implementation of ILogRepository is here - broken link Mar 13, 2017 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.