Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logging to Console #2795

Closed
ErikEJ opened this issue Aug 7, 2015 · 4 comments
Closed

Logging to Console #2795

ErikEJ opened this issue Aug 7, 2015 · 4 comments

Comments

@ErikEJ
Copy link
Contributor

ErikEJ commented Aug 7, 2015

Is SQL statement logging to console available in the current api, and if yes, do yiu have a sample?

@ErikEJ ErikEJ changed the title Logging Logging to Console Aug 11, 2015
@rowanmiller
Copy link
Contributor

Hey Erik,

It's not very pretty yet... but here is a way to wire up the low level pieces to make it happen.

Compiled and tested on Beta 6... may need tweaks for latest dev code base.

using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Framework.Logging;
using System;
using System.IO;
using System.Linq;

namespace EFGetStarted.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                db.Database.EnsureCreated();

                db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                db.SaveChanges();

                db.Blogs.ToList();
            }
        }
    }

    public class BloggingContext : DbContext
    {
        public BloggingContext()
        {
            var loggerFactory = ((IAccessor<IServiceProvider>)this).GetService<ILoggerFactory>();
            loggerFactory.AddProvider(new DbLoggerProvider());
        }

        public DbSet<Blog> Blogs { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=LoggingDemo;Trusted_Connection=True;");
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }

    public class DbLoggerProvider : ILoggerProvider
    {
        private static readonly string[] _whitelist = new string[]
        {
                typeof(Microsoft.Data.Entity.Update.BatchExecutor).FullName,
                typeof(Microsoft.Data.Entity.Query.QueryContextFactory).FullName
        };

        public ILogger CreateLogger(string name)
        {
            if (_whitelist.Contains(name))
            {
                return new DbLogger();
            }

            return NullLogger.Instance;
        }
    }

    public class DbLogger : ILogger
    {
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
        {
            var message = $"{Environment.NewLine}{formatter(state, exception)}";
            File.AppendAllText(@"C:\temp\DatabaseLog.sql", message);
        }

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

        public IDisposable BeginScopeImpl(object state)
        {
            return null;
        }
    }

    public class NullLogger : ILogger
    {
        private static NullLogger _instance = new NullLogger();

        public static NullLogger Instance
        {
            get { return _instance; }
        }

        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
        { }

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

        public IDisposable BeginScopeImpl(object state)
        {
            return null;
        }
    }

}

@rowanmiller
Copy link
Contributor

BTW here is the work item to add something like Database.Log that we had in the past #1199

@ErikEJ
Copy link
Contributor Author

ErikEJ commented Aug 13, 2015

@rowanmiller Thanks, not exactly intuitive! It will come in very handy for a demo with the SQLCE provider (as no Profiler is available with that)

@ErikEJ
Copy link
Contributor Author

ErikEJ commented Aug 14, 2015

Thanks, added that to my providers (for the time being) as a LogToConsole() extension method on the DbContext

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants